我的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)
答案 0 :(得分:1)
在第二个LSTM层中设置return_sequences =False
时,结果是(None,100)不再需要Flatten()
。您可以根据需要在第二个LSTM层中设置return_sequences=True
或删除regressor.add(Flatten())
。
此外,如果要获取19个类别中每个类别的概率,则标签数据应为一格形式。使用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)