一维卷积CNN Keras

时间:2020-07-25 18:51:57

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

我是Keras的新手,我想使用一维卷积实现CNN,以便对原始时间序列数据进行二进制分类。每个训练示例都有160个时间步长,而我有120个训练示例。训练数据的形状为(120,160)。这是代码:

X_input = Input((160,1))

X = Conv1D(6, 5, strides=1, name='conv1', kernel_initializer=glorot_uniform(seed=0))(X_input)
X = Activation('relu')(X)
X = MaxPooling1D(2, strides=2)(X)

X = Conv1D(16, 5, strides=1, name='conv2', kernel_initializer=glorot_uniform(seed=0))(X)
X = Activation('relu')(X)
X = MaxPooling1D(2, strides=2)(X)
X = Flatten()(X)
    
X = Dense(120, activation='relu', name='fc1', kernel_initializer=glorot_uniform(seed=0))(X)

X = Dense(84, activation='relu', name='fc2', kernel_initializer=glorot_uniform(seed=0))(X)
    
X = Dense(2, activation='sigmoid', name='fc3', kernel_initializer=glorot_uniform(seed=0))(X)

model = Model(inputs=X_input, outputs=X, name='model')


X_train = X_train.reshape(-1,160,1)   # shape (120,160,1)
t_train = y_train.reshape(-1,1,1)     # shape (120,1,1)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train)

我得到的错误是expected fc3 to have 2 dimensions, but got array with shape (120, 1, 1)

我尝试删除每一层并仅保留'conv1'组件,但出现错误expected conv1 to have shape (156, 6) but got array with shape (1, 1)。我的输入形状似乎有误;但是,从其他示例来看,这似乎对其他人有用。

1 个答案:

答案 0 :(得分:0)

我认为问题不是您的投入,而是您的目标。

模型的输出为2维,但是当检查目标时,它会意识到目标位于形状为(120,1,1)的数组中。

您可以尝试如下更改y_train重塑线(仅供参考,似乎您不小心键入了t_train而不是y_train):

y_train = y_train.reshape(-1,1)

此外,您似乎希望在最后一个Dense层中使用1而不是2(请参见Difference between Dense(2) and Dense(1) as the final layer of a binary classification CNN?