#coding=utf8 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data',one_hot=True) def weight_variable(shape): initial = tf.truncated_normal(shape,stddev=0.1) #从截断的正态分布中输出随机值。 #生成的值服从具有指定平均值和标准偏差的正态分布,如果生成的值大于平均值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') #http://www.jianshu.com/p/05c4f1621c7e #VALID不会添加新元素,SAME添加元素使得卷积前后尺寸不变 def max_pool_2x2(x): return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') x = tf.placeholder(tf.float32,[None,784]) y_actual = tf.placeholder(tf.float32,[None,10]) x_image = tf.reshape(x,[-1,28,28,1]) # w1 = weight_variable([5,5,1,32]) b1 = bias_variable([32]) conv1 = tf.nn.relu(conv2d(x_image,w1)+b1) pool1 = max_pool_2x2(conv1)#输出14x14x32 #第二个卷积层 w2 = weight_variable([5,5,32,64]) # 5x5的卷积,32维度的输入, 64 维度的输出 b2 = bias_variable([64]) conv2 = tf.nn.relu(conv2d(pool1,w2)+b2) pool2 = max_pool_2x2(conv2) #输出7x7x64 #全连接层1 fc_w1 = weight_variable([7 * 7 * 64, 1024]) fc_b1 = bias_variable([1024]) #将pool2特征层展平 pool2_flat = tf.reshape(pool2,[-1,7*7*64]) fc1 =tf.nn.relu(tf.matmul(pool2_flat,fc_w1)+fc_b1) #全连接层2 fc_w2 = weight_variable([1024,10]) fc_b2 = weight_variable([10]) y = tf.matmul(fc1,fc_w2)+fc_b2 loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_actual,logits=y)) train_step = tf.train.AdamOptimizer(0.0001).minimize(loss) correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_actual, 1)) accuracy = tf.reduce_sum(tf.cast(correct_prediction, tf.float32)) #计算正确的个数 def train(): saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(1000): batch_x, batch_y = mnist.train.next_batch(1000) if i%10 == 0: print(sess.run(accuracy,feed_dict={x: batch_x, y_actual: batch_y})) sess.run(train_step,feed_dict={x:batch_x,y_actual:batch_y}) saver.save(sess, "D:\workspace\save_model\mnist3\mnist.ckpt")#window下面保存的保存路径还是写绝对路径比较安全 #如果显存够可以使用下面的测试 #print(sess.run(accuracy,feed_dict={x: mnist.train.images, y_actual: mnist.train.labels})) #print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_actual:mnist.test.labels})) #保存读取模型参考 http://blog.csdn.net/marsjhao/article/details/72829635 def test(): saver = tf.train.Saver() with tf.Session() as sess: #saver = tf.train.import_meta_graph("D:\workspace\save_model\mnist3\mnist.ckpt.meta") saver.restore(sess, r"D:\workspace\save_model\mnist3\mnist.ckpt") # 注意此处路径前添加"./" right = 0 for i in range(10): test_x,test_y = mnist.test.next_batch(1000) #注意这里将accuracy计算方式改掉了,之前是直接计算准确率,现在是统计正确的个数 right = right + (sess.run(accuracy,feed_dict={x:test_x,y_actual:test_y})) print(right/10000) if __name__ == '__main__': test()
tensorflow3 mnist2
最新推荐文章于 2021-05-28 22:49:42 发布