简体   繁体   English

TensorFlow 线性回归

[英]TensorFlow Linear Regression

I am trying to use Tensorflow to calculate the linear regression of some data.我正在尝试使用 Tensorflow 来计算一些数据的线性回归。 I do not understand why cannot predict a decent line.我不明白为什么不能预测一条像样的线。 Below the result I am getting:在我得到的结果下方:

在此处输入图像描述

This is my code, I have tried to change different parameters but nothing to do.这是我的代码,我尝试更改不同的参数但无事可做。

Any suggestion is welcome.欢迎任何建议。

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

When I run it with当我运行它时

a = tf.get_variable('a', initializer= 0.05) 
b = tf.get_variable('b', initializer=-2.0) 

I get我明白了

ex2

However, I did some data preprocessing.但是,我做了一些数据预处理。 I removed entries with "."我删除了带有“。”的条目as you did as far as I can see.就我所见,正如你所做的那样。 Furthermore I removed entries with "x", so code looks like:此外,我删除了带有“x”的条目,因此代码如下所示:

df = df[df.Attainment8 != "."] 
df = df[df.Progress8 != "."] 

df = df[df.Attainment8 != "x"] 
df = df[df.Progress8 != "x"] 

#convert object in float 
df["Attainment8_float"] = df["Attainment8"].astype(float) 
df["Progress8_float"]= df["Progress8"].astype(float)

When I additionally use (together with initializer set to 0.05 and -2.0)当我另外使用(连同设置为 0.05 和 -2.0 的初始化程序)

num_epochs = 2000
learning_rate = 0.000001

I get我明白了

ex2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM