Python 二维阵列Keras网络

Python 二维阵列Keras网络,python,keras,keras-layer,Python,Keras,Keras Layer,我有下面的输入数组,我想把它输入CNN import numpy as np from keras.layers import Input, Dense, Conv2D #dummy data for 1d array width = 5 levels = 4 inputArray =np.random.randint(low=0, high=levels, size=20) inputArray_ = inputArray.reshape(-1,width) #reshape to 2d a

我有下面的输入数组,我想把它输入CNN

import numpy as np 
from keras.layers import Input, Dense, Conv2D
#dummy data for 1d array
width = 5
levels = 4
inputArray =np.random.randint(low=0, high=levels, size=20)
inputArray_ = inputArray.reshape(-1,width) #reshape to 2d array
网络的第一层是:

x = Conv2D(16, (3, 3), activation='relu', padding='same')(inputArray_)
我得到以下错误:

ValueError: Layer conv2d_13 was called with an input that isn't a symbolic tensor.   Received type: <class 'numpy.ndarray'>. Full input: [array([[3, 1, 1, 1, 1],
   [0, 1, 3, 1, 3],
   [0, 0, 2, 0, 0],
   [1, 3, 2, 2, 0],
   [1, 1, 2, 1, 1],
   [0, 3, 1, 3, 0],
   [3, 1, 2, 3, 2],
   [1, 2, 0, 2, 2],
   [3, 2, 2, 1, 0],
   [1, 2, 1, 3, 1],
   [0, 3, 2, 3, 0],
   [0, 3, 1, 0, 0],
   [2, 2, 0, 0, 2],
   [2, 2, 1, 0, 1],
   [3, 3, 0, 3, 1],
   [0, 0, 3, 1, 0],
   [1, 3, 1, 2, 2],
   [1, 0, 3, 2, 2],
   [3, 1, 2, 1, 2],
   [3, 0, 3, 3, 1]])]. All inputs to the layer should be tensors.
ValueError:调用层conv2d_13时使用的输入不是符号张量。收到的类型:。完整输入:[数组([[3,1,1,1,1],
[0, 1, 3, 1, 3],
[0, 0, 2, 0, 0],
[1, 3, 2, 2, 0],
[1, 1, 2, 1, 1],
[0, 3, 1, 3, 0],
[3, 1, 2, 3, 2],
[1, 2, 0, 2, 2],
[3, 2, 2, 1, 0],
[1, 2, 1, 3, 1],
[0, 3, 2, 3, 0],
[0, 3, 1, 0, 0],
[2, 2, 0, 0, 2],
[2, 2, 1, 0, 1],
[3, 3, 0, 3, 1],
[0, 0, 3, 1, 0],
[1, 3, 1, 2, 2],
[1, 0, 3, 2, 2],
[3, 1, 2, 1, 2],
[3, 0, 3, 3, 1]])]. 层的所有输入都应该是张量。

您需要将数组转换为张量

import numpy as np
import tensorflow.keras.backend as K
#dummy data for 1d array
width = 5
levels = 4
inputArray =np.random.randint(low=0, high=levels, size=20)
inputArray_ = inputArray.reshape(-1,width)
print(type(inputArray_))



inputTensor_ = K.constant(inputArray_)

print(type(inputTensor_))
print(inputTensor_)

您应该将
Input
层而不是
inputArray
传递到
Conv2D
层。在定义神经网络的架构时,我们只传递占位符,而不传递实际值

inputArray =np.random.randint(low=0, high=levels, size=20)
inputArray_ = inputArray.reshape(-1,width, 1) #Conv2D accepts 3D array

input_data = Input(name='the_input', shape=(None, width, 1), dtype='float32')
x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_data) 

这将返回以下错误值错误:输入0与层conv2d_15不兼容:预期ndim=4,使用以下布局找到ndim=2:x=conv2d(16,(3,3),activation='relu',padding='same')(输入数据)x=MaxPooling2D((2,2),padding='same')(x)x=conv2d(8,(3,3),activation='relu',padding='same')(x)x=MaxPooling2D((2,2),padding='same')(x)x=Conv2D(8,(3,3),activation='relu',padding='same')(x)encoded=MaxPooling2D((2,2),padding='same')(x)encoder=Model(inputArray,encoded)inputArray_u)给出以下错误:TypeError:unhable type:'numpy.ndarray'现在是不同的错误。您正在向模型传递错误的输入。我建议您查看keras文档中的示例,它们非常容易理解: