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浏览器打开即可