3.1 实例1:从一组看似混乱的数据中找出 的规律
深度学习大概的4个步骤:
1)准备数据
2)搭建模型
3)迭代训练
4)使用模型
'''
代码3-1 线性回归
'''
'''3.1.1准备数据'''
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
train_X = np.linspace(-1,1,100)
train_Y = 2*train_X + np.random.rand(*train_X.shape)*0.3 # y= 2x,但加入了噪声
# 显示模拟数据点
plt.plot(train_X,train_Y,'ro',label='Original data')
plt.legend()
plt.show()
'''3.1.2 搭建模型'''
'''正向搭建模型'''
# 创建模型
# 占位符
X = tf.placeholder("float")
Y = tf.placeholder("float")
# 模型参数
W = tf.Variable(tf.random_normal([1]),name="weight")
b = tf.Variable(tf.zeros([1]),name='bias')
#前向结构
z = tf.multiply(X,W)+b
'''反向搭建模型'''
# 反向优化
cost = tf.reduce_mean(tf.square(Y-z))
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
'''3.1.3 迭代训练模型'''
'''1.训练模型'''
# 初始化所有变量(全局初始化)
init = tf.global_variables_initializer()
# 定义参数(设置训练迭代次数)
training_epochs = 20
display_step = 2
# 启动session
with tf.Session() as sess:
sess.run(init)
plotdata={"batchsize":[],"loss":[]} # 存放批次值和损失值
def moving_average(a,w=10):
if len(a)<w:
return a[:]
return [val if idx < w else sum(a[(idx-w):idx])/w for idx,val in enumerate(a)]
#向模型输入数据
for epoch in range(training_epochs):
for (x,y) in zip(train_X,train_Y):
sess.run(optimizer,feed_dict={X:x,Y:y})
#通过feed机制将真实数据灌倒占位符对应的位置feed_dict={X:x,Y:y}
#显示训练中的详细信息
if epoch % display_step == 0 :
loss = sess.run(cost,feed_dict={X:x,Y:y})
print("Epoch:",epoch+1,"cost",loss,"W=",sess.run(W),"b=",sess.run(b))
if not (loss == "NA"):
plotdata["batchsize"].append(epoch)
plotdata["loss"].append(loss)
print("Finished!")
print("cost",loss,"W=",sess.run(W),"b=",sess.run(b))
'''2.训练模型可视化'''
# 图形显示
plt.plot(train_X,train_Y,'ro',label='Original data')
plt.plot(train_X,sess.run(W)*train_X + sess.run(b),label="Fittedline")
plt.legend()
plt.show()
plotdata["avgloss"]=moving_average(plotdata["loss"])
plt.figure(1)
plt.subplot(211)
plt.plot(plotdata["batchsize"],plotdata["avgloss"],'b--')
plt.xlabel("Minibatch number")
plt.ylabel('Loss')
plt.title("Minibatch run vs. Training loss")
plt.show()
'''3.1.4 使用模型'''
print("x=0.2,z=",sess.run(z,feed_dict={X:0.2}))
代码显示结果:
Epoch: 1 cost 0.307698 W= [ 1.07834482] b= [ 0.38648397]
Epoch: 3 cost 0.00384723 W= [ 1.72923148] b= [ 0.22827642]
Epoch: 5 cost 0.00243724 W= [ 1.90749121] b= [ 0.16141097]
Epoch: 7 cost 0.00606877 W= [ 1.95375144] b= [ 0.14368476]
Epoch: 9 cost 0.00727198 W= [ 1.96571577] b= [ 0.13909404]
Epoch: 11 cost 0.00760079 W= [ 1.9688096] b= [ 0.13790683]
Epoch: 13 cost 0.00768692 W= [ 1.9696089] b= [ 0.1376]
Epoch: 15 cost 0.00770926 W= [ 1.96981561] b= [ 0.13752069]
Epoch: 17 cost 0.00771508 W= [ 1.96986938] b= [ 0.13750011]
Epoch: 19 cost 0.00771655 W= [ 1.96988297] b= [ 0.13749486]
Finished!
cost 0.00771655 W= [ 1.96988535] b= [ 0.13749394]
x=0.2,z= [ 0.53147101]
3.3 了解Tensorflow开发的基本步骤
基本步骤如下:
1)定义Tensorflow输入节点
2)定义“学习参数”的变量
3)定义“运算”
4)优化函数,优化目标
5)初始化所有变量
6)迭代更新参数到最优解
7)测试模型
8)使用模型
3.3.1 定义输入节点的方法
1)通过占位符定义:一般使用这种方式
X = tf.placeholder("float")
Y = tf.placeholder("float")
2)通过字典类型定义:一般用于输入比较多的情况
......
#占位符
inputdict = {
'x':tf.placeholder("float"),
'y':tf.placeholder("float")
}
3)直接定义:一般很少使用
......
#生成模拟数据
train_X =np.float32( np.linspace(-1, 1, 100))
train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.3 # y=2x,但是加入了噪声
#图形显示
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.legend()
plt.show()
# 创建模型
# 模型参数
W = tf.Variable(tf.random_normal([1]), name="weight")
b = tf.Variable(tf.zeros([1]), name="bias")
# 前向结构
z = tf.multiply(W, train_X)+ b
3.3.4 定义“学习参数”的变量
有直接定义和字典定义两种方式,不过由于在深度神经网络里参数过多,一般使用字典定义的方式。
1)直接定义
# 模型参数
W = tf.Variable(tf.random_normal([1]), name="weight")
b = tf.Variable(tf.zeros([1]), name="bias")
2)字典定义
......
# 模型参数
paradict = {
'w': tf.Variable(tf.random_normal([1])),
'b': tf.Variable(tf.zeros([1]))
}
# 前向结构
z = tf.multiply(X, paradict['w'])+ paradict['b']
3.3.8 初始化所有变量
在session创建好了之后,第一件事就是需要初始化。
# 初始化所有变量(全局初始化)
init = tf.global_variables_initializer()
# 启动session
with tf.Session() as sess:
sess.run(init)
注意:使用tf.global_variables_initializer函数初始化所有变量的步骤,必须在所有变量和OP定义完成之后,这样才能保证定义的内容有效。