代码如下:
#tf可以认为是全局变量,从该变量为类,从中取input_data变量
import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf
#读取数据集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#这里用CNN方法进行训练
#函数定义部分
def weight_variable(shape):
initial=tf.truncated_normal(shape,stddev=0.1)#随机权重赋值,不过truncated_normal代表如果是2倍标准差之外的结果重新选取该值
return tf.Variable(initial)
def bias_variable(shape):
initial=tf.constant(0.1,shape=shape)#偏置项
return tf.Variable(initial)
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')#SAME表示输出补边,这里输出与输入尺寸一致
def max_pool_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')#ksize代表池化范围的大小,stride为扫描步长
# 这里是变量的占位符,一般是输入输出使用该部分
x=tf.placeholder(tf.float32,[None,784])
y_=tf.placeholder("float",[None,10])
x_image=tf.reshape(x,[-1,28,28,1])#-1表示自动计算该维度
#该部分会说明tensorboard的使用,tensorboard会显示常量、变量、结构图等
#这里做一些常见数据的显示,如结构图的显示,训练的loss,某个节点权重值的变化
#结构图的显示,这里显示是分部分的,第一层在建立时可以按照下面的方式
#正常建立第一层
#W_conv1=weight_variable([5,5,1,32])
#b_conv1=bias_variable([32])
#h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
#h_pool1=max_pool_2x2(h_conv1)
#建立第一层,并指定该部分在tensorboard显示
#这里在显示时建立了两层结构,第二层结构在part1的内部结构,放大后可以显示,后续我们只着重大的模块
with tf.name_scope('part1'):#指定显示的结构图的部分
with tf.name_scope('weights1'):
W_conv1=weight_variable([5,5,1,32])
with tf.name_scope('bias1'):
b_conv1=bias_variable([32])
with tf.name_scope('h_conv1'):
h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
with tf.name_scope('h_pool1'):
h_pool1=max_pool_2x2(h_conv1)
#第二层
with tf.name_scope('part2'):
W_conv2=weight_variable([5,5,32,64])
b_conv2=bias_variable([64])
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2=max_pool_2x2(h_conv2)
#第三层,而且这里是全连接层
with tf.name_scope('part3'):
with tf.name_scope('fcn1_dropout'):
W_fc1=weight_variable([7*7*64,1024])
b_fc1=bias_variable([1024])
h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])
h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
#dropout,注意这里也是有一个输入参数的,和x以及y一样
keep_prob=tf.placeholder(tf.float32)
h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
with tf.name_scope('fcn2_softmax'):
W_fc2=weight_variable([1024,10])
b_fc2=bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)
#之上是网络显示的部分
# 评价函数
cross_entropy=-tf.reduce_sum(y_*tf.log(y_conv))
train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction=tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
tf.summary.scalar('cross_entropy',cross_entropy)#显示优化函数的变化
tf.summary.scalar('accuracy',accuracy)#显示训练的准确率
# 启动模型,Session建立这样一个对象,然后指定某种操作,并实际进行该步
init=tf.initialize_all_variables()
sess=tf.Session()
#之前只是指定了显示的部分,我们需要将它们整合
merged=tf.summary.merge_all()
#tensorboard信息需要写到文件中,这里定义写文件的部分writer
writer=tf.summary.FileWriter("MNIST_board/", sess.graph)
sess.run(init)
#数据读取部分
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(50)#这里貌似是代表读取50张图像数据
#run第一个参数是fetch,可以是tensor也可以是Operation,第二个feed_dict是替换tensor的值
'''
if i % 10 == 0:
train_accuracy = accuracy.eval(feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})
print("step:%d,accuracy:%g" % (i, train_accuracy))
'''
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})#sess.run第一个参数是想要运行的位置,一般有train,accuracy,initdeng
#第二个参数feed_dict,一般是输入参数,该代码里有x,y以及drop的参数
if i%20==0 :
print(i)
print("train accuracy:%g"%sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5}))
result = sess.run(merged, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})#merged也是tf中的,也需要session的运行
writer.add_summary(result, i)#这里代表写入,因为只有单次所以应该写在循环中,不然会只有一次的结果
print("test accuracy:%g"%sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1}))
writer.close()
具体的用法见注释
可以看到运行结果:
然后anaconda Prompt中输入命令:
这样应该有网址出现,复制打开即可,不过貌似本人电脑缺少部分文件,一直没有成功,也是比较心塞的