首页 > 解决方案 > 深度神经网络学习函数 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,并调整超参数以确保损失收敛,但没有效果。还有其他方法可以提高神经网络的性能吗?

标签: pythontensorflowmachine-learningneural-network

解决方案


您的损失图显示大约 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 个隐藏节点的单层模型开始。较小的模型收敛速度更快。


推荐阅读