【发布时间】:2020-08-14 16:04:52
【问题描述】:
我正在尝试使用 Tensorflow 来计算一些数据的线性回归。 我不明白为什么不能预测一条像样的线。 在我得到的结果下方:
这是我的代码,我尝试更改不同的参数但无事可做。
欢迎提出任何建议。
# Prepare the data
x = df["Attainment8_float"]
y = df["Progress8_float"]
# Check the data
plt.scatter(x, y)
plt.show()
# TensorFlow Model
# Config
num_epochs = 1000
learning_rate = 0.0001
# /Config
# Creating the graph
ops.reset_default_graph()
tf.disable_v2_behavior()
X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')
a = tf.get_variable('a', initializer=0.)
b = tf.get_variable('b', initializer=0.)
h = a * X + b
cost = tf.reduce_mean( (h - Y)**2 )
optimizer = tf.train.GradientDescentOptimizer(
learning_rate=learning_rate
).minimize(cost)
init = tf.global_variables_initializer()
# Running the Model
found_a = 0
found_b = 0
with tf.Session() as sess:
sess.run(init)
for epoch in range(num_epochs):
_, costValue = sess.run(
[optimizer, cost],
feed_dict={
X: x,
Y: y,
}
)
found_a = a.eval()
found_b = b.eval()
if epoch % (num_epochs/10) == 0: # Every 10 percent
print("... epoch: " + str(epoch))
print(f"cost[{str(costValue)}] / a[{str(a.eval())}] / b[{str(b.eval())}]")
# Seing the obtained values in a plot
xrange = np.linspace(x.min(), x.max(), 2)
# Plot points
plt.plot(x, y, 'ro')
# Plot resulting function
plt.plot(xrange, xrange * found_a + found_b, 'b')
plt.show()
【问题讨论】:
-
你能让数据可以访问吗?
-
data.london.gov.uk/download/gcse-results-by-borough/…我已经清理了一些数据,但在这里你可以找到所有内容。
-
你能添加完整的代码吗?尤其是你如何创建 df。
-
df = pd.read_csv(r'C:/Users/Lavoro/Desktop/PythonBook/gcse-results.csv') #drop 。在 cvs df = df[df.Attainment8 != "."] df = df[df.Progress8 != "."] #convert object in float df["Attainment8_float"] = df["Attainment8"].astype(float ) df["Progress8_float"]= df["Progress8"].astype(float)
-
我确实在 np 数组中转换了 x 和 y 但仍然没有
标签: python tensorflow linear-regression