Keras: convolutional layer for 1D input

送分小仙女□ 提交于 2019-12-24 01:55:23

问题


I can not build CNN for 1D input vector.

Example of input value:

df_x.iloc[300]
Out[33]:
0     0.571429
1     1.000000
2     0.971429
3     0.800000
4     1.000000
5     0.142857
6     0.657143
7     0.857143
8     0.971429
9     0.000000
10    0.000000
11    0.000000
12    0.000000
13    0.000000
14    0.000000
15    0.000000
Name: 300, dtype: float64

Example of output value:

df_y.iloc[300]
Out[34]:
0     0.571429
1     0.914286
2     1.000000
3     0.971429
4     0.800000
5     1.000000
6     0.914286
7     0.942857
8     0.800000
9     0.657143
10    0.857143
11    0.971429
12    0.000000
13    0.000000
14    0.000000
15    0.000000
16    0.000000
17    0.000000
18    0.000000
19    0.000000
20    0.000000
21    0.000000
22    0.000000

I have 15k traing examples.

df_x.shape
Out[28]:
(15772, 16)

df_y.shape
Out[29]:
(15772, 23)

My current model:

model = Sequential()
model.add(Conv2D(5, df_x.shape[1], input_shape=(5, 1)))
model.add(Dense(46, activation='relu'))
model.add(Dense(56, activation='relu'))
model.add(Dense(66, activation='relu'))
model.add(Dense(56, activation='relu'))
model.add(Dense(46, activation='relu'))
model.add(Dense(df_y.shape[1], activation='relu'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit the model
model.fit(df_x, df_y, epochs=5, batch_size=10)

I want to build model where first layer will be conv size (5,1), 5 filters and input shape df_x.shape[1], 1.

I have an error:

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

Can you explain me how can I build CNN for 1D input values?


回答1:


You should use Conv1D instead of Conv2D for that.

Conv2D is named 2-dimensional because it's designed to process images. However, the input to Conv2D is actually 4-dimensional - (batch, width, height, channels); the channels can be 3 for RGB or 1 for grey-scale images. That's why keras is complaining:

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

Conv1D accepts 3-dimensional input and that's exactly what you have (provided that you expand your df_x to (15772, 16, 1)). Also the input_shape argument must match the size of each row. Try this:

model.add(Conv1D(5, 5, input_shape=(df_x.shape[1], 1)))


来源:https://stackoverflow.com/questions/49739356/keras-convolutional-layer-for-1d-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!