Keras InvalidArgumentError与Model.Fit()

时间:2019-06-14 20:34:18

标签: python python-3.x tensorflow keras

我试图在顺序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)且不将其分解为要点和标签时,一切正常。任何见解将不胜感激!

1 个答案:

答案 0 :(得分:1)

根据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:目标数据。像输入数据x一样,它可以是Numpy数组或TensorFlow张量。它应该与x一致(您不能有Numpy输入和张量目标,或者相反)。 如果x是数据集,数据集迭代器,生成器或keras.utils.Sequence实例,则不应指定y(因为将从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)适应当前要解决的问题。