基于MNIST数据集实现简单的卷积神经网络,熟悉基于TensorFlow的CNN的流程和框架。

#1、导入相关库
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import input_data#2、加载数据集
mnist = input_data.read_data_sets('data/', one_hot=True)
trainimg   = mnist.train.images
trainlabel = mnist.train.labels
testimg    = mnist.test.images
testlabel  = mnist.test.labels
print("MNIST ready")#3、定义权重和偏置
n_input = 784
n_output= 10
weights = {'wc1':tf.Variable(tf.random_normal([3,3,1,64], stddev=0.1)),'wc2':tf.Variable(tf.random_normal([3,3,64,128],stddev=0.1)),'wd1':tf.Variable(tf.random_normal([7*7*128,1024],stddev=0.1)),'wd2':tf.Variable(tf.random_normal([1024,n_output],stddev=0.1))
}
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))
}#4、定义CNN层
def conv_basic(_input, _w, _b, _keepratio):# INPUT_input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])# CONV LAYER 1_conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')#_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')_pool_dr1 = tf.nn.dropout(_pool1, _keepratio)# CONV LAYER 2_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)# VECTORIZE_dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])# FULLY CONNECTED LAYER 1_fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))_fc_dr1 = tf.nn.dropout(_fc1, _keepratio)# FULLY CONNECTED LAYER 2_out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])# RETURNout = { '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 out
print ("CNN READY")  #5、定义会话,初始化
a = tf.Variable(tf.random_normal([3,3,1,64], stddev=0.1))
print(a)
a = tf.Print(a, [a], "a: ")
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)#print (help(tf.nn.conv2d))
print (help(tf.nn.max_pool))x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keepratio = tf.placeholder(tf.float32)#functions
_pred = conv_basic(x, weights, biases, keepratio)['out']
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y))
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()#save
print("GRAAPH ready")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 batchesfor i in range(total_batch):batch_xs, batch_ys = mnist.train.next_batch(batch_size)# Fit training using batch datasess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})# Compute average lossavg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batch# Display logs per epoch stepif 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的卷积神经网络相关推荐

  1. 深度学习系列笔记——贰 (基于Tensorflow Keras搭建的猫狗大战模型 一)

    猫狗大战是著名的竞赛网站kaggle几年前的一个比赛,参赛者得到猫狗各12500张图片,作为训练集,另外还会得到12500张猫和狗的图片,作为验证.最后提交结果至kaggle平台,获得评测分数. 本篇 ...

  2. 【神经网络与深度学习】CIFAR10数据集介绍,并使用卷积神经网络训练图像分类模型——[附完整训练代码]

    [神经网络与深度学习]CIFAR-10数据集介绍,并使用卷积神经网络训练模型--[附完整代码] 一.CIFAR-10数据集介绍 1.1 CIFAR-10数据集的内容 1.2 CIFAR-10数据集的结 ...

  3. 深度学习入门笔记(十八):卷积神经网络(一)

    欢迎关注WX公众号:[程序员管小亮] 专栏--深度学习入门笔记 声明 1)该文章整理自网上的大牛和机器学习专家无私奉献的资料,具体引用的资料请看参考文献. 2)本文仅供学术交流,非商用.所以每一部分具 ...

  4. 深度学习入门笔记(十九):卷积神经网络(二)

    欢迎关注WX公众号:[程序员管小亮] 专栏--深度学习入门笔记 声明 1)该文章整理自网上的大牛和机器学习专家无私奉献的资料,具体引用的资料请看参考文献. 2)本文仅供学术交流,非商用.所以每一部分具 ...

  5. 基于tensorflow和卷积神经网络的电影推荐系统的实现

    基于tensorflow和卷积神经网络的电影推荐系统的实现 一. 数据处理 1. MovieLens数据集 2. 处理后的数据 二. 建模&训练 1. 嵌入层 2. 文本卷积层 3. 全连接层 ...

  6. 深度学习笔记(四)(1)卷积神经网络

    深度学习笔记(四)(1)卷积神经网络 返回目录 终于到了.... 1.1 计算机视觉(Computer vision) 图象识别.目标检测.风格迁移. 但在应用计算机视觉时要面临一个挑战,就是数据的输 ...

  7. 深度学习思维导图(基于TensorFlow框架)

    文章目录 深度学习 深度学习介绍 深度学习与机器学习的区别 深度学习的应用场景: 深度学习框架介绍 TensorFlow 的特点 TensorFlow 的安装 TensorFlow 框架介绍 TF 数 ...

  8. 深度学习入门笔记系列 ( 二 )——基于 tensorflow 的一些深度学习基础知识

    本系列将分为 8 篇 .今天是第二篇 .主要讲讲 TensorFlow 框架的特点和此系列笔记中涉及到的入门概念 . 1.Tensor .Flow .Session .Graphs TensorFlo ...

  9. 【深度学习基础】一步一步讲解卷积神经网络

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送 本文转自:一步一步讲解卷积神经网络 卷积神经网络(Convoluti ...

最新文章

  1. node.js 学习笔记三:路由url
  2. C语言(rand函数)
  3. linux smplayer 快捷键,SMPlayer:让 MPlayer 的使用更简单
  4. 如何将每一条记录放入到对应的范围中
  5. activemq和kafka的区别
  6. C++学习笔记(达内视频版)
  7. 欧洲语言框架A1到C2,法语等级 A1、A2、B1、B2、C1、C2
  8. 最新最全MTK联发科手机芯片型号及参数汇总
  9. 维刻柠檬鲜果冰怎么样?
  10. 产品 观察体会微信界面心得(一)
  11. Unity 将3D物体的世界坐标转换为对应的屏幕坐标
  12. Python中字符的匹配
  13. Python吴恩达深度学习作业15 -- YOLO原理及应用(自动驾驶——汽车检测)
  14. matlab迭代实现矩阵运算,用matlab实现Rayleigh迭代计算矩阵特征值的程序
  15. 联想拯救者R720双系统如何进bios
  16. 电子烟市场Juul来袭,锐刻福禄们该如何做防?
  17. 复活→移步:https://beiyuouo.github.io/
  18. 重装fedora17之后的一些配置
  19. linux 中 lrwxrwxrwx是什么意思?
  20. JSP设置Excel表格换行_Excel中快速将阿拉伯数字转化为大写文字的妙招

热门文章

  1. cba篮球暂停次数和时间_中国篮球即将来袭!202021赛季CBA赛程时间表
  2. win7 ghost 安装串口驱动inf文件出现问题
  3. 【Linux】24.gdb调试和coredump
  4. faster rcnn的源码理解(一)SmoothL1LossLayer论文与代码的结合理解
  5. 统计学习笔记(3)——k近邻法与kd树
  6. Caffe学习记录:Cifar-10 自定义网络训练记录
  7. Precision和Recall
  8. 计算机视觉、机器学习相关领域论文和源代码大集合
  9. Vue.js 深入响应式原理
  10. Spring中事务内部调用引发的惨案