本次通过CNN来实现Mnist
该模型在可以识别原数据集的前提下,加入了可以识别艺术体数字的功能。
先给出未经训练的模型的程序,你可以自己设定训练次数并将参数数据保存到自己想要保存的位置:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
return result
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
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')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_falt = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_falt, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
counter = 10
for step in range(10000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if step % 1000 == 0:
counter -= 1
print('the remaining times trained is ', counter * 1000, '.')
print('the current accuracy is ', compute_accuracy(mnist.test.images, mnist.test.labels), '.')
print()
saver = tf.train.Saver()
save_path = saver.save(sess, 'Mnist_parameter_CNN/save_parameter.ckpt')
print('The training has been end!')
接下来给出已经训练好的模型的程序,你可以通过绝对路径或相对路径来上传你想要识别的艺术体数字的图片:
import tensorflow as tf
import numpy as np
from PIL import Image
import random
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def get_picture(img_path):
img = Image.open(img_path)
img = img.resize((28, 28), Image.ANTIALIAS).convert('L')
img = np.array(img.getdata()).reshape((1, 784))
img = [10*(255-x)*1.0/255.0 for x in img]
return img[0]
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
return result
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
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')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28, 28, 1])
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_falt = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_falt, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
saver = tf.train.Saver()
saver.restore(sess, 'Mnist_parameter_CNN/save_parameter.ckpt')
min = random.randint(0, len(mnist.test.labels))
max = random.randint(0, len(mnist.test.labels))
if min > max:
min, max = max, min
max += 1
for i in range(min, max):
prediction_num = sess.run(prediction, feed_dict={xs: np.array([mnist.test.images[i]]), keep_prob: 1})
prediction_number = np.argmax(prediction_num, axis=1)
print('The predictive number is ', prediction_number[0], '.', end=' ')
ys_num = sess.run(ys, feed_dict={ys: np.array([mnist.test.labels[i]]), keep_prob: 1})
ys_number = np.argmax(ys_num, axis=1)
print(' The actual number is ', ys_number[0], '.')
print()
max -= 1
print('The random test interval is [', min, ',', max, '].')
print()
recognition_accuracy = compute_accuracy(mnist.test.images, mnist.test.labels)
print('The current recognition accuracy is', recognition_accuracy, '.')
print()
print('Loading image or not? Y/N')
choice = input()
while(choice != 'Y' and choice != 'N'):
print('Warning! Please input Y or N rather than any other words!')
choice = input()
if choice == 'Y':
while(1):
print('You have chosen to load image, please input the path of the image and the model will recognize it.')
path = input()
path = 'number_picture/' + path
number_picture = get_picture(path)
prediction_num = sess.run(prediction, feed_dict={xs: np.array([number_picture]), keep_prob: 1})
prediction_num = np.argmax(prediction_num, axis=1)
print('The predictive number is ', prediction_num[0], '.')
print('Continuing to input the image or not? Y/N')
choice = input()
while (choice != 'Y' and choice != 'N'):
print('Warning! Please input Y or N rather than any other words!')
choice = input()
if choice == 'N':
break
print('The model is over.')
elif choice == 'N':
print('You have not chosen to load image and the model is over.')