[英]Shape error when training a model with Keras (Tensorflow)
我是機器學習的新手,並且發現很難使用Keras進行TensorFlow的模型訓練。 我正在嘗試使用TensorFlow進行時間序列預測。 我有一個生成器功能,可以生成訓練數據和標簽:
x_batch, y_batch = next(generator)
print(x_batch.shape)
print(y_batch.shape)
(256, 60, 9)
(256, 60, 3)
我通過以下方式構建模型:
model = Sequential()
model.add(LSTM(128, input_shape=(None, num_x_signals,), return_sequences=True))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(LSTM(128, return_sequences=True))
model.add(Dropout(0.1))
model.add(BatchNormalization())
model.add(LSTM(128))
model.add(Dropout(0.2))
model.add(BatchNormalization())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_y_signals, activation='relu'))
opt = tf.keras.optimizers.Adam(lr=0.001, decay=1e-6)
# Compile model
model.compile(
loss='sparse_categorical_crossentropy',
optimizer=opt,
metrics=['accuracy']
)
我的模型摘要如下所示:
model.summary()
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm_19 (LSTM) (None, None, 128) 70656
_________________________________________________________________
dropout_23 (Dropout) (None, None, 128) 0
_________________________________________________________________
batch_normalization_18 (Batc (None, None, 128) 512
_________________________________________________________________
lstm_20 (LSTM) (None, None, 128) 131584
_________________________________________________________________
dropout_24 (Dropout) (None, None, 128) 0
_________________________________________________________________
batch_normalization_19 (Batc (None, None, 128) 512
_________________________________________________________________
lstm_21 (LSTM) (None, 128) 131584
_________________________________________________________________
dropout_25 (Dropout) (None, 128) 0
_________________________________________________________________
batch_normalization_20 (Batc (None, 128) 512
_________________________________________________________________
dense_12 (Dense) (None, 32) 4128
_________________________________________________________________
dropout_26 (Dropout) (None, 32) 0
_________________________________________________________________
dense_13 (Dense) (None, 3) 99
=================================================================
Total params: 339,587
Trainable params: 338,819
Non-trainable params: 768
這是我嘗試訓練模型的方式:
tensorboard = TensorBoard(log_dir="logs/{}".format(NAME))
filepath = "RNN_Final-{epoch:02d}-{val_acc:.3f}" # unique file name that will include the epoch and the validation acc for that epoch
checkpoint = ModelCheckpoint("models/{}.model".format(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')) # saves only the best ones
# Train model
history = model.fit_generator(
generator=generator,
epochs=EPOCHS,
steps_per_epoch=100,
validation_data=validation_data,
callbacks=[tensorboard, checkpoint],
)
# Score model
score = model.evaluate(validation_x, validation_y, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# Save model
model.save("models/{}".format(NAME))
但是,當我嘗試訓練模型時,出現以下錯誤:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-67-f5263636596b> in <module>()
10 steps_per_epoch=100,
11 validation_data=validation_data,
---> 12 callbacks=[tensorboard, checkpoint],
13 )
14
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
1777 use_multiprocessing=use_multiprocessing,
1778 shuffle=shuffle,
-> 1779 initial_epoch=initial_epoch)
1780
1781 def evaluate_generator(self,
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training_generator.py in fit_generator(model, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
134 'or `(val_x, val_y)`. Found: ' + str(validation_data))
135 val_x, val_y, val_sample_weights = model._standardize_user_data(
--> 136 val_x, val_y, val_sample_weight)
137 val_data = val_x + val_y + val_sample_weights
138 if model.uses_learning_phase and not isinstance(K.learning_phase(), int):
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split)
915 feed_output_shapes,
916 check_batch_axis=False, # Don't enforce the batch size.
--> 917 exception_prefix='target')
918
919 # Generate sample-wise weight values given the `sample_weight` and
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
180 ': expected ' + names[i] + ' to have ' +
181 str(len(shape)) + ' dimensions, but got array '
--> 182 'with shape ' + str(data_shape))
183 if not check_batch_axis:
184 data_shape = data_shape[1:]
ValueError: Error when checking target: expected dense_13 to have 2 dimensions, but got array with shape (1, 219, 3)
正如@yhenon在注釋部分中提到的那樣,因為模型的每個時間步都有一些輸出,所以對於最后一個LSTM層,也必須使用return_sequences=True
。
但是,尚不清楚任務是什么(即分類或回歸)。 如果是分類任務,則必須使用'categorical_crossentropy'
作為損失函數(而不是當前使用的'sparse_categorical_crossentropy'
),並使用'softmax'
作為最后一層的激活函數。
在另一方面,如果它是一個回歸的任務,你需要使用一個回歸的損失,如'mse'
或'mae'
正確,並設置最后一層的激活功能,根據不同的輸出值(即采用'linear'
如果輸出值范圍包括正數和負數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.