LSTM Keras- 值输入维度错误

LSTM Keras- Value input dimension error

我正在尝试使用 Keras 实现 LSTM 来解决多 class 问题。我输入了尺寸为 1007x5 的 csv。每个实例的特征数为 5,总共有 12 classes。下面是代码

seed = 7
numpy.random.seed(seed)

input_file = 'input.csv'

def load_data(test_split = 0.2):
    print ('Loading data...')
    dataframe = pandas.read_csv(input_file, header=None)
    dataset = dataframe.values

    X = dataset[:,0:5].astype(float)
    print(X)
    Y = dataset[:,5]
    print("y=", Y)    
    return X,Y


def create_model(X):
    print ('Creating model...')
    model = Sequential()

    model.add(LSTM(128, input_shape =(5,)))
    model.add(Dense(12, activation='sigmoid'))

    print ('Compiling...')
    model.compile(loss='categorical_crossentropy',
                  optimizer='rmsprop',
                  metrics=['accuracy'])
    return model


X,Y,dummy_y= load_data()
print("input Lnegth X=",len(X[0]))

model = create_model(X)

print ('Fitting model...')
hist = model.fit(X, Y, batch_size=5, nb_epoch=10, validation_split = 0.1, verbose = 1)


score, acc = model.evaluate(dummy_x,dummy_y)
print('Test score:', score)
print('Test accuracy:', acc)

在不同的论坛和此处的帖子中出现此错误后,我尝试了不同的输入形状,但仍然无法正常工作。 当我给出输入数据形状时,出现以下错误: 1. 当我将 input_shape 作为 X.shape[1:]) 时 - 错误是 "input 0 is incompatible layer lstm_1: expected ndim =3, found ndim=2"

  1. 当我给input_shape=X.shape[1:])时,错误是"value error: when checking input: expected lstm_1_input to have 3 dimensions, but got array with shape (1007,5)"

  2. 除形状外,如果ndim设置为5,则表示"input 0 is incompatible layer lstm_1: expected ndim =3, found ndim=2"

lstm第一层应该输入什么?我到layer 1的维度应该是(128,1007,5)吧?

LSTM 需要 3 维输入。您的输入形状应采用(样本、时间步长、特征)的形式。由于 keras 推断第一个维度是样本,因此您应该输入 (timesteps, features) 作为输入形状。

由于您的 csv 尺寸为 1007*5,我认为最好的做法是将您的输入重塑为 (1007, 5, 1),这样您的 LSTM 可以获得 3D 输入。

所以里面 load_data:

X = X.reshape(X.shape[0], x.shape[1], 1)

在里面 create_model:

model.add(LSTM(128, input_shape =(5,1)))