gpt4 book ai didi

python - Keras InvalidArgumentError 与 Model.Fit()

转载 作者:行者123 更新时间:2023-12-01 07:42:55 24 4
gpt4 key购买 nike

我尝试在顺序 Keras 模型上调用 model.fit(),但收到此错误:

---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
<ipython-input-30-3fc420144082> in <module>
15 return model
16
---> 17 trained_model = build_model()

<ipython-input-30-3fc420144082> in build_model()
10 # fit model
11 es = tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=1)
---> 12 model.fit(train_data[0], train_data[1], epochs=100,verbose=1)
13 # validation_data = (val_data[0], val_data[1])
14 print(model.summary())

~/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, max_queue_size, workers, use_multiprocessing, **kwargs)
878 initial_epoch=initial_epoch,
879 steps_per_epoch=steps_per_epoch,
--> 880 validation_steps=validation_steps)
881
882 def evaluate(self,

~/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_arrays.py in model_iteration(model, inputs, targets, sample_weights, batch_size, epochs, verbose, callbacks, val_inputs, val_targets, val_sample_weights, shuffle, initial_epoch, steps_per_epoch, validation_steps, mode, validation_in_fit, **kwargs)
327
328 # Get outputs.
--> 329 batch_outs = f(ins_batch)
330 if not isinstance(batch_outs, list):
331 batch_outs = [batch_outs]

~/.local/lib/python3.6/site-packages/tensorflow/python/keras/backend.py in __call__(self, inputs)
3074
3075 fetched = self._callable_fn(*array_vals,
-> 3076 run_metadata=self.run_metadata)
3077 self._call_fetch_callbacks(fetched[-len(self._fetches):])
3078 return nest.pack_sequence_as(self._outputs_structure,

~/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in __call__(self, *args, **kwargs)
1437 ret = tf_session.TF_SessionRunCallable(
1438 self._session._session, self._handle, args, status,
-> 1439 run_metadata_ptr)
1440 if run_metadata:
1441 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/.local/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg)
526 None, None,
527 compat.as_text(c_api.TF_Message(self.status.status)),
--> 528 c_api.TF_GetCode(self.status.status))
529 # Delete the underlying status object from memory otherwise it stays alive
530 # as there is a reference to status from this from the traceback due to

InvalidArgumentError: data[0].shape = [3] does not start with indices[0].shape = [2]
[[{{node training_40/Adam/gradients/loss_21/dense_21_loss/MeanSquaredError/Mean_grad/DynamicStitch}}]]

我创建了一组训练点,每个 1 x 3,由 train_data[0] 调用,以及一组训练标签,每个 1x1 由 train_data[1] 调用。这是我用来构建模型的代码:

def build_model():
'''
Function to build a LSTM RNN model that takes in quantitiy, converted week; outputs predicted price
'''
# define model
model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(128, activation='relu', input_shape=(num_steps,num_features*input_size)))
model.add(tf.keras.layers.Dense(input_size))
model.compile(optimizer='adam', loss='mse')
# fit model
es = tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=1)
model.fit(train_data[0], train_data[1], epochs=100,verbose=1)
# validation_data = (val_data[0], val_data[1])
print(model.summary())
return model

trained_model = build_model()

我不确定为什么,但是当我调用 model.fit(train_data, epochs = 100) 并且不将其分解为点和标签时,一切正常。任何见解将不胜感激!

最佳答案

根据tensorflow的tf.keras.models.Model文档,这是有意义的:

https://www.tensorflow.org/api_docs/python/tf/keras/models/Model#fit

 fit(x=None, y=None, batch_size=None, epochs=1, ...)

它精确:

y: Target data. Like the input data x, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with x (you cannot have Numpy inputs and tensor targets, or inversely). If x is a dataset, dataset iterator, generator, or keras.utils.Sequence instance, y should not be specified (since targets will be obtained from x).

你的lstm是一个顺序模型,我猜你准备了train_data类型为keras.utils.Sequence?

另请注意您的 TensorFlow 版本,上面的文档链接适用于 r1.13

编辑:

尝试以这种方式准备数据集:

features_type = tf.float32
target_type = tf.int32

train_dataset = tf.data.Dataset.from_tensor_slices(
tf.cast(train_data[0].values, features_type),
tf.cast(train_data[1].values, target_type)
)

model.fit(train_dataset, epochs=100, verbose=1)

确保根据您当前要解决的问题调整 features_type(所有功能都转换为 float32)和 target_type(用于分类的 int32)。

关于python - Keras InvalidArgumentError 与 Model.Fit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56604825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com