【问题标题】:Input 0 is incompatible with layer lstm_93: expected ndim=3, found ndim=2输入 0 与层 lstm_93 不兼容:预期 ndim=3,发现 ndim=2
【发布时间】:2018-12-20 18:12:53
【问题描述】:

我的 X_train 形状是 (171,10,1),y_train 形状是 (171,)(包含从 1 到 19 的值)。 输出应该是 19 个类别中每个类别的概率。 我正在尝试使用 RNN 对 19 个类进行分类。

from sklearn.preprocessing import LabelEncoder,OneHotEncoder
label_encoder_X=LabelEncoder()
label_encoder_y=LabelEncoder()

y_train=label_encoder_y.fit_transform(y_train)
y_train=np.array(y_train)

X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))


from keras.models import Sequential
from keras.layers import Dense,Flatten
from keras.layers import LSTM
from keras.layers import Dropout


regressor = Sequential()

regressor.add(LSTM(units = 100, return_sequences = True, input_shape=( 
(X_train.shape[1], 1)))
regressor.add(Dropout(rate=0.15))

regressor.add(LSTM(units = 100, return_sequences =False))#False caused the 
exception ndim
regressor.add(Dropout(rate=0.15))


regressor.add(Flatten())
regressor.add(Dense(units= 19,activation='sigmoid'))
regressor.compile(optimizer = 'rmsprop', loss = 'mean_squared_error')

regressor.fit(X_train, y_train, epochs = 250, batch_size = 16)

【问题讨论】:

    标签: python keras lstm


    【解决方案1】:

    当你在第二个LSTM层设置return_sequences =False时,结果是(None, 100)不再需要Flatten()。您可以根据需要在第二个LSTM层设置return_sequences=True或删除regressor.add(Flatten())

    另外,如果你想得到 19 个类中的每一个的概率,你的标签数据应该是 one-hot 形式。使用keras.utils.to_categorical

    one_hot_labels = keras.utils.to_categorical(y_train, num_classes=19) #(None,19)
    regressor.fit(X_train, one_hot_labels, epochs = 250, batch_size = 16)
    

    【讨论】:

    • 谢谢。我试过那个sn-p的代码。但是当我在解释器中运行 keras.utils.to_categorical(y_train, num_classes=19) 时,它会抛出一个不同的错误索引 20 超出轴 1 的范围,大小为 19。你能帮忙吗?我无法纠正它。但是,当我给出 num_classes=21 时,程序执行得很好。但考虑到我只有 19 个标签,我认为这样运行它是无效的。
    • @Suvab 此错误表示您的y_train 中有数字20。您应该确保y_train 中的标签号属于[0,18]
    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 2020-10-05
    • 2022-08-15
    • 2019-06-04
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多