Tensorflow笔记一
一. 目的:
生成干扰数据 计算 Y = 2 * X 的结果
二.代码
# 完整代码
# 计算 Y = 2 * X 的值
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
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)]
# 生成100 个 -1 到 1 的数据
trainX = np.linspace(-1,1,100)
# 生成100个干扰数据
trainY = 2 * trainX + np.random.randn(*trainX.shape) * 0.3
# 绘图
plt.plot(trainX,trainY,'ro',label = 'I Love China')
plt.legend()
plt.show()
# 占位
X = tf.placeholder("float")
Y = tf.placeholder("float")
# 模型参数
W = tf.Variable(tf.random_normal([1]), name = 'bias')
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)
# 迭代训练模型
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(trainX,trainY):
sess.run(optimizer,feed_dict={X:x,Y:y})
# 显示训练中的详细信息
if epoch % display_step == 0:
loss = sess.run(cost,feed_dict={X:trainX,Y: trainY})
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:trainX,Y: trainY}),"W=",sess.run(W),"b=",sess.run(B))
# 图像显示
plt.plot(trainX,trainY,'ro',label = 'sad data')
plt.plot(trainX,sess.run(W)*trainX + 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()
print("x=0.2,z=",sess.run(Z,feed_dict={X:0.2}))
三、运行结果
Epoch: 1 cost = 0.19036867 W= [1.5034635] b= [0.15345636]
Epoch: 3 cost = 0.09338717 W= [1.8725581] b= [0.05529383]
Epoch: 5 cost = 0.08592511 W= [1.9727246] b= [0.01758706]
Epoch: 7 cost = 0.085566826 W= [1.9987036] b= [0.00763]
Epoch: 9 cost = 0.08558113 W= [2.0054226] b= [0.00505186]
Epoch: 11 cost = 0.08559199 W= [2.00716] b= [0.00438513]
Epoch: 13 cost = 0.08559528 W= [2.00761] b= [0.00421249]
Epoch: 15 cost = 0.085596174 W= [2.0077255] b= [0.00416822]
Epoch: 17 cost = 0.08559638 W= [2.0077548] b= [0.00415687]
Epoch: 19 cost = 0.08559645 W= [2.0077631] b= [0.00415374]
Finished
cost= 0.08559646 W= [2.0077643] b= [0.00415323]
x=0.2,z= [0.4057061]
x=0.2,z= [0.4057061]
四、小结
(1)linspace
# 作用:生成100 个 -1 到 1的数
# start 参数1: 起始位置
# stop 参数2: 结束位置
# num 参数3: 生成个数,默认50
# endpoint 参数4 :是否包含 stop 数值,默认为True,包含stop值;若为False,则不包含stop值
# retstep 参数5: 默认为False,返回等差数列数组[-1. -0.5 0. 0.5 1. ],
# 若为True,则返回结果(array([`samples`, `step`]))
# return 返回: num 个 start 到 stop 之间数组成的数组或列表
trainX = np.linspace(-1,1,100)