CNN卷积神经网络(二)

来源:互联网 发布:网络策略游戏 编辑:程序博客网 时间:2024/06/04 18:21

这里主要是对上一篇的Tensorflow搭建卷积神经网络模型进行了一些修改,并且在测试数据上对模型进行了测试,准确率99.3%

# 卷积网络的训练数据为MNIST(28*28灰度单色图像)import tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltfrom tensorflow.examples.tutorials.mnist import input_data
# 训练参数train_epochs    = 100     # 训练轮数batch_size      = 100     # 随机抽取数据大小display_step    = 1       # 显示训练结果的间隔learning_rate   = 0.0001  # 学习效率fch_nodes       = 512     # 全连接隐藏层神经元的个数train_keep_prob = 0.5     # 全连接层正则化参数c1_kernel       = [5, 5, 1, 16]c2_kernel       = [5, 5, 16, 32]p1_ksize        = [1, 2, 2, 1]p2_ksize        = [1, 2, 2, 1]
# 网络模型需要的一些辅助函数def weight_init(shape):    weights = tf.truncated_normal(shape, stddev=0.1,dtype=tf.float32)    return tf.Variable(weights)# 偏置的初始化def biases_init(shape):    biases = tf.random_normal(shape,dtype=tf.float32)    return tf.Variable(biases)# 随机选取mini_batchdef get_random_batchdata(n_samples, batchsize):    start_index = np.random.randint(0, n_samples - batchsize)    return (start_index, start_index + batchsize)
# 全连接层权重初始化函数xavierdef xavier_init(layer1, layer2, constant = 1):    Min = -constant * np.sqrt(6.0 / (layer1 + layer2))    Max = constant * np.sqrt(6.0 / (layer1 + layer2))    return tf.Variable(tf.random_uniform((layer1, layer2), minval = Min, maxval = Max, dtype = tf.float32))
# 卷积def conv2d(x, w):    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')# x 张量的维度[batch, height, width, channels]# w 卷积核的维度[height, width, channels, channels_multiplier]# padding 参数'SAME',表示对原始输入像素进行填充,卷积后映射的2D图像与原图大小相等
# 池化def max_pool_2x2(x, ksize):    return tf.nn.max_pool(x, ksize= ksize, strides=[1, 2, 2, 1], padding='SAME')# ksize 的维度[batch, height, width, channels],跟 x 张量相同# strides [1, 2, 2, 1],与上面对应维度的移动步长
# x 是手写图像的像素值,y 是图像对应的标签x = tf.placeholder(tf.float32, [None, 784])y = tf.placeholder(tf.float32, [None, 10])# 把灰度图像一维向量,转换为28x28二维结构x_image = tf.reshape(x, [-1, 28, 28, 1])# -1表示任意数量的样本数,大小为28x28深度为一的张量
# 第一层卷积+池化w_conv1 = weight_init(c1_kernel)                              b_conv1 = biases_init([c1_kernel[-1]])h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)     h_pool1 = max_pool_2x2(h_conv1, p1_ksize)                       
# 第二层卷积+池化w_conv2 = weight_init(c2_kernel)                             b_conv2 = biases_init([c2_kernel[-1]])h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)    h_pool2 = max_pool_2x2(h_conv2, p2_ksize)                                  
# 全连接层# h_pool2是一个7x7x32的tensor,将其转换为一个一维的向量h_fpool2 = tf.reshape(h_pool2, [-1, 7*7*32])# 全连接层,隐藏层节点为512个# 权重初始化w_fc1 = xavier_init(7*7*32, fch_nodes)b_fc1 = biases_init([fch_nodes])h_fc1 = tf.nn.relu(tf.matmul(h_fpool2, w_fc1) + b_fc1)
# 全连接隐藏层/输出层# 为了防止网络出现过拟合的情况,对全连接隐藏层进行 Dropout(正则化)处理,在训练过程中随机的丢弃部分keep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)# 隐藏层与输出层权重初始化w_fc2 = xavier_init(fch_nodes, 10)b_fc2 = biases_init([10])# 未激活的输出y_ = tf.add(tf.matmul(h_fc1_drop, w_fc2), b_fc2)# 激活后的输出y_out = tf.nn.softmax(y_)
# 交叉熵代价函数cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_out), reduction_indices = [1]))# 优化器选择Adam(有多个选择)optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)# 准确率# 每个样本的预测结果是一个(1,10)的vectorcorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_out, 1))# tf.cast把bool值转换为浮点数accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 全局变量进行初始化的Operationinit = tf.global_variables_initializer()
# 加载数据集MNISTmnist = input_data.read_data_sets('MNIST/mnist', one_hot=True)n_samples = int(mnist.train.num_examples)total_batches = int(n_samples / batch_size)
Extracting MNIST/mnist/train-images-idx3-ubyte.gzExtracting MNIST/mnist/train-labels-idx1-ubyte.gzExtracting MNIST/mnist/t10k-images-idx3-ubyte.gzExtracting MNIST/mnist/t10k-labels-idx1-ubyte.gz
sess = tf.Session()sess.run(init)
Train_cost = []for i in range(train_epochs):    # 随机抽取batch data 的次数    for j in range(10):        start_index, end_index = get_random_batchdata(n_samples, batch_size)        batch_x = mnist.train.images[start_index: end_index]        batch_y = mnist.train.labels[start_index: end_index]        _ , cost= sess.run([ optimizer,cross_entropy], feed_dict={x:batch_x, y:batch_y,keep_prob:train_keep_prob})        Train_cost.append(cost)    if i % display_step ==0:        print ('Epoch : %d , Train cost: %.7f'%(i+1,cost))print 'training finished'
Epoch : 10 , Train cost: 0.0080721Epoch : 11 , Train cost: 0.0110888 ........Epoch : 100 , Train cost: 0.0023396training finished

Test 结果

accu = sess.run(accuracy, feed_dict={x:mnist.test.images,y:mnist.test.labels , keep_prob:1.0})print ('Test result is: %.7f'%(accu))
Test result is: 0.9930000

input image的可视化

# 从训练数据中选取了一个样本,转换为一个28x28的以为数组fig2,ax2 = plt.subplots(figsize=(2,2))ax2.imshow(np.reshape(mnist.train.images[14], (28, 28)))plt.show()

png这里写图片描述

第一个卷基层

# 第一层的卷积输出的特征图input_image = mnist.train.images[14:15]conv1_16 = sess.run(h_conv1, feed_dict={x:input_image})          # [16, 28, 28 ,1] conv1_reshape = sess.run(tf.reshape(conv1_16, [16, 1, 28, 28]))fig3,ax3 = plt.subplots(nrows=1, ncols=16, figsize = (16,1))for i in range(16):    ax3[i].imshow(conv1_reshape[i][0])                          # tensor的切片[batch, channels, row, column] plt.title('Conv1 16x28x28')plt.show()

png这里写图片描述

第一个池化层

# 第一层池化后的特征图pool1_16 = sess.run(h_pool1, feed_dict={x:input_image})          # [16, 14, 14, 1]pool1_reshape = sess.run(tf.reshape(pool1_16, [16, 1, 14, 14]))fig4,ax4 = plt.subplots(nrows=1, ncols=16, figsize=(16,1))for i in range(16):    ax4[i].imshow(pool1_reshape[i][0])plt.title('Pool1 16x14x14')plt.show()

png这里写图片描述

第二层卷积

# 第二层卷积输出特征图conv2_32 = sess.run(h_conv2, feed_dict={x:input_image})          # [32, 14, 14, 1]conv2_reshape = sess.run(tf.reshape(conv2_32, [32, 1, 14, 14]))fig5,ax5 = plt.subplots(nrows=1, ncols=32, figsize = (32, 1))for i in range(32):    ax5[i].imshow(conv2_reshape[i][0])plt.title('Conv2 32x14x14')plt.show()

png这里写图片描述

第二层池化

# 第二层池化后的特征图pool2_32 = sess.run(h_pool2, feed_dict={x:input_image})          # [32, 7, 7, 1]pool2_reshape = sess.run(tf.reshape(pool2_32, [32, 1, 7, 7]))fig6,ax6 = plt.subplots(nrows=1, ncols=32, figsize = (32, 1))plt.title('Pool2 32x7x7')for i in range(32):    ax6[i].imshow(pool2_reshape[i][0])plt.show()

png这里写图片描述

sess.close()
原创粉丝点击