我是 TensorFlow 的新手,我只是在进行一些实验。我正在尝试使用自定义层构建一个(非常)简单的模型,并使用最大似然对其进行拟合。 (我目前尝试使用该软件包的方式可能并不完全符合预期,但似乎 - 从理论上讲 - 它应该仍然有效。)
我正在尝试运行此代码:
import tensorflow as tf
from tensorflow import keras
import numpy as np
import pandas as pd
leng = 10000
realised = np.random.normal(1, 2, leng).astype(dtype="float32")
feat = np.ones(leng, dtype="float32")
df = pd.DataFrame({'x1' : feat, 'target' : realised})
target = df.pop('target')
dataset = tf.data.Dataset.from_tensor_slices((df.values, target.values))
class Gauss(keras.layers.Layer):
def __init__(self, realised, units=32, input_dim=32):
super(Gauss, self).__init__()
w_init = tf.random_normal_initializer()
self.w = tf.Variable(
initial_value=w_init(shape=(input_dim, units), dtype="float32"),
trainable=True,
)
s_init = tf.ones_initializer()
self.s = tf.Variable(
initial_value=s_init(shape=(units,), dtype="float32"), trainable=True
)
self.realised = tf.Variable(
initial_value=realised, dtype="float32", trainable=False
)
def call(self, inputs):
diff = tf.square(
tf.subtract(
tf.matmul(inputs, self.w), self.realised))
pi2 = tf.constant((2*np.pi)**0.5, dtype="float32")
return tf.divide(
tf.math.exp(
tf.divide(
-diff, tf.multiply(
2.0, tf.square(tf.math.log(1 + tf.math.exp(self.s)))))),
tf.math.log(1 + tf.math.exp(self.s))*pi2)
@tf.function()
def loss_fn(output, dummy_var):
return -tf.reduce_sum(tf.math.log(output))
def get_compiled_model():
model = tf.keras.Sequential([
Gauss(tf.constant(target.values, shape=(leng, 1), dtype="float32"), 1, 1)
])
model.compile(optimizer='adam',
loss=loss_fn,
metrics=['accuracy'])
return model
model = get_compiled_model()
model.fit(dataset, epochs=3, batch_size=16)
但是,当我尝试编译模型时,我从最后一行收到了 ValueError。这是完整的错误:
Traceback (most recent call last):
File "<ipython-input-28-c3a2ecd18f95>", line 59, in <module>
model.fit(dataset, epochs=3, batch_size=16)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 108, in _method_wrapper
return method(self, *args, **kwargs)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1098, in fit
tmp_logs = train_function(iterator)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 780, in __call__
result = self._call(*args, **kwds)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 823, in _call
self._initialize(args, kwds, add_initializers_to=initializers)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 697, in _initialize
*args, **kwds))
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 2855, in _get_concrete_function_internal_garbage_collected
graph_function, _, _ = self._maybe_define_function(args, kwargs)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 3213, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\function.py", line 3075, in _create_graph_function
capture_by_value=self._capture_by_value),
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py", line 986, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\eager\def_function.py", line 600, in wrapped_fn
return weak_wrapped_fn().__wrapped__(*args, **kwds)
File "C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py", line 973, in wrapper
raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:806 train_function *
return step_function(self, iterator)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:796 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1211 run
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2585 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2945 _call_for_each_replica
return fn(*args, **kwargs)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:789 run_step **
outputs = model.train_step(data)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py:749 train_step
y, y_pred, sample_weight, regularization_losses=self.losses)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\compile_utils.py:212 __call__
batch_dim = array_ops.shape(y_t)[0]
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\util\dispatch.py:201 wrapper
return target(*args, **kwargs)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py:1024 _slice_helper
name=name)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\util\dispatch.py:201 wrapper
return target(*args, **kwargs)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py:1196 strided_slice
shrink_axis_mask=shrink_axis_mask)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py:10352 strided_slice
shrink_axis_mask=shrink_axis_mask, name=name)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:744 _apply_op_helper
attrs=attr_protos, op_def=op_def)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\func_graph.py:593 _create_op_internal
compute_device)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py:3485 _create_op_internal
op_def=op_def)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py:1975 __init__
control_input_ops, op_def)
C:\Users\FaberMR\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py:1815 _create_c_op
raise ValueError(str(e))
ValueError: slice index 0 of dimension 0 out of bounds. for '{{node strided_slice}} = StridedSlice[Index=DT_INT32, T=DT_INT32, begin_mask=0, ellipsis_mask=0, end_mask=0, new_axis_mask=0, shrink_axis_mask=1](Shape, strided_slice/stack, strided_slice/stack_1, strided_slice/stack_2)' with input shapes: [0], [1], [1], [1] and with computed input tensors: input[1] = <0>, input[2] = <1>, input[3] = <1>.
我正在 Windows 操作系统上工作,在 Spyder 4.1.5 中使用 Python 3.7.4。使用 TensorFlow 2.3.1。任何建议将不胜感激。