tensorflow 11 -tensorboard网络结构

本文介绍了一个使用TensorFlow实现的简单神经网络模型,该模型在MNIST手写数字数据集上进行训练和测试。通过定义占位符、权重、偏置等,构建了网络结构,并使用梯度下降法进行参数优化。最后,评估了模型在测试集上的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

#定义每个批次的大小,训练模型的时候一次放入一个批次
batch_size = 8
#计算一共有多ti少个批次,//为整除
n_batch = mnist.train.num_examples // batch_size

#定义命名空间
with tf.name_scope('input'):  
    #定义两个占位符,784是28*28的size,把图像拉长为784的向量,None是批次
    x = tf.placeholder(tf.float32,[None,784],name='x_input')
    y = tf.placeholder(tf.float32,[None,10],name='y_input')

#test_x = mnist.test.images
#test_y = mnist.test.labels
with tf.name_scope('layer'):
    with tf.name_scope('weights'):
        #创建一个简单的神经网络
        W1 = tf.Variable(tf.random_normal([784,10]),name='W')
    with tf.name_scope('biases'):
        b1 = tf.Variable(tf.zeros([1,10]),name='b')
    with tf.name_scope('wx_plus_b'):
        wx_plus_b = tf.matmul(x,W1)+b1
        #分类问题一般需要在输出之后加上一个softmax,让输出的概率相加为1
    with tf.name_scope('output'):
        output = tf.nn.softmax(wx_plus_b)

with tf.name_scope('loss'):
    #定义二次代价函数
    loss = tf.reduce_mean(tf.square(y-output))
    #适合于softmax的对数似然交叉熵函数
    #loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=output))

with tf.name_scope('train'):
    lr=0.5
    #梯度下降
    train = tf.train.GradientDescentOptimizer(lr).minimize(loss)

#初始化
init = tf.global_variables_initializer()
#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(output,1))

with tf.name_scope('Accuracy'):
    with tf.name_scope('correct_prediction'):
        #结果存放在一个布尔型列表中
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(output,1))
    with tf.name_scope('accuracy'):
        #求准确率,cast函数是转换类型从布尔到浮点型,然后求平均
        acc = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

with tf.Session() as sess:
    sess.run(init)
    writer = tf.summary.FileWriter('logs/',sess.graph)
    #每一个epoch都要把所有的图片喂到网络里面
    for epoch in range(1):
        #每次喂多少个图片
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train,feed_dict={x:batch_xs,y:batch_ys})
            
        #每个epoch结束看下准确率
        accuracy = sess.run(acc,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print("iter = " + str(epoch) + ",test_acc = " + str(accuracy))
        
        #if epoch%10 == 0:
        #    lr = 0.1*lr

 在anaconda prompt中输入

tensorboard --logdir=C:\Users\HSI\tensorflow\logs

后面那个是你的logs的文件夹

然后会出现一个网站,用Google浏览器打开即可 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值