环境:python 3 ,tensorflow 1.1 , matplotlib 2.02
tensorflow1.1在构建卷积神经网络方面代码大大简化,方便很多,并且将keras作为tensorflow的高级api
#coding:utf-8
"""
python 3
tensorflow 1.1
matplotlib 2.02
"""
import tensorflow as tf
import input_data
import numpy as np
import matplotlib.pyplot as plt
#设置随机种子
tf.set_random_seed(100)
np.random.seed(100)
BATCH_SIZE = 50
learning_rate = 0.001
#读取数据
mnist = input_data.read_data_sets('mnist/',one_hot=True)
#测试数据
test_x = mnist.test.images[:2000]
test_y = mnist.test.labels[:2000]
#查看图片
plt.imshow(mnist.train.images[1].reshape((28,28)))
#坐标是one_hot (1000000000--->>>>0) np.argmax返回最大值所对应的索引
plt.title('the picture is %i' %np.argmax(mnist.train.labels[1]),fontdict={'size':16,'color':'c'})
plt.show()
#数据的形状 data:(55000,28*28),labels:(55000,10)
xs = tf.placeholder(tf.float32,[None,28*28])
ys = tf.placeholder(tf.int32,[None,10])
#传入卷积神经网络图片形状
x = tf.reshape(xs,[-1,28,28,1]) #表示图片数量,28行,28列,1个颜色通道
#构建卷积神经网络[None,28,28,1] --->>>[None,28,28,16]
conv1 = tf.layers.conv2d(inputs=x,filters=16,kernel_size=5,strides=1,padding='same',activation=tf.nn.relu)
#[None,28,28,16] --->>>[None,14,14,16]
pool1 = tf.layers.max_pooling2d(conv1,pool_size=2,strides=2)
#[None,14,14,16] --->>>[None,14,14,32]
conv2 = tf.layers.conv2d(inputs=pool1,filters=32,kernel_size=5,strides=1,padding='same',activation=tf.nn.relu)
#[None,14,14,32] --->>>[None,7,7,32]
pool2 = tf.layers.max_pooling2d(conv2,pool_size=2,strides=2)
#[None,7,7,32] --->>>[None,7*7*32]
flat = tf.reshape(pool2,[-1,7*7*32])
output = tf.layers.dense(flat,10)
#计算loss
loss = tf.losses.softmax_cross_entropy(onehot_labels=ys,logits=output)
train = tf.train.AdamOptimizer(learning_rate).minimize(loss)
#计算accuracy,返回两个参数,acc和update_op
accuracy = tf.metrics.accuracy(labels=tf.argmax(ys,axis=1),predictions=tf.argmax(output,axis=1))[1]
with tf.Session() as sess:
init = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())
sess.run(init)
for step in range(1000):
batch_x,batch_y = mnist.train.next_batch(BATCH_SIZE)
_,loss = sess.run([train,loss],feed_dict={xs:batch_x,ys:batch_y})
if step % 100 ==0:
acc = sess.run(accuracy,feed_dict={xs:batch_x,ys:batch_y})
print('= = = = = => > > > > >','step:',step,'loss: %.4f' %loss,'accuracy:%.2f' %acc)
结果: