Tensor flow小案例——01单变量线性回归

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

#源数据

#从1到10,分为100等分
data_x = np.linspace(1, 10, 100)

#噪音,使数据更加真实,均值为0,标准差为1.5
noise = np.random.normal(0, 1.5, data_x.shape)

#定义函数,y = -5x + 20
data_y = data_x * -5 + 20 + noise



#定义变量

#X,Y作为输入值
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

#W为权重,相当于斜率,B为偏移量
W = tf.Variable(tf.zeros([1]))
B = tf.Variable(tf.zeros([1]))

#Y的预测值,Y = XW + B
Y_prediction = tf.add(tf.multiply(X, W), B)

#定义损失函数
Loss = tf.reduce_sum(tf.square(Y - Y_prediction))

#定义学习率,注意一定不要太大了,否则不会收敛
rateLearning = 0.0001

#定义训练方法,使得Loss最小化(这里是梯度下降,还有其他更好的训练方法,以后介绍)
Train = tf.train.GradientDescentOptimizer(rateLearning).minimize(Loss)


sess = tf.Session()

#初始化所有变量
init = tf.global_variables_initializer()
sess.run(init)

#训练1000次
for i in range(1000):
    sess.run(Train, feed_dict={X: data_x, Y: data_y})

#得到w,b
w, b = sess.run([W, B])

#画出源数据的散点图
plt.scatter(data_x, data_y, color = 'b')
#画出预测直线
plt.plot(data_x, data_x * w + b, color = 'r')

plt.show()

猜你喜欢

转载自blog.csdn.net/iv__vi/article/details/82889640