我是keras的新用户,正在尝试实现一个LSTM模型。为了测试,我声明了以下模型,但由于输入维度的差异而失败了。虽然我在这个网站上找到了类似的问题,但我自己找不到错误。
ValueError:
Error when checking model input:
expected lstm_input_4 to have 3 dimensions, but got array with shape (300, 100)
我的环境
- Python 3.5.2
- Keras 1.2.0(Theano)
代码
from keras.layers import Input, Dense
from keras.models import Sequential
from keras.layers import LSTM
from keras.optimizers import RMSprop, Adadelta
from keras.layers.wrappers import TimeDistributed
import numpy as np
in_size = 100
out_size = 10
nb_hidden = 8
model = Sequential()
model.add(LSTM(nb_hidden,
name='lstm',
activation='tanh',
return_sequences=True,
input_shape=(None, in_size)))
model.add(TimeDistributed(Dense(out_size, activation='softmax')))
adadelta = Adadelta(clipnorm=1.)
model.compile(optimizer=adadelta,
loss='categorical_crossentropy',
metrics=['accuracy'])
# create dummy data
data_size = 300
train = np.zeros((data_size, in_size,), dtype=np.float32)
labels = np.zeros((data_size, out_size,), dtype=np.float32)
model.fit(train, labels)
编辑1(在 Marcin Możejko 的评论之后仍然无法工作)
感谢 Marcin Możejko。但是我遇到了与下面类似的错误。我更新了虚拟数据来检查,但这段代码有什么问题呢?
ValueError:检查模型目标时出错:预期 timedistributed_36 具有 3 维,但得到了形状为 (208, 1) 的数组
def create_dataset(X, Y, loop_back=1):
dataX, dataY = [], []
for i in range(len(X) - loop_back-1):
a = X[i:(i+loop_back), :]
dataX.append(a)
dataY.append(Y[i+loop_back, :])
return np.array(dataX), np.array(dataY)
data_size = 300
dataset = np.zeros((data_size, feature_size), dtype=np.float32)
dataset_labels = np.zeros((data_size, 1), dtype=np.float32)
train_size = int(data_size * 0.7)
trainX = dataset[0:train_size, :]
trainY = dataset_labels[0:train_size, :]
testX = dataset[train_size:, :]
testY = dataset_labels[train_size:, 0]
trainX, trainY = create_dataset(trainX, trainY)
print(trainX.shape, trainY.shape) # (208, 1, 1) (208, 1)
# in_size = 100
feature_size = 1
out_size = 1
nb_hidden = 8
model = Sequential()
model.add(LSTM(nb_hidden,
name='lstm',
activation='tanh',
return_sequences=True,
input_shape=(1, feature_size)))
model.add(TimeDistributed(Dense(out_size, activation='softmax')))
adadelta = Adadelta(clipnorm=1.)
model.compile(optimizer=adadelta,
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(trainX, trainY, nb_epoch=10, batch_size=1)