这里的话就不多说明了,因为上上一个博客已经说明了

import numpy as np
import  tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data/', one_hot=True)


# 构造初始化参数, 方差为0.1
n_input = 784
n_output = 10
weights = {
    'wc1' : tf.Variable(tf.truncated_normal([3, 3, 1, 64], stddev=0.1)),
    'wc2' : tf.Variable(tf.truncated_normal([3, 3, 64, 128], stddev=0.1)),
    'wd1' : tf.Variable(tf.truncated_normal([7*7*128, 1024], stddev=0.1)),
    'wd2' : tf.Variable(tf.truncated_normal([1024, n_output], stddev=0.1))

}

biases = {
    'b1' : tf.Variable(tf.truncated_normal([64], stddev=0.1)),
    'b2' : tf.Variable(tf.truncated_normal([128], stddev=0.1)),
    'bd1' : tf.Variable(tf.truncated_normal([1024], stddev=0.1)),
    'bd2' : tf.Variable(tf.truncated_normal([n_output], stddev=0.1))

}

def conv_basic(_input, _w, _b, _keepratio):

    _input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])
    #进行卷积操作
    _conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
    # 使用激活函数
    _conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
    # 进行池化操作, padding='SAME', 表示维度不足就补齐
    _pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], stride=[1, 2, 2, 1], padding='SAME')
    #去除一部分数据
    _pool1_dr1 = tf.nn.dropout(_pool1, _keepratio)
    #第二次卷积操作
    _conv2 = tf.nn.conv2d(_pool1_dr1, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
    # 使用激活函数
    _conv2 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
    # 进行池化操作
    _pool2 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], stride=[1, 2, 2, 1], padding='SAME')
    _pool_dr2 = tf.nn.dropout(_pool1, _keepratio)

    # 第一次全连接操作
    # 对_pool_dr2 根据wd1重新构造函数
    _densel = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])
    _fcl = tf.nn.relu(tf.add(tf.matmul(_densel, _w['wd1'], _b['bd1'])))
    _fc_dr1 = tf.nn.dropout(_fcl, _keepratio)
    # 第二次全连接
    _out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])
    out = {'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1,
           'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1,
           'fcl': _fcl, 'fc_dr1': _fc_dr1, 'out': _out
           }
    return out


x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keepratio = tf.placeholder(tf.float32)

# FUNCTIONS

# 构造cost函数
#获得预测结果
_pred =conv_basic(x, weights, biases, keepratio)['out']
# 输入预测结果与真实值构造cost 函数
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(_pred, y))
# 优化函数使得cost最小
optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
# 计算准确率
_corr = tf.equal(tf.argmax(_pred, 1), tf.argmax(y, 1))
accr = tf.reduce_mean(tf.cast(_corr, tf.float32))
init = tf.global_variables_initializer()

# 进行训练
sess = tf.Session()
sess.run(init)
save_step = 1
# 每次只保存3个值
saver = tf.train.Saver(max_to_keep=3)
#迭代次数
training_epochs = 15
# 每次训练的样本数
batch_size      = 16
#循环打印的次数
display_step    = 1
do_train = 1
if do_train == 1:
    for epoch in range(training_epochs):
        avg_cost = 0.
        #total_batch = int(mnist.train.num_examples/batch_size)
        total_batch = 10
        # Loop over all batches
        for i in range(total_batch):
            # 提取训练数据和标签
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            #训练模型优化参数
            sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})
            # 加和损失值
            avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batch

        # Display logs per epoch step
        if epoch % display_step == 0:
            print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
            train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})
            print (" Training accuracy: %.3f" % (train_acc))
            #test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel, keepratio:1.})
            #print (" Test accuracy: %.3f" % (test_acc))
        if epoch % save_step == 0:
            saver.save(sess, "save/nets/cnn_mnist_basic.ckpt-" + str(epoch))
    print ("OPTIMIZATION FINISHED")

if do_train == 0:
    epoch = training_epochs - 1
    saver.restore(sess, "save/nets/cnn_mnist_basic.ckpt-" + str(epoch))
    # 对测试集进行测试
    feed_test = {x: mnist.test.images, y: mnist.test.labels, keepratio:1.}
    test_acc = sess.run(accr, feed_dict=feed_test)
    print(test_acc)

 

posted on 2018-09-01 15:15  python我的最爱  阅读(335)  评论(0编辑  收藏  举报