from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) print(mnist.train.images.shape, mnist.train.labels.shape) print(mnist.test.images.shape, mnist.test.labels.shape) print(mnist.validation.images.shape, mnist.validation.labels.shape) import tensorflow as tf sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b) y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))//第二个参数reduction_indices不指定
,那么就在所有的元素中取平均值;
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) tf.global_variables_initializer().run() //若是用的tf.Session,则这里初始化要用,sess.run(tf.initalize_all_variables()) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) train_step.run({x: batch_xs, y_: batch_ys}) // sess.run(train_step, feed_dict={x:batch_xs, y_:batch_ys})也可以 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x:mnist.train.images, y_:mnist.train.labels}))
//指定第二个参数为0,则第一维的元素取平均值,即每一列求平均值;指定第二个参数为1,则第二维的元素取平均值,即每一行求平均值
print(sess.run(accuracy, feed_dict={x:mnist.test.images, y_:mnist.test.labels}))
print(sess.run(accuracy, feed_dict={x:mnist.validation.images, y_:mnist.validation.labels}))
#保存模型
saver = tf.train.Saver()
saver.save(sess, "/home/magina/Documents/mnist_model/model.ckpt")
接下来就是试验自己写的数字了
rom PIL import Image import tensorflow as tf import matplotlib.pyplot as plt im = Image.open('/home/magina/Downloads/0.jpg').convert('L') //利用手机拍照,然后处理,不过图像不理想 img = im.resize((28, 28)) arr = [] for i in range(28): for j in range(28): # mnist 里的颜色是0代表白色(背景),1.0代表黑色 pixel = 1-float(img.getpixel((j, i)))/255.0 # getpixel返回指定位置的像素 arr.append(pixel) x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x,W)+b) saver=tf.train.Saver() with tf.Session() as sess: saver.restore(sess, "/home/magina/Documents/mnist_model/model.ckpt") //加载参数模型 print ("Model restored.") prediction=tf.argmax(y,1) print(type(prediction)) #predint=prediction.eval(feed_dict={x: [arr]}) # print(predint[0]) print(sess.run(prediction[0], feed_dict={x: [arr]}))
把权重用图像表示
from PIL import Image import tensorflow as tf import matplotlib.pyplot as plt x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x,W)+b) saver=tf.train.Saver() with tf.Session() as sess: saver.restore(sess, "/home/magina/Documents/mnist_model/model.ckpt") print ("Model restored.") for i in range(10): plt.subplot(2, 5, i+1) weight = sess.run(W)[:,i] plt.title(i) plt.imshow(weight.reshape([28,28]), cmap=plt.get_cmap('seismic')) plt.show()