生活随笔
收集整理的這篇文章主要介紹了
tensorflow随笔-线性拟合以及tensorboard
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
運(yùn)行程序,并查看生成的匯總信息
[root@VM_0_3_centos learn]# python36 learn1.py
2018-12-19 09:22:26.676337: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
epoch: 1 cost: 1.7284197 W: [-0.0083635] b: [0.56105036]
epoch: 11 cost: 0.07411575 W: [1.9666643] b: [-0.02874836]
epoch: 21 cost: 0.0741418 W: [1.9690341] b: [-0.0296577]
epoch: 31 cost: 0.07414182 W: [1.9690363] b: [-0.02965866]
epoch: 41 cost: 0.07414182 W: [1.9690363] b: [-0.02965866]
ok
[root@VM_0_3_centos learn]# ls log
mnist_with_summaries
[root@VM_0_3_centos learn]# cd log/mnist_with_summaries
[root@VM_0_3_centos mnist_with_summaries]# ls
events.out.tfevents.1545182546.VM_0_3_centos
[root@VM_0_3_centos mnist_with_summaries]#
啟動(dòng)tensorboard查看信息
tensorboard -logdir /root/learn/log/mnist_with_summaries
# -*- coding:utf-8 -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as pltdef moving_average(a,w=10):"""移動(dòng)平均 """if len(a)<w:return a[:]return [val if idx <w else sum(a[(idx-w):idx]/w) for idx,val in enumerate(a)]
#生成模擬數(shù)據(jù)
trainX=np.linspace(-1,1,100)
trainY=2*trainX+np.random.randn(*trainX.shape)*0.3#y=2x,但是加入噪聲
tf.reset_default_graph()
#創(chuàng)建模型
x_=tf.placeholder("float")
y_=tf.placeholder("float")
w=tf.Variable(tf.random_normal([1]),name="w")
b=tf.Variable(tf.zeros([1]),name="b")
#構(gòu)建前向網(wǎng)絡(luò)
z=tf.multiply(x_,w)+b
tf.summary.histogram('z',z)
#反向優(yōu)化
cost=tf.reduce_mean(tf.square(y_-z))
tf.summary.scalar('loss',cost)#計(jì)算損失匯總
learnRate=0.01
#梯度下降
optimizer=tf.train.GradientDescentOptimizer(learnRate).minimize(cost)
#初始化變量
init=tf.global_variables_initializer()
#參數(shù)設(shè)置
tranningEpochs=50
dispStep=10
#開(kāi)始訓(xùn)練
with tf.Session() as sess: sess.run(init)mergedSummaryOp=tf.summary.merge_all()#將所有merge操作合在一個(gè)操作里summaryWriter=tf.summary.FileWriter('log/mnist_with_summaries',sess.graph)
#向模型輸入數(shù)據(jù)for epoch in np.arange(tranningEpochs):for (x,y) in zip(trainX,trainY):sess.run(optimizer,feed_dict={x_:x,y_:y})#根據(jù)損失計(jì)算梯度summaryStr=sess.run(mergedSummaryOp,feed_dict={x_:x,y_:y})summaryWriter.add_summary(summaryStr,epoch)#將summary寫入文件if epoch%dispStep==0:#訓(xùn)練中的詳細(xì)信息runLoss=sess.run(cost,feed_dict={x_:trainX,y_:trainY})print("epoch:",epoch+1,"cost:",runLoss,"W:",sess.run(w),"b:",sess.run(b))print("ok")
總結(jié)
以上是生活随笔為你收集整理的tensorflow随笔-线性拟合以及tensorboard的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。