> 29次观察后的张量流简单回归nan

数据挖掘 神经网络 张量流
2022-03-13 01:42:36

我有如下代码。如果数据点的数量更改为 30 以上的任何数字(例如 40),那么我会得到 为什么nan值?final_slope , final_intercept

对于 25 个示例,它运行良好。我在 Windows 机器上的 tensorflow 上使用 cpu 版本。

可以通过更改第 4 行的数字来更改数据点的数量 n= 40

import numpy as np
import tensorflow as tf

n= 40
x_data = np.linspace(0,10,n) + np.random.uniform(-1.5,1.5,n)
y_label = np.linspace(0,10,n) + np.random.uniform(-1.5,1.5,n)

import matplotlib.pyplot as plt
#%matplotlib inline
plt.plot(x_data,y_label,'*')

m = tf.Variable(0.39)
b = tf.Variable(0.2)

error = 0

for x,y in zip(x_data,y_label):

    y_hat = m*x + b  #Our predicted value

    error += (y-y_hat)**2 # The cost we want to minimize (we'll need to use an optimization function for the minimization!)


optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train = optimizer.minimize(error)

init = tf.global_variables_initializer()

with tf.Session() as sess:

    sess.run(init)

    epochs = 1000

    for i in range(epochs):

        sess.run(train)


    # Fetch Back Results
    final_slope , final_intercept = sess.run([m,b])

print (final_slope , final_intercept)
1个回答

您计算“错误”函数的方式是错误的。每当您训练模型时,您都会汇总错误值。因此,误差值会随着时间的推移而增加并达到无穷大(您可以在每个时期打印误差值来检查)。误差函数应计算如下。

错误 = tf.reduce_mean((y_hat - y_label)**2)

顺便说一句,您可以检查每个时期的错误值。选择模型的超参数以确保误差值在时间跨度内减小。这是历元跨度的误差曲线。 在此处输入图像描述