首页 > 解决方案 > ValueError:层顺序需要 1 个输入,但它在 tensorflow 2.0 中接收到 211 个输入张量

问题描述

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

[np.array([2, 3, 4, ... 5, 4, 6]) ... np.array([3, 4, 5, ... 3, 4, 5])]

我使用这段代码来训练模型:

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.

可能是什么问题?

标签: pythonpython-3.xtensorflowkerasconv-neural-network

解决方案


你不需要扁平化你的输入。如果您有 211 个 shape 样本(185,),则这已经表示扁平化输入。

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

x = np.stack([i.tolist() for i in x])

然后,你犯了其他错误。您不能通过 SoftMax 激活输出 1 个神经元。它只会输出 1,所以使用"sigmoid". 这也是错误的损失函数。如果您有两个类别,则应使用"binary_crossentropy".

这是一个修复错误的工作示例,从您的无效输入开始:

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)

推荐阅读