python - TensorFlow 回归神经网络为所有内容输出相同的数字
问题描述
我创建了一个非常简单的回归模型,可以训练黑白图像和 0.5-10 之间的相应标签。在训练预测标签时,它总是会收敛到一个模型,该模型为所有内容输出相同的数字,该数字看起来最有可能是所有标签的平均值。我的模型有什么东西在创造这个吗?我的代码:
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
(train_images, train_labels), (test_images, test_labels) = np.load("dataset.npy", allow_pickle=True)
train_labels = list(map(float, train_labels))
test_labels = list(map(float, test_labels))
train_labels = [int(i) for i in train_labels]
test_labels = [int(i) for i in test_labels]
print(train_labels)
model = keras.Sequential([
keras.layers.Flatten(input_shape=(128, 128)),
keras.layers.Dense(64, activation=tf.nn.relu),
keras.layers.Dense(1)
])
model.compile(loss='mean_squared_error',
optimizer='adam',
metrics=['mean_absolute_error', 'mean_squared_error'])
model.fit(train_images, train_labels, epochs=1000)
predictions = model.predict(test_images)
for i in range(103):
print("%s: %s" % (test_labels[i], predictions[i]))
解决方案
处理图像时的一个关键步骤是标准化图像值。它有助于平滑优化和梯度更新,还可以帮助您的模型更好更快地收敛。有多种方法可以做到这一点,但其中一种简单的归一化方案是将图像像素的值除以 255(不要忘记图像像素的值通常在 [0,255] 范围内,因此将它们除以 255 会使它们落在 [0,1] 范围内):
train_images = train_images.astype('float32') / 255.0
test_images = test_images.astype('float32') / 255.0
推荐阅读
- react-native - 相机拍摄后无法打印照片
- python - Python 根据两个字符之间的字符串进行拆分
- react-native - 我应该为每个 onPress 编写不同的函数吗
- postgresql - OperationalError:无法连接到服务器:连接被拒绝 - 尝试连接到新的 postgresql 数据库时
- c# - WPF ComboBox SelectionChangedEventHandler 删除?
- java - 具有 CascadeType.ALL 的 JPA 外键约束
- ios - TableView Swift 中的多选
- android - 如何将firebase数据库引用到另一个活动(用于更新数据库记录)?
- c++ - 初始化原子指针是原子的吗?如果初始化或内存分配抛出,会发生什么?
- python - 获取多索引数据框的第二级名称