Keras的Conv1d中的input_shape变量如何工作?

时间:2019-08-19 09:57:08

标签: python tensorflow keras conv-neural-network

Ciao, 我正在Keras上使用CNN 1d,但是在输入形状变量方面遇到了很多麻烦。

我有一个100个时间步长和5个带有布尔标签的功能的时间序列。我想训练一个长度为10的滑动窗口的CNN 1d。这是我编写的非常简单的代码:

from keras.models import Sequential
from keras.layers import Dense, Conv1D
import numpy as np

N_FEATURES=5
N_TIMESTEPS=10
X = np.random.rand((100, N_FEATURES))
Y = np.random.randint(0,2, size=100)


# CNN
model.Sequential()
model.add(Conv1D(filter=32, kernel_size=N_TIMESTEPS, activation='relu', input_shape=N_FEATURES
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

我的问题是出现以下错误:

  File "<ipython-input-2-43966a5809bd>", line 2, in <module>
    model.add(Conv1D(filter=32, kernel_size=10, activation='relu', input_shape=N_FEATURES))
TypeError: __init__() takes at least 3 arguments (3 given)

我也尝试过将以下值传递给input_shape:

input_shape=(None, N_FEATURES)
input_shape=(1, N_FEATURES)
input_shape=(N_FEATURES, None)
input_shape=(N_FEATURES, 1)
input_shape=(N_FEATURES, )
  

您知道代码有什么问题吗?或者一般来说,您可以解释Keras CNN中 input_shape 变量背后的逻辑吗?

疯狂的事情是我的问题与以下相同:

Keras CNN Error: expected Sequence to have 3 dimensions, but got array with shape (500, 400)

但是我无法用帖子中给出的解决方案来解决它。

  

Keras版本为 2.0.6-tf

谢谢

1 个答案:

答案 0 :(得分:1)

这应该有效:

from keras.models import Sequential
from keras.layers import Dense, Conv1D
import numpy as np

N_FEATURES=5
N_TIMESTEPS=10
X = np.random.rand(100, N_FEATURES)
Y = np.random.randint(0,2, size=100)

# Create a Sequential model
model = Sequential()
# Change the input shape to input_shape=(N_TIMESTEPS, N_FEATURES)
model.add(Conv1D(filters=32, kernel_size=N_TIMESTEPS, activation='relu', input_shape=(N_TIMESTEPS, N_FEATURES)))
# If it is a binary classification then you want 1 neuron - Dense(1, activation='sigmoid')
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

请在每行代码之前查看注释。此外,Conv1D期望的输入形状为(time_steps, feature_size_per_time_step)。您的代码的翻译为(N_TIMESTEPS, N_FEATURES)