很好·的一个tensorflow初学的代码 (转)

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#mnist已经作为官方的例子,做好了数据下载,分割,转浮点等一系列工作,源码在tensorflow源码中都可以找到
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# 配置每个 GPU 上占用的内存的比例
# 没有GPU直接sess = tf.Session()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

#每个批次的大小
batch_size = 20
#定义训练轮数据
train_epoch = 1
#定义每n轮输出一次
test_epoch_n = 1

#计算一共有多少批次
n_batch = mnist.train.num_examples // batch_size
print("batch_size="+str(batch_size)+"n_batch="+str(n_batch))

#占位符,定义了输入,输出
x = tf.placeholder(tf.float32,[None, 784],name='InputFeature') 
y_ = tf.placeholder(tf.float32,[None, 10],name='InputLabel') 
#权重和偏置,使用0初始化
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

#这里定义的网络结构
y = tf.nn.softmax(tf.matmul(x,W) + b,name='NetOutput') 
#损失函数是交叉熵
#cross_entropy = -tf.reduce_sum(y_*tf.log(y))
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y))
#训练方法:
#train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
train_step = tf.train.AdamOptimizer(1e-2).minimize(cross_entropy)
#初始化sess中所有变量
init = tf.global_variables_initializer() 
sess.run(init) 

MaxACC = 0#最好的ACC
saver = tf.train.Saver()  

#训练n个epoch
for epoch in range(train_epoch): 
    for batch in range(n_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size) 
        sess.run(train_step, feed_dict = {x: batch_xs, y_: batch_ys}) 
    if(0==(epoch%test_epoch_n)):#每若干次预测test一次
        #计算test集的准确率
        correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
        now_acc=sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels})
        print('epoch=',epoch,'ACC=',now_acc)
        if(now_acc>MaxACC):
            MaxACC = now_acc
            #tf.train.write_graph(sess.graph_def,'Model2','ModelSoftmax.pbtxt')
            saver.save(sess,'Model2/ModelSoftmax.ckpt')
            print('Save model! Now ACC=',MaxACC)

#计算最终test集的准确率
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 
print('Train OK! epoch=',epoch,'ACC=',sess.run(accuracy, feed_dict={x:mnist.test.images, y_: mnist.test.labels}))

#关闭sess
sess.close()


猜你喜欢

转载自blog.csdn.net/qq_41672744/article/details/80946684
今日推荐