如何在keras python中构建一维卷积神经网络?

我正在使用CNN解决分类问题.我有data.csv文件(15000个样本/行和271列),其中第1列是类标签(总共4个类),其他270列是特征(6个不同的长度为45的信号连接,即6X45 = 270).

问题:
我想提供长度为270的单个样本作为向量(6 X 45,所有6个信号具有不同的含义)但是当在卷积中将单个样本重新整形为(6行,45列)时,我的尺寸会出错.
我的CNN型号:

X, y = load_data()   
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
num_classes = 4

X_train = X_train.reshape(X_train.shape[0], 6, 45).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 6, 45).astype('float32') 

model = Sequential()
model.add(Conv1D(filters=32, kernel_size=5, input_shape=(6, 45)))
model.add(MaxPooling1D(pool_size=5 ))
model.add(Flatten())
model.add(Dense(1000, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))  

如何重塑我的数据,CNN将每个样本视为长度为45的6个信号,并与窗口5的核心进行卷积.

最佳答案 您需要像Xtrain.reshape(num_of_examples,num_of_features,num_of_signals)一样重塑数据,并将模型中的input_shape更改为(45,6).请参阅下面的示例代码

X = np.random.randn(4000,270)
y = np.ones((4000,1))
y[0:999] = 2
y[1000:1999] = 3
y[2000:2999] = 0

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
num_classes = 4

X_train = X_train.reshape(X_train.shape[0], 45, 6).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 45, 6).astype('float32') 

model = Sequential()
model.add(Conv1D(filters=32, kernel_size=5, input_shape=(45, 6)))
model.add(MaxPooling1D(pool_size=5 ))
model.add(Flatten())
model.add(Dense(1000, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
点赞