ValueError:层 max_pooling1d 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4。收到完整形状:(无、128、1、32)

时间:2021-02-25 09:26:45

标签: python tensorflow keras deep-learning conv-neural-network

我正在尝试创建一个 CNN 模型。 x_train 数据的形状是 (8040, 128),y_train 数据的形状是 (8040, 1)。同理,x_test 数据的形状为 (3960, 128),y_test 数据的形状为 (3960, 1)。

加载您的数据:

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(data,out_data,test_size=0.33, random_state=21)
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)
#(8040, 128) (8040, 1)
#(3960, 128) (3960, 1)
from sklearn.preprocessing import OneHotEncoder
OHE = OneHotEncoder()

y_train1 = OHE.fit_transform(y_train).toarray()
y_test1 = OHE.fit_transform(y_test).toarray()

我在 CNN 模型的输入层出现错误。这是我的模型:

# Conv1:
model.add(keras.layers.Conv1D(filters = 32, kernel_size=1,strides = 1, activation='relu', input_shape=(128,1,1)))
# Conv2:
model.add(keras.layers.Conv1D(filters = 32, kernel_size=1,strides = 1, activation='relu'))
# Pool1:
model.add(keras.layers.MaxPool1D(pool_size=(3), strides = 1)) 
# BN1:
model.add(keras.layers.BatchNormalization())
# Conv3:
model.add(keras.layers.Conv1D(filters = 64, kernel_size=1,strides = 1, activation='relu'))
# Conv4:
model.add(keras.layers.Conv1D(filters = 64, kernel_size=1,strides = 1, activation='relu'))
# Pool2:
model.add(keras.layers.MaxPool1D(pool_size=(3), strides = 1))
# BN2:
model.add(keras.layers.BatchNormalization())

model.add(keras.layers.Conv1D(filters = 128, kernel_size=1,strides = 1, activation='relu'))
# Conv6:
model.add(keras.layers.Conv1D(filters = 128, kernel_size=1,strides = 1, activation='relu'))
# Pool3:
model.add(keras.layers.GlobalMaxPooling1D())
# BN4:
model.add(keras.layers.BatchNormalization())

import tensorflow as tf
model.add(tf.keras.layers.Flatten())
# Dense1:
model.add(keras.layers.Dense(units=256, activation='relu',use_bias=True))
# Dense2:
model.add(keras.layers.Dense(units=128, activation='relu',use_bias=True))
# BN3:
model.add(keras.layers.BatchNormalization())
# Dense3:
model.add(keras.layers.Dense(units=16, activation='softmax',use_bias=True))
from keras.utils import np_utils
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

scaler.fit(x_train)
model_history = model.fit(scaler.transform(x_train),y_train1, batch_size=32, epochs=43, callbacks=[callback], verbose=1)

显示的错误是: ValueError:层 max_pooling1d 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4。收到完整形状:(无、128、1、32)

我该如何解决这个问题? cnn层的参数应该是什么?

1 个答案:

答案 0 :(得分:1)

将您的 input_shape 更改为

input_shape =(128,1)

或使用 batch_input_shape 而不是 input_shape 并设置为

batch_input_shape=(128, 1, 1)