跟我学算法-tensorflow 实现卷积神经网络
我们采用的卷积神经网络是两层卷积层,两层池化层和两层全连接层
我们使用的数据是mnist数据,数据训练集的数据是50000*28*28*1 因为是黑白照片,所以通道数是1
第一次卷积采用64个filter, 第二次卷积采用128个filter,池化层的大小为2*2,我们采用的是两次全连接
第一步:导入数据
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data/', one_hot=True)
第二步: 初始化函数
# 构造初始化参数, 方差为0.1
n_input = 784
n_output = 10
weights = {
'wc1' : tf.Variable(tf.truncated_normal([3, 3, 1, 64], stddev=0.1)),
'wc2' : tf.Variable(tf.truncated_normal([3, 3, 64, 128], stddev=0.1)),
'wd1' : tf.Variable(tf.truncated_normal([7*7*128, 1024], stddev=0.1)),
'wd2' : tf.Variable(tf.truncated_normal([1024, n_output], stddev=0.1)) } biases = {
'b1' : tf.Variable(tf.truncated_normal([64], stddev=0.1)),
'b2' : tf.Variable(tf.truncated_normal([128], stddev=0.1)),
'bd1' : tf.Variable(tf.truncated_normal([1024], stddev=0.1)),
'bd2' : tf.Variable(tf.truncated_normal([n_output], stddev=0.1)) }
第三步: 构造前向传播卷积函数,两次卷积,两次池化,两次全连接
def conv_basic(_input, _w, _b, _keepratio):
_input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])
#进行卷积操作
_conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
# 使用激活函数
_conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
# 进行池化操作, padding='SAME', 表示维度不足就补齐
_pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], stride=[1, 2, 2, 1], padding='SAME')
#去除一部分数据
_pool1_dr1 = tf.nn.dropout(_pool1, _keepratio)
#第二次卷积操作
_conv2 = tf.nn.conv2d(_pool1_dr1, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
# 使用激活函数
_conv2 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
# 进行池化操作
_pool2 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], stride=[1, 2, 2, 1], padding='SAME')
_pool_dr2 = tf.nn.dropout(_pool1, _keepratio)
# 第一次全连接操作
# 对_pool_dr2 根据wd1重新构造函数
_densel = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])
_fcl = tf.nn.relu(tf.add(tf.matmul(_densel, _w['wd1'], _b['bd1'])))
_fc_dr1 = tf.nn.dropout(_fcl, _keepratio)
# 第二次全连接
_out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])
out = {'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1,
'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1,
'fcl': _fcl, 'fc_dr1': _fc_dr1, 'out': _out
}
return out
第四步: 构造cost函数,和准确值函数
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keepratio = tf.placeholder(tf.float32)
# 构造cost函数
#获得预测结果
_pred =conv_basic(x, weights, biases, keepratio)['out']
# 输入预测结果与真实值构造cost 函数
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(_pred, y))
# 优化函数使得cost最小
optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
# 计算准确率
_corr = tf.equal(tf.argmax(_pred, 1), tf.argmax(y, 1))
accr = tf.reduce_mean(tf.cast(_corr, tf.float32))
第五步: 训练模型,降低cost,提升精度
init = tf.global_variables_initializer() # 进行训练
sess = tf.Session()
sess.run(init)
#迭代次数
training_epochs = 15
# 每次训练的样本数
batch_size = 16
#循环打印的次数
display_step = 1
for epoch in range(training_epochs):
avg_cost = 0.
#total_batch = int(mnist.train.num_examples/batch_size)
total_batch = 10
# Loop over all batches
for i in range(total_batch):
# 提取训练数据和标签
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
#训练模型优化参数
sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})
# 加和损失值
avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batch # Display logs per epoch step
if epoch % display_step == 0:
print ("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})
print (" Training accuracy: %.3f" % (train_acc))
#test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel, keepratio:1.})
#print (" Test accuracy: %.3f" % (test_acc)) print ("OPTIMIZATION FINISHED")
跟我学算法-tensorflow 实现卷积神经网络的更多相关文章
- 跟我学算法-tensorflow 实现卷积神经网络附带保存和读取
这里的话就不多说明了,因为上上一个博客已经说明了 import numpy as np import tensorflow as tf import matplotlib.pyplot as plt ...
- TensorFlow实现卷积神经网络
1 卷积神经网络简介 在介绍卷积神经网络(CNN)之前,我们需要了解全连接神经网络与卷积神经网络的区别,下面先看一下两者的结构,如下所示: 图1 全连接神经网络与卷积神经网络结构 虽然上图中显示的全连 ...
- 使用TensorFlow的卷积神经网络识别自己的单个手写数字,填坑总结
折腾了几天,爬了大大小小若干的坑,特记录如下.代码在最后面. 环境: Python3.6.4 + TensorFlow 1.5.1 + Win7 64位 + I5 3570 CPU 方法: 先用MNI ...
- tensorflow CNN 卷积神经网络中的卷积层和池化层的代码和效果图
tensorflow CNN 卷积神经网络中的卷积层和池化层的代码和效果图 因为很多 demo 都比较复杂,专门抽出这两个函数,写的 demo. 更多教程:http://www.tensorflown ...
- Python之TensorFlow的卷积神经网络-5
一.卷积神经网络(Convolutional Neural Networks, CNN)是一类包含卷积计算且具有深度结构的前馈神经网络(Feedforward Neural Networks),是深度 ...
- 吴裕雄 python 神经网络——TensorFlow 使用卷积神经网络训练和预测MNIST手写数据集
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_dat ...
- TensorFlow构建卷积神经网络/模型保存与加载/正则化
TensorFlow 官方文档:https://www.tensorflow.org/api_guides/python/math_ops # Arithmetic Operators import ...
- Tensorflow之卷积神经网络(CNN)
前馈神经网络的弊端 前一篇文章介绍过MNIST,是采用的前馈神经网络的结构,这种结构有一个很大的弊端,就是提供的样本必须面面俱到,否则就容易出现预测失败.如下图: 同样是在一个图片中找圆形,如果左边为 ...
- 字符型图片验证码,使用tensorflow实现卷积神经网络,进行验证码识别CNN
本项目使用卷积神经网络识别字符型图片验证码,其基于 TensorFlow 框架.它封装了非常通用的校验.训练.验证.识别和调用 API,极大地减低了识别字符型验证码花费的时间和精力. 项目地址: ht ...
随机推荐
- UEFI下windows启动过程
引导文件 在UEFI安装完操作系统后,Windows至少使用两个分区,一个叫做ESP分区(EFI SYSTEM PARTITION),用于存放启动文件,另一个则是BIOS下正常的系统分区,不同的是,B ...
- 【DEV GridControl】怎样使GridView中满足某个条件的行可编辑,其余行不可编辑?
DXperience控件包,使用起来非常方便,但有时候某些功能的实现在文档中不太容易找到解决方案,比如下面要提到的这个功能我就在文档中找了很久也没找到,最后还是在官方论坛上找到的. 具体问题是这样的: ...
- java远程下载文件到本地
方法一 ** * 下载远程文件并保存到本地 * * @param remoteFilePath-远程文件路径 * @param localFilePath-本地文件路径(带文件名) */ public ...
- SSH整合报错:Unable to instantiate Action, testAction, defined for 'test' in namespace '/'testAction
报错如下: Struts Problem Report Struts has detected an unhandled exception: Messages: testAction Unable ...
- 解决sublime package control 出现There are no packages available for installation
昨天在安装了一下Sublime Text 3,在安装插件的过程中出现了一些问题,现在记录一下,也给遇到同样问题的朋友一些帮助.在安装插件的时候,需要先安装一下Package Control. 安装Pa ...
- (译)KVO的内部实现
09年的一篇文章,比较深入地阐述了KVO的内部实现. KVO是实现Cocoa Bindings的基础,它提供了一种方法,当某个属性改变时,相应的objects会被通知到.在其他语言中,这种观察者模 ...
- hasura graphql subscriptions 使用
subscriptions graphql 的一项实时数据推送的功能,还是很方便的,自己在直接使用subscriptions-transport-ws npm 包 的时候运行一直有错误(主要是依赖 ...
- Brackets编辑器使用
常用快捷操作 Ctrl + b 当选中一个文本时,离该文本最近的相同的文本会被高亮显示,这样,相同的2个文本就全部获得了焦点,可以同时更改高亮文本.(对,只会找寻最近的且只找到一个就不找了!惰性查找. ...
- Hive之 hive的三种使用方式(CLI、HWI、Thrift)
Hive有三种使用方式——CLI命令行,HWI(hie web interface)浏览器 以及 Thrift客户端连接方式. 1.hive 命令行模式 直接输入/hive/bin/hive的执行程 ...
- Autocad 2010+ObjectArx 2010 +Vs2010 的.net 开发设置(转)
Autocad 2010+ObjectArx 2010 +Vs2010 的.net 开发设置 分类: ObjectArx.net2010-09-14 16:52 4203人阅读 评论(7) 收藏 举报 ...