网络结构:
输入 --> 卷积层1 --> 池化层1 --> 卷积层2 --> 池化层2 --> 全连接层1 -- 全连接层1 -->输出层
图片大小的尺度变化:
输入 : 784*1
卷积层1 : 28*28*32
池化层1 : 14*14*32
卷积层2 : 14*14*64
池化层2 : 7*7*64
全连接层1 : 1024
全连接层2 : 10
代码如下所示:
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 20:37:23 2019
@author: 666
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#设置批次
batch_size = 10
#计算一共有多少个批次
n_batch = mnist.train.num_examples
#初始化权值
def weight_variable(shape):
return tf.Variable(tf.truncated_normal(shape,stddev=0.1))
#初始化偏置项
def bias_variable(shape):
return tf.Variable(tf.constant(0.1,shape = shape))
#卷积层
def cov2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#池化层
def max_pooling_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
#对x进行变形操作,本来是784*1的向量,需要变成4D的向量,[batch(批次),in_height(高),in_weight(宽),channel(通道)]
x_image = tf.reshape(x,[-1,28,28,1])
#初始化第一个卷积的权值和偏置项
W_cov1 = weight_variable([5,5,1,32])
b_cov1 = bias_variable([32])
#进行第一层卷积,并用激活函数激活
h_conv1 = tf.nn.relu(cov2d(x_image,W_cov1) + b_cov1)
h_pool1 = max_pooling_2x2(h_conv1)
#初始化第一个卷积的权值和偏置项
W_cov2 = weight_variable([5,5,32,64])
b_cov2 = bias_variable([64])
#进行第二层卷积,并用激活函数激活
h_conv2 = tf.nn.relu(cov2d(h_pool1,W_cov2) + b_cov2)
h_pool2 = max_pooling_2x2(h_conv2)
#部分数据的计算
#经过第一个卷积层,图片大小不变,为 28*28
#经过第一个池化层 2*2,图片大小变为 14*14
#经过第二个卷积层,图片大小不变,为 14*14
#经过第二个池化层 2*2,图片大小变为 7*7
#经过上述操作,一共产生了64张 7*7 的图片
#初始化第一个全连接层
W_fc1 = weight_variable([7*7*64,1024])
b_fc1 = bias_variable([1024])
#将池化层2扁平为1维
h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
#求第一个全连接层的输出
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
#dropout
keep_prob = tf.placeholder(tf.float32)
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.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#定义优化器
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#结果存入bool类型的值
correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Session(config = config) as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(21):
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict = {x:batch_xs,y:batch_ys,keep_prob:0.7})
acc = sess.run(accuracy,feed_dict= {x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
print('Iter '+ str(epoch) + ", Test accuracy = "+str(acc))
结果如图所示:
哈哈哈,并没有,别问我为什么,我需要一个1080t