Python ValueError:Layer sequential需要1个输入,但在tensorflow 2.0中收到211个输入张量

Python ValueError:Layer sequential需要1个输入,但在tensorflow 2.0中收到211个输入张量,python,python-3.x,tensorflow,keras,conv-neural-network,Python,Python 3.x,Tensorflow,Keras,Conv Neural Network,我有一个这样的训练数据集(主列表中的项目数为211,每个数组中的数字数为185): 我用这个代码来训练模型: def create_model(): model = keras.Sequential([ keras.layers.Flatten(input_shape=(211, 185), name="Input"), keras.layers.Dense(211, activation='relu', name="Hidden_Layer_1&

我有一个这样的训练数据集(主列表中的项目数为211,每个数组中的数字数为185):

我用这个代码来训练模型:

def create_model():
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(211, 185), name="Input"), 
    keras.layers.Dense(211, activation='relu', name="Hidden_Layer_1"), 
    keras.layers.Dense(185, activation='relu', name="Hidden_Layer_2"), 
    keras.layers.Dense(1, activation='softmax', name="Output"),
])

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

return model
但每当我这样穿的时候:

model.fit(x=training_data, y=training_labels, epochs=10, validation_data = [training_data,training_labels])
它返回以下错误:

ValueError: Layer sequential expects 1 inputs, but it received 211 input tensors.
可能是什么问题?

您有两个错误:

您不能提供数组列表。将输入转换为数组:

input = np.asarray(input)
您声明了(211185)的输入形状。Keras自动添加批次维度。因此,将形状更改为(185,):


你不需要平铺你的输入。如果您有211个形状样本
(185,)
,这已经表示平坦的输入

但您最初的错误是无法将NumPy数组列表作为输入传递。它需要是列表列表或NumPy数组。试试这个:

x = np.stack([i.tolist() for i in x])
然后,你犯了其他错误。SoftMax激活时不能有1个神经元的输出。它只输出1,所以使用
“sigmoid”
。这也是错误的损失函数。如果有两个类别,则应使用
“二进制交叉熵”

以下是修复错误的工作示例,从无效输入开始:

import tensorflow as tf
import numpy as np

x = [np.random.randint(0, 10, 185) for i in range(211)]
x = np.stack([i.tolist() for i in x])

y = np.random.randint(0, 2, 211)

model = tf.keras.Sequential([ 
    tf.keras.layers.Dense(21, activation='relu', name="Hidden_Layer_1"), 
    tf.keras.layers.Dense(18, activation='relu', name="Hidden_Layer_2"), 
    tf.keras.layers.Dense(1, activation='sigmoid', name="Output"),
])

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


history = model.fit(x=x, y=y, epochs=10)

你想预测什么?只有一个神经元的致密层不应该有softmax作为激活。此外,您的损失设置不正确。实际代码包含来自临时的数据。我试图预测他/她是否有健康问题。我是tensorflow的初学者。很抱歉,它似乎没有解决这个问题。@Ahmadfromjameedium查看编辑后的答案它运行了一段时间,然后返回此错误:ValueError:Layer sequential\u 38需要1个输入,但它收到了2个输入张量。谢谢!它现在运行的代码没有任何问题!
x = np.stack([i.tolist() for i in x])
import tensorflow as tf
import numpy as np

x = [np.random.randint(0, 10, 185) for i in range(211)]
x = np.stack([i.tolist() for i in x])

y = np.random.randint(0, 2, 211)

model = tf.keras.Sequential([ 
    tf.keras.layers.Dense(21, activation='relu', name="Hidden_Layer_1"), 
    tf.keras.layers.Dense(18, activation='relu', name="Hidden_Layer_2"), 
    tf.keras.layers.Dense(1, activation='sigmoid', name="Output"),
])

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


history = model.fit(x=x, y=y, epochs=10)