tensorflow 入门之四 - 单变量线性回归
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
tf.__version__
'1.14.0'
# 关闭 waring 警告
import warnings
warnings.filterwarnings("ignore")
# 加载数据
boston=tf.contrib.learn.datasets.load_dataset('boston')
x_train,y_train=boston.data[:,5],boston.target
# 预览前五行
x_train[:5],y_train[:5]
(array([6.575, 6.421, 7.185, 6.998, 7.147]),
array([24. , 21.6, 34.7, 33.4, 36.2]))
# 画出图形数据
fig,ax=plt.subplots(figsize=(8,8))
ax.scatter(x_train,y_train)
线性回归模型:
y
=
w
0
+
w
1
∗
x
y=w_0+w_1*x
y=w0+w1∗x
# 准备 x 和 y. tensorFlow 定义 x,y 用占位符.
p_x=tf.placeholder(tf.float32,name="X")
p_y=tf.placeholder(tf.float32,name="Y")
# 准备 w0 和 w1, 这两个参数是动态变化的, 所有用 TensorFlow 中的变量
w0=tf.Variable(0.0)
w1=tf.Variable(0.0)
p_x,p_y,w0,w1
(<tf.Tensor 'X:0' shape=<unknown> dtype=float32>,
<tf.Tensor 'Y:0' shape=<unknown> dtype=float32>,
<tf.Variable 'Variable:0' shape=() dtype=float32_ref>,
<tf.Variable 'Variable_1:0' shape=() dtype=float32_ref>)
# 定义回归模型
y_pre=w1*p_x+w0
y_pre
<tf.Tensor 'add:0' shape=<unknown> dtype=float32>
误差函数(损失函数)
c
o
s
t
=
(
y
_
p
r
e
−
y
)
2
cost= (y\_pre - y)^2
cost=(y_pre−y)2
cost=tf.square(p_y-y_pre,name="cost")
cost
<tf.Tensor 'cost:0' shape=<unknown> dtype=float32>
使用优化器优化
# 实例化优化器,最小化 cost. 这里定义计算图, 只定义,不计算
optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
optimizer
<tf.Operation 'GradientDescent' type=NoOp>
# 记录所有的损失
loses=[]
with tf.Session() as se:
# 初始化,不然会出错
se.run(tf.global_variables_initializer())
for i in range(100):
total_lose=0
for x,y in zip(x_train,y_train):
# 第二个返回值是当前参数 x,y 的损失
# feed_dict={p_x:x,p_y:y : 将当前所得的值 x,y 传递给占位符 p_x,p_y
# p_x, p_y 是在之前申请的占位符
# [optimizer,cost]: 我的理解是: 通过 optimizer, 不断的优化 cost, 并且 cost 每次都会返回值
_,lose=se.run([optimizer,cost],feed_dict={p_x:x,p_y:y})
total_lose+=lose
# 这里通过 w0, w1 占位符来获取优化之后的值
w0_value,w1_value=se.run([w0,w1])
loses.append(total_lose)
# 画出预测曲线
fig,ax=plt.subplots(figsize=(8,8))
ax.scatter(x_train,y_train)
tp_y=np.array(w1_value*x_train+w0_value)
ax.plot(x_train,tp_y,'r')
[<matplotlib.lines.Line2D at 0x23610aa8f08>]
# 绘制损失的图像
t_x=np.linspace(0,1000,len(loses))
t_y=np.array(loses)
fig,ax=plt.subplots(figsize=(8,8))
ax.plot(t_x,t_y)
[<matplotlib.lines.Line2D at 0x23610ae1c88>]
从损失函数来看,该模型的损失已经趋于平缓,即使增加训练次数,损失也降不下来了
# 预测
# 假设我们有新数据
new_data=np.array([1,200,3])
# 预测
pre_date=w1_value*new_data+w0_value
pre_date
array([-7.76327801e+00, 8.33582280e+02, 6.92456245e-01])
# 预测
# 假设我们有新数据
new_data=np.array([1,200,3])
# 预测
pre_date=w1_value*new_data+w0_value
pre_date
array([-7.76327801e+00, 8.33582280e+02, 6.92456245e-01])
上面这个就是预测值了,这便完成了预测