【问题标题】:How do I shape my input data for use with Conv1D in keras?如何塑造我的输入数据以在 keras 中与 Conv1D 一起使用?
【发布时间】:2017-12-12 05:22:05
【问题描述】:

我的虚拟数据集中有 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

【问题讨论】:

标签: python machine-learning keras conv-neural-network


【解决方案1】:

Keras documentation 中写到input_shape 是一个形状为(batch_size, steps, input_dim) 的3D 张量。含义如下:

  1. batch_size 是样本数。给你的是12
  2. steps 是数据的时间维度。您可以将其设置为1,因为数据中只有一个通道。
  3. input_dim 是一个样本的维度。给你的是200

您的问题的答案是将您的数据重塑为(12,1,200)

【讨论】:

  • 我试过了,但我又得到了错误:ValueError:检查模型目标时出错:预期 conv1d_1 有 3 个维度,但得到了形状为 (12, 1) 的数组。我是否也必须更改我的 input_shape 参数?
  • 是的。这是告诉 keras 输入的形状为 (12,1,200) 的唯一方法。
  • @user1816679 如果你不想指定训练样本的数量,那么写input_shape=(None, 1, 200))
  • 好的,我这样做了,但现在我收到了一个新错误:ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4
  • 好吧,我错了。 input_shape=(None, 1, 200)) 会出错,input_shape=(None, 200)) 应该可以正常工作。如果您可以提供脚本,我可以建议编辑。否则thisinput_shape 有更好的解释。
【解决方案2】:

您需要根据 Conv1D 层输入格式重塑您的输入数据 - (batch_size, steps, input_dim)。试试

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

【讨论】:

    【解决方案3】:

    有点晚了,但只是为了回答这个问题,输入形状是(不同模型的数量 - 批次,每个模型的数据数量,数据的维度)。在你的情况下(12,200,1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 2018-01-14
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      相关资源
      最近更新 更多