我目前正在学习如何使用 Tensorflow,并且在编写线性回归应用的代码时遇到了一些问题。
以下是完整的错误描述:
ValueError: 没有任何变量提供梯度,请检查您的图形中是否存在不支持梯度的操作,在变量 [“”, “”] 和损失 Tensor(“Mean:0”, shape=(), dtype=float64) 之间。
我看到过关于这个问题的类似报告,看起来似乎与数据格式冲突有关,如果您能提供一些关于此错误原因的想法或知识,我将不胜感激。
完整代码如下:
import tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltnum_points = 200x_points = []y_points = []a = 0.22b = 0.78for i in range(num_points): x = np.random.normal(0.0, 0.5) y = a*x + b + np.random.normal(0.0, 0.1) x_points.append([x]) y_points.append([y])plt.plot(x_points, y_points, 'o', label='Input Data')plt.title('Linear Regression')#plt.legend()#plt.show()A = tf.Variable(tf.random_uniform([1], -1.0, 1.0))B = tf.Variable(tf.zeros([1]))Y = tf.add(tf.multiply(A, x_points), B)cost_function = tf.reduce_mean(tf.square(np.array(y) - np.array(y_points)))optimizer = tf.train.GradientDescentOptimizer(0.5)linear_reg = optimizer.minimize(cost_function)model = tf.initialize_all_variables()with tf.Session() as sess: sess.run(model) for step in range(0, 21): sess.run(linear_reg) if (step % 5) == 0: plt.plot(x_points, y_points, 'o', label='step = {}'.format(step)) plt.plot(x_points, sess.run(A)*x_points + sess.run(B)) plt.legend() plt.show()
回答:
这是您的代码的一个工作示例:
import tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltnum_points = 200a = 0.22b = 0.78# 不需要在循环中创建所有内容,np.random.normal 接受一个 size 参数x_points = np.random.normal(0.0, 0.5, 200)y_points = a*x_points + b + np.random.normal(0.0, 0.1, 200)plt.plot(x_points, y_points, 'o', label='Input Data')plt.title('Linear Regression')A = tf.Variable(tf.random_uniform([1], -1.0, 1.0))B = tf.Variable(tf.zeros([1]))Y = tf.add(tf.multiply(A, x_points), B)# 总是检查您正在使用的 API 是否提供了您需要的实现。它们更稳定,并且可以帮助您避免像现在这样的调试麻烦cost_function = tf.losses.mean_squared_error(Y, y_points)optimizer = tf.train.GradientDescentOptimizer(0.5)linear_reg = optimizer.minimize(cost_function)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for step in range(0, 21): sess.run(linear_reg) if (step % 5) == 0: plt.plot(x_points, y_points, 'o', label='step ={}'.format(step)) plt.plot(x_points, sess.run(A)*x_points + sess.run(B)) plt.legend() plt.show()