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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值