【问题标题】:ValueError: Layer sequential expects 1 inputs, but it received 211 input tensors in tensorflow 2.0ValueError:层顺序需要 1 个输入,但它在 tensorflow 2.0 中接收到 211 个输入张量
【发布时间】:2021-01-13 16:06:59
【问题描述】:

我有一个这样的训练数据集(主列表中的项目数为 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.

可能是什么问题?

【问题讨论】:

  • 你想预测什么?具有一个神经元的密集层不应将 softmax 作为激活。此外,您的损失设置不正确。
  • 实际代码有来自临时的数据。传感器呼吸一个小时,我试图预测他/她是否有健康问题。我是 tensorflow 的初学者。

标签: python python-3.x tensorflow keras conv-neural-network


【解决方案1】:

您不需要扁平化您的输入。如果您有 211 个形状为 (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)

【讨论】:

  • 谢谢!它现在运行代码没有任何问题!
【解决方案2】:

对我来说这是一个愚蠢的错误,我在列表中输入而不是 numpy.ndarray

1.检查你的X_train的数据格式类型:

type(X_train)

2.如果您以列表或任何其他格式输出,只需将其转换为 numpy.ndarray

X_train = numpy.array(X_train)

希望这会有所帮助 谢谢

【讨论】:

    【解决方案3】:

    你有两个错误:

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

    input = np.asarray(input)
    

    您声明的输入形状为 (211, 185)。 Keras 自动添加批量维度。所以把形状改成(185,):

    keras.layers.Flatten(input_shape=(185,), name="Input"), 
    

    【讨论】:

    • 很抱歉,问题似乎没有解决。
    • @Ahmadfromjameedium 查看编辑后的答案
    • 它运行了一会儿,然后返回这个错误:ValueError: Layersequential_38 期望 1 个输入,但它接收到 2 个输入张量。
    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 2020-07-15
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2021-09-28
    相关资源
    最近更新 更多