tensorflow-线性拟合以及tensorboard

运行程序,并查看生成的汇总信息

[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]# 

启动tensorboard查看信息
tensorboard -logdir /root/learn/log/mnist_with_summaries

# -*- coding:utf-8 -*-
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)]
#生成模拟数据
trainX=np.linspace(-1,1,100)
trainY=2*trainX+np.random.randn(*trainX.shape)*0.3#y=2x,但是加入噪声
tf.reset_default_graph()
#创建模型
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")
#构建前向网络
z=tf.multiply(x_,w)+b
tf.summary.histogram('z',z)
#反向优化
cost=tf.reduce_mean(tf.square(y_-z))
tf.summary.scalar('loss',cost)#计算损失汇总
learnRate=0.01
#梯度下降
optimizer=tf.train.GradientDescentOptimizer(learnRate).minimize(cost)
#初始化变量
init=tf.global_variables_initializer()
#参数设置
tranningEpochs=50
dispStep=10
#开始训练
with tf.Session() as sess: 
    sess.run(init)
    mergedSummaryOp=tf.summary.merge_all()#将所有merge操作合在一个操作里
    summaryWriter=tf.summary.FileWriter('log/mnist_with_summaries',sess.graph)
#向模型输入数据
    for epoch in np.arange(tranningEpochs):
        for (x,y) in zip(trainX,trainY):
            sess.run(optimizer,feed_dict={x_:x,y_:y})#根据损失计算梯度
            summaryStr=sess.run(mergedSummaryOp,feed_dict={x_:x,y_:y})
            summaryWriter.add_summary(summaryStr,epoch)#将summary写入文件
        if epoch%dispStep==0:#训练中的详细信息
            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")

猜你喜欢

转载自blog.51cto.com/13959448/2332650
今日推荐