python - 深度神经网络学习函数 f(x) = x^2
问题描述
目前,我有一个功能f(x) = x^2
。
我有一个数据集,其特征为 x,对应的标签为 x^2。
我希望我的机器学习模型能够稍微准确地预测新值。
比如300的预测应该接近300*300 = 90000
在我的代码中,我首先创建了训练数据特征和标签,它们看起来像特征:[0, 1, 2, ... 999] 标签:[0, 1, 4, ... 999*999]
import tensorflow as tf
import numpy as np
import logging
import matplotlib.pyplot as plt
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
val = np.empty([1000], dtype = float)
val_squared = np.empty([1000], dtype = float)
#Create training data
for i in range(1000):
val[i] = i
val_squared[i] = i*i;
#Create layers of Deep Neural Network
l0 = tf.keras.layers.Dense(units = 500,input_shape=[1])
l1 = tf.keras.layers.Dense(units = 500, activation = 'sigmoid')
l2 = tf.keras.layers.Dense(units = 500, activation = 'sigmoid')
l3 = tf.keras.layers.Dense(units = 1)
model = tf.keras.Sequential([l0, l1, l2, l3])
model.compile(loss='mean_squared_error', optimizer = tf.keras.optimizers.Adam(lr=10))
history = model.fit(val,val_squared,epochs = 500, verbose = False, batch_size = 500)
plt.xlabel('Epoch Number')
plt.ylabel("Loss Magnitude")
plt.plot(history.history['loss'])
print("Prediction of 200: {}".format(model.predict([200.0])))
plt.show()
绘制图形时,我们可以看到损失收敛,这表明模型正在学习。然而,实际预测与我们的预期值有很大不同——332823.16 而不是 40000。
绘制的图表可以在这里看到:https ://imgur.com/a/GJMSrbV
我尝试将激活函数更改为 relu 和 tanh,并调整超参数以确保损失收敛,但没有效果。还有其他方法可以提高神经网络的性能吗?
解决方案
您的损失图显示大约 0.8E11、80 亿的误差 - 一个非常大的损失,相当于您的预测中大约 300,000 的误差。
原因可能是你的学习率是 10,非常高(tf.keras.optimizers.Adam(lr=10)
)。通常使用 Adam 的学习率约为 1e-3 (0.001) 或 1e-4 (0.0001)。
还有几点——你甚至不应该需要一个多层模型来解决 y=x^2,尝试一个具有 500 个隐藏节点的单层模型开始。较小的模型收敛速度更快。
推荐阅读
- sql - 如何在将按钮单击为“是”时使用 VBA 更新 SQL Server 中的表
- django - 使用 url 路径数据在我的 HTML 模板中预加载字段
- c# - 将具有字典属性的对象序列化为 .csv
- ruby-on-rails - 在 Rails 应用程序中集成 SAML
- javascript - 如何在去中心化交易所检查加密代币的价格数据
- google-apps-script - 有什么方法可以在不手动编写所有工作表的情况下包含所有工作表?
- python-sphinx - Sphinx:链接到外部 PPT 文档?
- powershell - 如何在 Azure DevOps 的任务组中使用环境变量?
- python - 熊猫周期和熊猫时间戳之间的转换不正确
- xquery - 为什么在 Marklogic 中切换页面时总结果计数会发生变化?