python - 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.
可能是什么问题?
解决方案
你不需要扁平化你的输入。如果您有 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)
推荐阅读
- python - Django 模板块没有出现在渲染模板中的正确位置 - 导致 jQuery“$ 未定义”错误
- android - 如何解决 PreferredSize 颤振中的零参数构造函数错误?
- ajax - 如何在 Laravel 的 Ajax 请求中手动验证 CSRF 令牌
- elasticsearch - 如何在 ElasticSearch 中搜索包含错误单词的短语?
- powerbi - 使用 React 包装器嵌入 Power BI 报表时,报表中的一些视觉对象未呈现
- amazon-s3 - 从 S3 存储桶加载 pytorch 模型
- r - 带有 rstudioapi::jobRunScript 的彩色文本输出
- ios - iOS 辅助功能:通知用户相机处于活动状态
- python - 将条目输入用作 tkinter 的变量
- c++ - 填充一个向量,该向量包含来自 csv 文件的多个派生类的对象