简体   繁体   English

Keras中使用Conv1D的形状错误

[英]Error of Shape Using Conv1D in Keras

I have troubles using Conv1D as an input layer in Sequential NN with Keras. 我在使用Keras将Conv1D用作顺序NN中的输入层时遇到麻烦。 Here is my code : 这是我的代码:

import numpy as np    
from keras.layers.convolutional import Conv1D    
from keras.models import Sequential    
from keras.optimizers import Adam    

conv1d = Conv1D(input_shape=(None, 16), kernel_size=2, filters=2)    

model = Sequential()    
model.add(conv1d)    
model.compile(loss="logcosh", optimizer=Adam(lr=0.001))    

x_train = np.zeros((32, 16, 1))    
y_train = np.zeros((32, 16, 1))    

print(x_train.shape)    

model.fit(x_train, y_train, batch_size=4, epochs=20)     

Here is the error. 这是错误。 I have tried multiple things but none of them helped me to resolve the issue. 我已经尝试了多种方法,但是没有一种方法可以帮助我解决问题。

ValueError: Error when checking input: expected conv1d_47_input to have shape (None, 16) but got array with shape (16, 1) ValueError:检查输入时出错:预期conv1d_47_input具有形状(None,16),但数组的形状为(16,1)

Conv1D expects the inputs to have the shape (batch_size, steps, input_dim) . Conv1D期望输入具有形状(batch_size, steps, input_dim)

Based on the shape of your training data, you have max length 16 and input dimensionality just 1. Is that what you need? 根据训练数据的形状,最大长度为16,输入维数仅为1。这是您所需要的吗?

If so, then the input shape can be specified either as (16, 1) (length is always 16) or (None, 1) (dynamic length). 如果是这样,则输入形状可以指定为(16, 1) (长度始终为16)或(None, 1) (动态长度)。

If you meant to define sequences of length 1 and dimensionality 16, then you need a different shape of the training data: 如果要定义长度为1和维数为16的序列,则需要不同形状的训练数据:

x_train = np.zeros((32, 1, 16))
y_train = np.zeros((32, 1, 16))

I managed to find a solution using flatten function and a dense layer and it worked 我设法找到了使用扁平化功能和密集层的解决方案,并且有效

import numpy as np
from keras.layers.convolutional import Conv1D
from keras.models import Sequential
from keras.optimizers import Adam
from keras.layers import Conv1D, Dense, MaxPool1D, Flatten, Input

conv1d = Conv1D(input_shape=(16,1), kernel_size=2, filters=2)

model = Sequential()
model.add(conv1d)
model.add(Flatten())
model.add(Dense(16))

model.compile(optimizer=optimizer,loss="cosine_proximity",metrics=["accuracy"])

x_train = np.zeros((32,16,1))
y_train = np.zeros((32,16))

print(x_train.shape)
print()

model.fit(x_train, y_train, batch_size=4, epochs=20) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM