深度学习的4个步骤
1.数据准备
2.搭建模型
3.迭代训练
4.使用模型
数据准备
以y=2x作为主体,加入一些干扰噪声。
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.randn(*train_X.shape)*0.3
说明:生成-1~1之间的100个数作为x,然后将X乘以2再加上一个[-1,1]之间的随机数×0.3(噪声),使得y≈2x
搭建模型
#创建模型
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)
说明:
X,Y:占位符,使用placeholder函数进行定义。
W,b: W被初始化成[-1,1]的随机数,形状为一维的数字,b被初始化为0,形状也是一维的数字。
cost:成本变量,它等于生成值与真实值的平方差
learning_rate:学习率,值越小越精确
迭代训练
#训练模型
#初始化所有变量
init = tf.global_variables_initializer()
#定义参数
training_epochs = 20
display_step = 2
#启动session
with tf.Session() as sess:
sess.run(init)
plotdata={"batchsize":[],"loss":[]}
#向模型中输入数据
for epoch in range(training_epochs):
for(x,y) in zip(train_X,train_Y):
sess.run(optimizer,feed_dict={X:x,Y:y})
#显示训练中的详细信息
if epoch % display_step == 0:
loss = sess.run(cost,feed_dict={X:train_X,Y:train_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=",sess.run(cost,feed_dict={X:train_X,Y:train_Y}),
"W=",sess.run(W),"b=",sess.run(b))
运行结果:
Epoch: 1 cost= 0.690374 W= [0.93709356] b= [0.35266542]
Epoch: 3 cost= 0.127353 W= [1.8180684] b= [0.11661541]
Epoch: 5 cost= 0.08249037 W= [2.05696] b= [0.02665882]
Epoch: 7 cost= 0.07982928 W= [2.1189156] b= [0.00291253]
Epoch: 9 cost= 0.079749465 W= [2.1349378] b= [-0.00323549]
Epoch: 11 cost= 0.07976955 W= [2.139082] b= [-0.00482556]
Epoch: 13 cost= 0.07977747 W= [2.1401534] b= [-0.00523691]
Epoch: 15 cost= 0.07977971 W= [2.1404312] b= [-0.00534345]
Epoch: 17 cost= 0.07978029 W= [2.1405025] b= [-0.00537088]
Epoch: 19 cost= 0.079780445 W= [2.140521] b= [-0.00537794]
Finished!
cost= 0.07978047 W= [2.1405234] b= [-0.00537907]
模型可视化
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()
使用模型
print("x=0.2,z=",sess.run(z,feed_dict={X:0.2}))
说明:预测x=0.2,y的值
结果:
x=0.2,z= [0.417329]