繁体   English   中英

使用Keras(Tensorflow)训练模型时出现形状错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM