今天在编写一个一维卷积神经网络做预测时,出现了很多报错。
def baseline_model():
model = Sequential()
model.add(Conv1D(filters=5, kernel_size=1, strides=3,input_shape=(235,1)))#卷积层
model.add(Dense(units=25, input_dim=(50,),activation='tanh'))#全连接层
model.add(Dense(9, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
return model
首先在网络中将一维卷积作为输入层时出现如下报错:
ValueError: Error when checking input: expected conv1d_11_input to have 3 dimensions, but got array with shape (869, 235)
以下是我导入的测试集:
X = df.values[:, 0:235].astype(float)
Y = df.values[:, 235]
X和Y的形状分别是:
X.shape: (869, 235)
Y.shape: (869,)
意思其实也很明白,就是模型希望输入一个3维的变量进来,结果输入进来了(899,246)这个二维变量。
这时我们给X增加一维:
X = np.expand_dims(df.values[:, 0:235].astype(float), axis=2)#增加一维轴
Y = df.values[:, 235]
此时X的形状变成:
X.shape: (869, 235, 1)
Y.shape: (869,)
继续运行程序,发现卷积层已经通过,而新的问题出现在了全连接层:
ValueError: Error when checking target: expected dense_2 to have 3 dimensions, but got array with shape (809, 9)
全连接层一般喜欢接收到一个一维的向量,这里我们需要加一层压平层:
model.add(Flatten())
def baseline_model():
model = Sequential()
model.add(Conv1D(filters=5, kernel_size=1, strides=3,input_shape=(235,1)))#卷积层
model.add(Flatten())
model.add(Dense(units=25, input_dim=(50,),activation='tanh'))#全连接层
model.add(Dense(9, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
return model
Flatten层用来将输入“压平”,即把多维的输入一维化,常用在从卷积层到全连接层的过渡。
也可以是model.add(GlobalAveragePooling1D()),全局平均值池化,降维的同时减小拟合度。
继续运行,程序开始训练,问题解决!