tensorflow3 mnist2

#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()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值