【发布时间】:2019-06-29 18:21:09
【问题描述】:
我目前正在学习如何使用 Tensorflow,但我在使用此代码进行线性回归应用时遇到了一些问题。
这是完整的错误描述:
ValueError: 没有为任何变量提供梯度,检查你的图表中不支持梯度的操作,在变量 ["", ""] 和 loss 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()
【问题讨论】:
标签: python tensorflow machine-learning