python – 如何在keras中对输入数据进行整形以与Conv1D一起使用?

我的虚拟数据集中有12个长度为200的向量,每个向量代表一个样本.假设x_train是一个形状为(12,200)的数组.

当我做:

model = Sequential()
model.add(Conv1D(2, 4, input_shape=(1, 200)))

我收到错误:

ValueError: Error when checking model input: expected conv1d_1_input to have 3 dimensions, but got array with shape (12, 200)

如何正确地塑造输入数组?

这是我更新的脚本:

data = np.loadtxt('temp/data.csv', delimiter=' ')
trainData = []
testData = []
trainlabels = []
testlabels = []

with open('temp/trainlabels', 'r') as f:
    trainLabelFile = list(csv.reader(f))

with open('temp/testlabels', 'r') as f:
    testLabelFile = list(csv.reader(f))

for i in range(2):
    for idx in trainLabelFile[i]:
        trainData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        trainlabels.append(i)

for i in range(2):
    for idx in testLabelFile[i]:
        testData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        testlabels.append(i)

# print(trainData.shape)
X = np.array(trainData)
Y = np.array(trainlabels)
X2 = np.array(testData)
Y2 = np.array(testlabels)

model = Sequential()
model.add(Conv1D(1, 1, input_shape=(12, 1, 200)))

opt = 'adam'
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy'])

model.fit(X, Y, epochs=epochs)

我现在收到一个新错误:

ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4

最佳答案 您需要根据Conv1D图层输入格式重新整形输入数据 – (batch_size,steps,input_dim).尝试

x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1])
点赞