我正在用Keras做一个递归神经网络。我的数据框由22个特征(x)组成,y为0和1(二进制)。 以下是我的代码,并且在第10个阶段也得到了一致的低精度。另外,这给了我一个形状错误。我不知道该如何改善。谁能帮助我了解它的形状?确实令人困惑,需要为输入层和隐藏层提供哪种形状?
from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten
from sklearn.model_selection import StratifiedKFold
import numpy as np
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
#Pandas dataframe csv
# split into input (X) and output (Y) variables
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 22].values
# split into 67% for train and 33% for test
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=seed)
#Check the shapes
print(X_train.shape)
y_train.shape
(590217, 22)
(590217,)
#Reshape it and check the shape
x_train = X_train.reshape(-1, 1, 22)
x_test = X_test.reshape(-1, 1, 22)
print(x_train.shape)
print(x_test.shape)
(590217, 1, 22)
(290704, 1, 22)
# Create the model
model = Sequential()
model.add(LSTM(1, activation='relu', input_shape=(25, 22),return_sequences=True))
model.add(LSTM(300, activation='relu'))
model.add(Flatten())
model.add(Dense(128))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse',metrics=['accuracy'])
# Fit the model
history = model.fit(x_train, y_train, epochs=3, batch_size=10)
Epoch 1/3
WARNING:tensorflow:Model was constructed with shape (None, 25, 22) for input Tensor("lstm_6_input:0", shape=(None, 25, 22), dtype=float32), but it was called on an input with incompatible shape (None, 1, 22).
WARNING:tensorflow:Model was constructed with shape (None, 25, 22) for input Tensor("lstm_6_input:0", shape=(None, 25, 22), dtype=float32), but it was called on an input with incompatible shape (None, 1, 22).
59022/59022 [==============================] - 337s 6ms/step - loss: 0.1966 - accuracy: 0.1096
Epoch 2/3
59022/59022 [==============================] - 310s 5ms/step - loss: 0.1841 - accuracy: 0.1584
Epoch 3/3
59022/59022 [==============================] - 294s 5ms/step - loss: 0.1823 - accuracy: 0.1721
#我增加了时间并检查了准确性,但并没有得到改善,我还需要改变什么
答案 0 :(得分:1)
在模型的第一层中,您输入了input_shape =(25,22),但您尝试将其拟合为形状为(1,22)的数据集。 为了提高准确性,请在将数据拟合到模型之前尝试对数据进行改组。
import random
np.random.shuffle(x_train)
np.random.shuffle(y_train)
您还可以尝试使用 binary_crossentropy 代替损失函数,而不是MSE,因为它专门针对两类问题。