没有为任何变量提供梯度,Tensorflow线性回归

时间:2019-02-05 20:45:25

标签: python tensorflow machine-learning

我目前正在学习如何使用Tensorflow,并且此代码在线性回归应用中存在一些问题。

这是完整的错误描述:

  

ValueError:没有为任何变量提供渐变,请检查图形中变量[“”,“”]和损失Tensor(“ Mean:0”,shape =(),dtype = float64之间的不支持渐变的操作)。

我一直看到与此主题相关的类似问题,并且似乎与数据格式冲突有关,如果您能就发生此错误的原因提供一些想法或知识,我将不胜感激。

完整代码:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

num_points = 200
x_points = []
y_points = []
a = 0.22
b = 0.78

for 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()

1 个答案:

答案 0 :(得分:0)

以下是您的代码的有效示例:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

num_points = 200
a = 0.22
b = 0.78
# No need to create everything in a loop, np.random.normal takes a size parameter
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)

# Always see whether the API you are using provides you with the implementation you need. It is more stable, and it will save you a lot of trouble with debugging like right now
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()