我已经在顺序模式下构建了该模型,并且运行良好,我使用的是完全相同的数据,其类型和形状与顺序模型相同。现在,我试图在功能性API中重新创建它,但出现错误。
train_x的形状是(68,1,50) train_y的形状是(68,)
这是我使用的代码:
inputs = Input(shape = (1, 50))
x = LSTM(4, return_sequences = True)(inputs)
x = LSTM(4, return_sequences = True)(x)
x = LSTM(4, return_sequences = True)(x)
x = LSTM(4, return_sequences = True)(x)
predictions = Dense(1, activation = 'relu')(x)
model = Model(inputs = inputs, outputs = predictions)
model.compile(optimizer = 'rmsprop', loss = 'mean_squared_error', metrics = ['accuracy'])
model.fit(x = train_x, y = train_y, batch_size = 17, epochs = 100)
错误消息:
ValueError Traceback (most recent call last)
<ipython-input-51-246abb1e3d55> in <module>()
1 model = Model(inputs = inputs, outputs = predictions)
2 model.compile(optimizer = 'rmsprop', loss = 'mean_squared_error', metrics = ['accuracy'])
----> 3 model.fit(x = train_x, y = train_y, batch_size = 17, epochs = 100)
C:\Python35\lib\site-packages\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, **kwargs)
1403 class_weight=class_weight,
1404 check_batch_axis=False,
-> 1405 batch_size=batch_size)
1406 # prepare validation data
1407 if validation_data:
C:\Python35\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_batch_axis, batch_size)
1297 output_shapes,
1298 check_batch_axis=False,
-> 1299 exception_prefix='model target')
1300 sample_weights = _standardize_sample_weights(sample_weight,
1301 self._feed_output_names)
C:\Python35\lib\site-packages\keras\engine\training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
119 ' to have ' + str(len(shapes[i])) +
120 ' dimensions, but got array with shape ' +
--> 121 str(array.shape))
122 for j, (dim, ref_dim) in enumerate(zip(array.shape, shapes[i])):
123 if not j and not check_batch_axis:
ValueError: Error when checking model target: expected dense_4 to have 3 dimensions, but got array with shape (68, 1)
这是对我有用的顺序模型。
model = Sequential()
model.add(LSTM(units = 3, return_sequences = True, input_shape = (1, 50)))
model.add(LSTM(units = 3, return_sequences=True))
model.add(LSTM(units = 3, return_sequences=True))
model.add(LSTM(units = 3, return_sequences=True))
model.add(LSTM(units = 3, return_sequences=True))
model.add(LSTM(units = 3, return_sequences=True))
model.add(LSTM(units = 3))
model.add(Dense(1, activation = 'relu'))
model.compile(loss = 'mean_squared_error', optimizer = 'adagrad', metrics = ['accuracy'])
model.fit(x = train_x, y = train_y, batch_size = 3, epochs = 100, validation_split = 0.2, shuffle = True)
Predictions = model.predict(x = test_x).reshape((29,))
error = (sum((test_y - Predictions)**2))**(1.0/2.0)
打印(错误)