博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
卷积神经网络:代码实现
阅读量:3946 次
发布时间:2019-05-24

本文共 4774 字,大约阅读时间需要 15 分钟。

import numpy as npimport tensorflow as tfimport matplotlib.pyplot as pltfrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('data/', one_hot=True)trainimg   = mnist.train.imagestrainlabel = mnist.train.labelstestimg    = mnist.test.imagestestlabel  = mnist.test.labels# 输入和输出 n_input  = 784 n_output = 10#卷积神经网络的参数初始化(w,b)weights  = {        'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64], stddev=0.1)), #第一层卷积层权重参数[3, 3, 1, 64]卷积核的大小(3*3*1);卷积核的个数64(特征图的个数)        'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.1)), #第二层卷积层权重参数[3, 3, 64, 128]卷积核的大小(3*3*64(与输入图像深度对应));卷积核的个数128(特征图的个数)        'wd1': tf.Variable(tf.random_normal([7*7*128, 1024], stddev=0.1)),#第一层全连接层权重参数(由于该模型中卷积并未改变输入图像的大小,经过两次池化原始图像大小(28*28)变为(7*7))        'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1))#第二层全连接层权重参数(10分类)    }biases   = {        'bc1': tf.Variable(tf.random_normal([64], stddev=0.1)),        'bc2': tf.Variable(tf.random_normal([128], stddev=0.1)),        'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)),        'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1))    }#卷积层定义def conv_basic(_input, _w, _b, _keepratio):        # 输入预处理(转换为TensorFlow支持的格式)的        _input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])#第一维:batchsize的大小(-1让TensorFlow根据其余值推断该值的大小);第二维:图像的高度;第三维:图像的宽度;第四维:图像的深度                # 第一层卷积        _conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')        #print(help(tf.nn.conv2d))查看函数的帮助文档        #strides=[batchsize的stride大小, h的stride大小, w的stride大小, c的stride大小]        #padding='SAME'/'VALID':自动填充0(推荐)/不进行填充        #_mean, _var = tf.nn.moments(_conv1, [0, 1, 2])        #_conv1 = tf.nn.batch_normalization(_conv1, _mean, _var, 0, 1, 0.0001)                _conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))#卷积之后进行激活                _pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')        #池化操作,ksize窗口大小(batchsize的大小;图像的高度;图像的宽度;图像的深度),strides=[1, 2, 2, 1]:h和w方向步长均为2               _pool_dr1 = tf.nn.dropout(_pool1, _keepratio)#dropout(随机地减少部分节点)                # 第二层卷积        _conv2 = tf.nn.conv2d(_pool_dr1, _w['wc2'], strides=[1, 1, 1, 1], padding='SAME')        #_mean, _var = tf.nn.moments(_conv2, [0, 1, 2])        #_conv2 = tf.nn.batch_normalization(_conv2, _mean, _var, 0, 1, 0.0001)        _conv2 = tf.nn.relu(tf.nn.bias_add(_conv2, _b['bc2']))        _pool2 = tf.nn.max_pool(_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')        _pool_dr2 = tf.nn.dropout(_pool2, _keepratio)              # 全连接层        _dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])#定义全连接的输入        # 第一层全连接层(神经网络)        _fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))        _fc_dr1 = tf.nn.dropout(_fc1, _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,            'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out        }        return outx = tf.placeholder(tf.float32, [None, n_input])y = tf.placeholder(tf.float32, [None, n_output])keepratio = tf.placeholder(tf.float32)_pred = conv_basic(x, weights, biases, keepratio)['out']cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(y, _pred))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)) init = tf.global_variables_initializer()    sess = tf.Session()sess.run(init)training_epochs = 10batch_size      = 16  #网络结果比较复杂,这里取小一些,方便演示,正常情况下要稍大一些display_step    = 1for 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)        # Fit training using batch data        sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})        # Compute average loss        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))

运行结果:

在这里插入图片描述
可以看出,损失值在不断减少,训练集的精度也有改善

转载地址:http://johwi.baihongyu.com/

你可能感兴趣的文章
boost学习-1.安装
查看>>
boost学习-2.总体感受
查看>>
boost学习-3.conversion,多态类型之间的安全转型,与数据类型转换
查看>>
2010年十大移动互联网应用将火山爆发
查看>>
云计算介绍
查看>>
敏捷开发笔记1
查看>>
vs2008
查看>>
转:NoSQL数据库探讨之一 - 为什么要用非关系数据库?
查看>>
log4cplus的按日生成文件,配置例子
查看>>
跨平台的文字编码转换方法--ICU
查看>>
ICU4C 4.4 静态库的编译
查看>>
FTP下载类, windows平台下对CFtpConnection上传下载的封装类
查看>>
代码自动生成-宏带来的奇技淫巧
查看>>
VC com开发中实现IObjectSafety
查看>>
c# 正则表达式基础
查看>>
C#3.0语言新特性
查看>>
W32Dasm反汇编工具使用教程
查看>>
EXE破解工具介绍
查看>>
机械码对应值
查看>>
常用语音编码的WAVE文件头格式剖析--各种编码
查看>>