输入0与lstm_93层不兼容:预期ndim = 3,找到的ndim = 2 [英] Input 0 is incompatible with layer lstm_93: expected ndim=3, found ndim=2

查看:296
本文介绍了输入0与lstm_93层不兼容:预期ndim = 3,找到的ndim = 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My X_train shape is (171,10,1) and y_train shape is (171,)(contains values from 1 to 19). The output should be probability of each of the 19 class. I am trying to use a RNN for classification of 19 classes.

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)

推荐答案

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

When you set return_sequences =False in the second LSTM layer, the result is that (None, 100) no longer needs Flatten(). You can set return_sequences=True in the second LSTM layer or delete regressor.add(Flatten()) according to your needs.

此外,如果要获取19个类别中每个类别的概率,则标签数据应为一格形式.使用keras.utils.to_categorical:

In addition, if you want to get probability of each of the 19 class, your label data should be in one-hot form. Using 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)

这篇关于输入0与lstm_93层不兼容:预期ndim = 3,找到的ndim = 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆