附录:代码
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
//加载数据集
mnist=input_data.read_data_sets("MNIST_data",one_hot=True)
sess=tf.InteractiveSession()
//构建 softmax 回归模型
x=tf.placeholder("float",shape=[None,784])
y_=tf.placeholder("float",shape=[None,10])
//构建一个多层卷积网络
//初始化权重和偏置项
def weight_variable(shape):
initial=tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
def bias_varible(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')
//第一层卷积+池化:5*5 大小的卷积核, 算出 32 个特征
W_conv1=weight_variable([5,5,1,32])
//输出通道的偏置量
b_conv1=bias_varible([32])
x_image=tf.reshape(x,[-1,28,28,1])
//第一层卷积
h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
//第二层池化
h_pool1=max_pool_2x2(h_conv1)
//第二层卷积+池化:5*5 大小的卷积核, 算出 64 个特征
W_conv2=weight_variable([5,5,32,64])
//输出通道的偏置量
b_conv2=bias_varible([64])
//第三层卷积
h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
//第四层池化
评论0