ValueError:层顺序需要 1 个输入,但在 TensorFlow 2.0 中收到了 211 个输入张量

Ahm*_*ium 2 python python-3.x conv-neural-network keras tensorflow

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

[np.array([2, 3, 4, ... 5, 4, 6]) ... np.array([3, 4, 5, ... 3, 4, 5])]
Run Code Online (Sandbox Code Playgroud)

我使用此代码来训练模型:

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
Run Code Online (Sandbox Code Playgroud)

但每当我这样安装时:

model.fit(x=training_data, y=training_labels, epochs=10, validation_data = [training_data,training_labels])
Run Code Online (Sandbox Code Playgroud)

它返回此错误:

ValueError: Layer sequential expects 1 inputs, but it received 211 input tensors.
Run Code Online (Sandbox Code Playgroud)

可能是什么问题?

Nic*_*ais 5

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

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

x = np.stack([i.tolist() for i in x])
Run Code Online (Sandbox Code Playgroud)

然后,你又犯了其他错误。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)
Run Code Online (Sandbox Code Playgroud)