1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import os import cv2
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' """------------------加载数据---------------------"""
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
trX = trX.reshape(-1, 28, 28, 1) teX = teX.reshape(-1, 28, 28, 1) """------------------构建模型---------------------"""
X = tf.placeholder("float", [None, 28, 28, 1], name="X") Y = tf.placeholder("float", [None, 10])
def init_weights(shape): return tf.Variable(tf.random_normal(shape, stddev=0.01)) w1 = init_weights([3, 3, 1, 32]) w2 = init_weights([3, 3, 32, 64]) w3 = init_weights([3, 3, 64, 128]) w4 = init_weights([128 * 4 * 4, 625]) w_o = init_weights([625, 10]) p_keep_conv = tf.placeholder("float", name="p_keep_conv") p_keep_hidden = tf.placeholder("float", name="p_keep_hidden")
def create_model(X, w1, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden): conv1 = tf.nn.conv2d(X, w1, strides=[1, 1, 1, 1], padding='SAME') conv1_out = tf.nn.relu(conv1) pool1 = tf.nn.max_pool(conv1_out, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') pool1_out = tf.nn.dropout(pool1, p_keep_conv) conv2 = tf.nn.conv2d(pool1_out, w2, strides=[1, 1, 1, 1], padding='SAME') conv2_out = tf.nn.relu(conv2) pool2 = tf.nn.max_pool(conv2_out, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') pool2_out = tf.nn.dropout(pool2, p_keep_conv) conv3 = tf.nn.conv2d(pool2_out, w3, strides=[1, 1, 1, 1], padding='SAME') conv3_out = tf.nn.relu(conv3) pool3 = tf.nn.max_pool(conv3_out, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') pool3 = tf.reshape(pool3, [-1, w4.get_shape().as_list()[0]]) pool3_out = tf.nn.dropout(pool3, p_keep_conv) fully_layer = tf.matmul(pool3_out, w4) fully_layer_out = tf.nn.relu(fully_layer) fully_layer_out = tf.nn.dropout(fully_layer_out, p_keep_hidden) out = tf.matmul(fully_layer_out, w_o) return out model = create_model(X, w1, w2, w3, w4, w_o, p_keep_conv, p_keep_hidden)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=model, labels=Y)) train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost) predict_op = tf.argmax(model, 1, name="predict")
saver=tf.train.Saver()
ckpt_dir="./ckpt_dir" if not os.path.exists(ckpt_dir): os.makedirs(ckpt_dir) """------------------训练模型或者加载模型进行测试---------------------""" train_batch_size = 128 test_batch_size = 256 epoches = 5 with tf.Session() as sess: """-------训练模型--------""" tf.global_variables_initializer().run()
"""-----加载模型,用导入的图片进行测试--------""" src = cv2.imread('./2.png') src = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) dst = cv2.resize(src, (28, 28), interpolation=cv2.INTER_CUBIC) picture = np.zeros((28, 28)) for i in range(0, 28): for j in range(0, 28): picture[i][j] = (255 - dst[i][j]) picture = picture.reshape(1, 28, 28, 1) saver.restore(sess, ckpt_dir+"/model.ckpt-4") predict_result = sess.run(predict_op, feed_dict={X: picture, p_keep_conv: 1.0, p_keep_hidden: 1.0}) print("你导入的图片是:", predict_result[0])
|