侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

TensorFlow实现简单的CNN的方法

技术  /  管理员 发布于 7年前   182

这里,我们将采用Tensor Flow内建函数实现简单的CNN,并用MNIST数据集进行测试

第1步:加载相应的库并创建计算图会话

import numpy as npimport tensorflow as tffrom tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_setsimport matplotlib.pyplot as plt #创建计算图会话sess = tf.Session()

第2步:加载MNIST数据集,这里采用TensorFlow自带数据集,MNIST数据为28×28的图像,因此将其转化为相应二维矩阵

#数据集data_dir = 'MNIST_data'mnist = read_data_sets(data_dir) train_xdata = np.array([np.reshape(x,[28,28]) for x in mnist.train.images] )test_xdata = np.array([np.reshape(x,[28,28]) for x in mnist.test.images] ) train_labels = mnist.train.labelstest_labels = mnist.test.labels

第3步:设置模型参数

这里采用随机批量训练的方法,每训练10次对测试集进行测试,共迭代1500次,学习率采用指数下降的方式,初始学习率为0.1,每训练10次,学习率乘0.9,为了进行对比,后面会给出固定学习率为0.01的损失曲线图和准确率图

#设置模型参数 batch_size = 100 #批量训练图像张数initial_learning_rate = 0.1 #学习率global_step = tf.Variable(0, trainable=False) ;learning_rate = tf.train.exponential_decay(initial_learning_rate,          global_step=global_step,          decay_steps=10,decay_rate=0.9) evaluation_size = 500 #测试图像张数 image_width = 28 #图像的宽和高image_height = 28 target_size = 10  #图像的目标为0~9共10个目标num_channels = 1    #灰度图,颜色通道为1generations = 1500  #迭代500次evaluation_step = 10 #每训练十次进行一次测试 conv1_features = 25  #卷积层的特征个数conv2_features = 50 max_pool_size1 = 2  #池化层大小max_pool_size2 = 2 fully_connected_size = 100 #全连接层的神经元个数

第4步:声明占位符,注意这里的目标y_target类型为int32整型

#声明占位符 x_input_shape = [batch_size,image_width,image_height,num_channels]x_input = tf.placeholder(tf.float32,shape=x_input_shape)y_target = tf.placeholder(tf.int32,shape=[batch_size]) evaluation_input_shape = [evaluation_size,image_width,image_height,num_channels]evaluation_input = tf.placeholder(tf.float32,shape=evaluation_input_shape)evaluation_target = tf.placeholder(tf.int32,shape=[evaluation_size])

第5步:声明卷积层和全连接层的权重和偏置,这里采用2层卷积层和1层隐含全连接层

#声明卷积层的权重和偏置#卷积层1#采用滤波器为4X4滤波器,输入通道为1,输出通道为25conv1_weight = tf.Variable(tf.truncated_normal([4,4,num_channels,conv1_features],stddev=0.1,dtype=tf.float32))conv1_bias = tf.Variable(tf.truncated_normal([conv1_features],stddev=0.1,dtype=tf.float32)) #卷积层2#采用滤波器为4X4滤波器,输入通道为25,输出通道为50conv2_weight = tf.Variable(tf.truncated_normal([4,4,conv1_features,conv2_features],stddev=0.1,dtype=tf.float32))conv2_bias = tf.Variable(tf.truncated_normal([conv2_features],stddev=0.1,dtype=tf.float32)) #声明全连接层权重和偏置 #卷积层过后图像的宽和高conv_output_width = image_width // (max_pool_size1 * max_pool_size2) #//表示整除conv_output_height = image_height // (max_pool_size1 * max_pool_size2) #全连接层的输入大小full1_input_size = conv_output_width * conv_output_height *conv2_features full1_weight = tf.Variable(tf.truncated_normal([full1_input_size,fully_connected_size],stddev=0.1,dtype=tf.float32))full1_bias = tf.Variable(tf.truncated_normal([fully_connected_size],stddev=0.1,dtype=tf.float32)) full2_weight = tf.Variable(tf.truncated_normal([fully_connected_size,target_size],stddev=0.1,dtype=tf.float32))full2_bias = tf.Variable(tf.truncated_normal([target_size],stddev=0.1,dtype=tf.float32))

第6步:声明CNN模型,这里的两层卷积层均采用Conv-ReLU-MaxPool的结构,步长为[1,1,1,1],padding为SAME

全连接层隐层神经元为100个,输出层为目标个数10

def my_conv_net(input_data):   #第一层:Conv-ReLU-MaxPool  conv1 = tf.nn.conv2d(input_data,conv1_weight,strides=[1,1,1,1],padding='SAME')  relu1 = tf.nn.relu(tf.nn.bias_add(conv1,conv1_bias))  max_pool1 = tf.nn.max_pool(relu1,ksize=[1,max_pool_size1,max_pool_size1,1],strides=[1,max_pool_size1,max_pool_size1,1],padding='SAME')   #第二层:Conv-ReLU-MaxPool  conv2 = tf.nn.conv2d(max_pool1, conv2_weight, strides=[1, 1, 1, 1], padding='SAME')  relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_bias))  max_pool2 = tf.nn.max_pool(relu2, ksize=[1, max_pool_size2, max_pool_size2, 1],    strides=[1, max_pool_size2, max_pool_size2, 1], padding='SAME')   #全连接层  #先将数据转化为1*N的形式  #获取数据大小  conv_output_shape = max_pool2.get_shape().as_list()  #全连接层输入数据大小  fully_input_size = conv_output_shape[1]*conv_output_shape[2]*conv_output_shape[3] #这三个shape就是图像的宽高和通道数  full1_input_data = tf.reshape(max_pool2,[conv_output_shape[0],fully_input_size])  #转化为batch_size*fully_input_size二维矩阵  #第一层全连接  fully_connected1 = tf.nn.relu(tf.add(tf.matmul(full1_input_data,full1_weight),full1_bias))  #第二层全连接输出  model_output = tf.nn.relu(tf.add(tf.matmul(fully_connected1,full2_weight),full2_bias))#shape = [batch_size,target_size]   return model_output model_output = my_conv_net(x_input)test_model_output = my_conv_net(evaluation_input)

第7步:定义损失函数,这里采用softmax函数作为损失函数

#损失函数 loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output,labels=y_target))

第8步:建立测评与评估函数,这里对输出层进行softmax,再通过np.argmax找出每行最大的数所在位置,再与目标值进行比对,统计准确率

#预测与评估prediction = tf.nn.softmax(model_output)test_prediction = tf.nn.softmax(test_model_output) def get_accuracy(logits,targets):  batch_predictions = np.argmax(logits,axis=1)#返回每行最大的数所在位置  num_correct = np.sum(np.equal(batch_predictions,targets))  return 100*num_correct/batch_predictions.shape[0]

第9步:初始化模型变量并创建优化器

#创建优化器opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)train_step = opt.minimize(loss) #初始化变量init = tf.initialize_all_variables()sess.run(init)

第10步:随机批量训练并进行绘图

#开始训练 train_loss = []train_acc = []test_acc = []Learning_rate_vec = []for i in range(generations):  rand_index = np.random.choice(len(train_xdata),size=batch_size)  rand_x = train_xdata[rand_index]  rand_x = np.expand_dims(rand_x,3)  rand_y = train_labels[rand_index]  Learning_rate_vec.append(sess.run(learning_rate, feed_dict={global_step: i}))  train_dict = {x_input:rand_x,y_target:rand_y}   sess.run(train_step,feed_dict={x_input:rand_x,y_target:rand_y,global_step:i})  temp_train_loss = sess.run(loss,feed_dict=train_dict)  temp_train_prediction = sess.run(prediction,feed_dict=train_dict)  temp_train_acc = get_accuracy(temp_train_prediction,rand_y)   #测试集  if (i+1)%evaluation_step ==0:    eval_index = np.random.choice(len(test_xdata),size=evaluation_size)    eval_x = test_xdata[eval_index]    eval_x = np.expand_dims(eval_x,3)    eval_y = test_labels[eval_index]      test_dict = {evaluation_input:eval_x,evaluation_target:eval_y}    temp_test_preds = sess.run(test_prediction,feed_dict=test_dict)    temp_test_acc = get_accuracy(temp_test_preds,eval_y)     test_acc.append(temp_test_acc)  train_acc.append(temp_train_acc)  train_loss.append(temp_train_loss)    #画损失曲线fig = plt.figure()ax = fig.add_subplot(111)ax.plot(train_loss,'k-')ax.set_xlabel('Generation')ax.set_ylabel('Softmax Loss')fig.suptitle('Softmax Loss per Generation') #画准确度曲线index = np.arange(start=1,stop=generations+1,step=evaluation_step)fig2 = plt.figure()ax2 = fig2.add_subplot(111)ax2.plot(train_acc,'k-',label='Train Set Accuracy')ax2.plot(index,test_acc,'r--',label='Test Set Accuracy')ax2.set_xlabel('Generation')ax2.set_ylabel('Accuracy')fig2.suptitle('Train and Test Set Accuracy')  #画图fig3 = plt.figure()actuals = rand_y[0:6]train_predictions = np.argmax(temp_train_prediction,axis=1)[0:6]images = np.squeeze(rand_x[0:6])Nrows = 2Ncols =3 for i in range(6):  ax3 = fig3.add_subplot(Nrows,Ncols,i+1)  ax3.imshow(np.reshape(images[i],[28,28]),cmap='Greys_r')  ax3.set_title('Actual: '+str(actuals[i]) +' pred: '+str(train_predictions[i]))  #画学习率fig4 = plt.figure()ax4 = fig4.add_subplot(111)ax4.plot(Learning_rate_vec,'k-')ax4.set_xlabel('step')ax4.set_ylabel('Learning_rate')fig4.suptitle('Learning_rate')   plt.show()

下面给出固定学习率图像和学习率随迭代次数下降的图像:

首先给出固定学习率图像:

下面是损失曲线


下面是准确率


我们可以看出,固定学习率损失函数下降速度较缓,同时其最终准确率为80%~90%之间就不再提高了

下面给出学习率随迭代次数降低的曲线:

首先给出学习率随迭代次数降低的损失曲线


然后给出相应的准确率曲线


我们可以看出其损失函数下降很快,同时准确率也可以达到90%以上

下面给出随机抓取的图像相应的识别情况:


至此我们实现了简单的CNN来实现MNIST手写图数据集的识别,如果想进一步提高其准确率,可以通过改变CNN网络参数,如通道数、全连接层神经元个数,过滤器大小,学习率,训练次数,加入dropout层等等,也可以通过增加CNN网络深度来进一步提高其准确率

下面给出一组参数:

初始学习率:initial_learning_rate=0.05

迭代步长:decay_steps=50,每50步改变一次学习率

下面是仿真结果:




我们可以看出,通过调整超参数,其既保证了损失函数能够快速下降,又进一步提高了其模型准确率,我们在训练次数为1500次的基础上,准确率已经达到97%以上。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    使用Flask-Cache缓存实现给Flask提速的方法详解
    下一条:
    selenium+Chrome滑动验证码破解二(某某网站)
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(1个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(1个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客