尝试用 Alexnet 来构建一个网络模型,并使用 mnist 数据查看训练结果。

我们将代码实现分为三个过程,加载数据、定义网络模型、训练数据和评估模型。

实现代码如下:

#-*- coding:utf-8 -*_

#加载数据

import tensorflow as tf

# 输入数据
from tensorflow.examples.tutorials.mnist import input_data
#TensorFlow 自带,用来下载并返回 mnist 数据。可以自己下载 mnist数据后,存放到指定目录,我这里是 /tmp/data 目录。
#其实如果没有下载数据,TensorFlow 也会帮你自动下载 mnist 数据存放到你指定的目录当中。
#mnist 数据下载地址:http://yann.lecun.com/exdb/mnist/
mnist = input_data.read_data_sets("/tmp/data", one_hot=True) # 定义网络的超参数
learning_rate = 0.001
training_iters = 200000
batch_size = 128
display_step = 5 # 定义网络的参数
n_input = 784 # 输入的维度 (img shape: 28*28)
n_classes = 10 # 标记的维度 (0-9 digits)
dropout = 0.75 # Dropout的概率,输出的可能性 # 输入占位符
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability) #构建网络模型 # 定义卷积操作
def conv2d(name,x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x,name=name) # 使用relu激活函数 # 定义池化层操作
def maxpool2d(name,x, k=2):
# MaxPool2D wrapper
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
padding='SAME',name=name) #最大值池化 # 规范化操作
def norm(name, l_input, lsize=4):
return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.001 / 9.0,
beta=0.75, name=name) # 定义所有的网络参数
weights = {
'wc1': tf.Variable(tf.random_normal([11, 11, 1, 96])),
'wc2': tf.Variable(tf.random_normal([5, 5, 96, 256])),
'wc3': tf.Variable(tf.random_normal([3, 3, 256, 384])),
'wc4': tf.Variable(tf.random_normal([3, 3, 384, 384])),
'wc5': tf.Variable(tf.random_normal([3, 3, 384, 256])),
'wd1': tf.Variable(tf.random_normal([4*4*256, 4096])),
'wd2': tf.Variable(tf.random_normal([4096, 1024])),
'out': tf.Variable(tf.random_normal([1024, n_classes]))
}
biases = {
'bc1': tf.Variable(tf.random_normal([96])),
'bc2': tf.Variable(tf.random_normal([256])),
'bc3': tf.Variable(tf.random_normal([384])),
'bc4': tf.Variable(tf.random_normal([384])),
'bc5': tf.Variable(tf.random_normal([256])),
'bd1': tf.Variable(tf.random_normal([4096])),
'bd2': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([n_classes]))
} #定义 Alexnet 网络模型 # 定义整个网络
def alex_net(x, weights, biases, dropout):
# 向量转为矩阵 Reshape input picture
x = tf.reshape(x, shape=[-1, 28, 28, 1]) # 第一层卷积
# 卷积
conv1 = conv2d('conv1', x, weights['wc1'], biases['bc1'])
# 下采样
pool1 = maxpool2d('pool1', conv1, k=2)
# 规范化
norm1 = norm('norm1', pool1, lsize=4) # 第二层卷积
# 卷积
conv2 = conv2d('conv2', norm1, weights['wc2'], biases['bc2'])
# 最大池化(向下采样)
pool2 = maxpool2d('pool2', conv2, k=2)
# 规范化
norm2 = norm('norm2', pool2, lsize=4) # 第三层卷积
# 卷积
conv3 = conv2d('conv3', norm2, weights['wc3'], biases['bc3'])
# 规范化
norm3 = norm('norm3', conv3, lsize=4) # 第四层卷积
conv4 = conv2d('conv4', norm3, weights['wc4'], biases['bc4']) # 第五层卷积
conv5 = conv2d('conv5', conv4, weights['wc5'], biases['bc5'])
# 最大池化(向下采样)
pool5 = maxpool2d('pool5', conv5, k=2)
# 规范化
norm5 = norm('norm5', pool5, lsize=4) # 全连接层1
fc1 = tf.reshape(norm5, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 =tf.add(tf.matmul(fc1, weights['wd1']),biases['bd1'])
fc1 = tf.nn.relu(fc1)
# dropout
fc1=tf.nn.dropout(fc1,dropout) # 全连接层2
fc2 = tf.reshape(fc1, [-1, weights['wd2'].get_shape().as_list()[0]])
fc2 =tf.add(tf.matmul(fc2, weights['wd2']),biases['bd2'])
fc2 = tf.nn.relu(fc2)
# dropout
fc2=tf.nn.dropout(fc2,dropout) # 输出层
out = tf.add(tf.matmul(fc2, weights['out']) ,biases['out'])
return out #构建模型,定义损失函数和优化器,并构建评估函数 # 构建模型
pred = alex_net(x, weights, biases, keep_prob) # 定义损失函数和优化器
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
#这里定义损失函数时调用tf.nn.softmax_cross_entropy_with_logits() 函数必须使用参数命名的方式来调用 (logits=pred, labels=y)不然会报错。
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # 评估函数
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) #训练模型和评估模型 # 初始化变量
init = tf.global_variables_initializer() # 开启一个训练
with tf.Session() as sess:
sess.run(init)
step = 1
# 开始训练,直到达到training_iters,即200000
while step * batch_size < training_iters:
#获取批量数据
batch_x, batch_y = mnist.train.next_batch(batch_size)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y, keep_prob: dropout})
if step % display_step == 0:
# 计算损失值和准确度,输出
loss,acc = sess.run([cost,accuracy], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.})
print ("Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc))
step += 1
print ("Optimization Finished!")
# 计算测试集的精确度
print ("Testing Accuracy:",
sess.run(accuracy, feed_dict={x: mnist.test.images[:256],
y: mnist.test.labels[:256],
keep_prob: 1.}))

GitHub 代码:https://github.com/weixuqin/tensorflow/blob/master/AlexNet.py

深度学习之 TensorFlow(五):mnist 的 Alexnet 实现的更多相关文章

  1. 截图:【炼数成金】深度学习框架Tensorflow学习与应用

    创建图.启动图 Shift+Tab Tab 变量介绍: F etch Feed 简单的模型构造 :线性回归 MNIST数据集 Softmax函数 非线性回归神经网络   MINIST数据集分类器简单版 ...

  2. 【原创 深度学习与TensorFlow 动手实践系列 - 4】第四课:卷积神经网络 - 高级篇

    [原创 深度学习与TensorFlow 动手实践系列 - 4]第四课:卷积神经网络 - 高级篇 提纲: 1. AlexNet:现代神经网络起源 2. VGG:AlexNet增强版 3. GoogleN ...

  3. 【原创 深度学习与TensorFlow 动手实践系列 - 3】第三课:卷积神经网络 - 基础篇

    [原创 深度学习与TensorFlow 动手实践系列 - 3]第三课:卷积神经网络 - 基础篇 提纲: 1. 链式反向梯度传到 2. 卷积神经网络 - 卷积层 3. 卷积神经网络 - 功能层 4. 实 ...

  4. UFLDL深度学习笔记 (五)自编码线性解码器

    UFLDL深度学习笔记 (五)自编码线性解码器 1. 基本问题 在第一篇 UFLDL深度学习笔记 (一)基本知识与稀疏自编码中讨论了激活函数为\(sigmoid\)函数的系数自编码网络,本文要讨论&q ...

  5. 深度学习与TensorFlow

    深度学习与TensorFlow DNN(深度神经网络算法)现在是AI社区的流行词.最近,DNN 在许多数据科学竞赛/Kaggle 竞赛中获得了多次冠军. 自从 1962 年 Rosenblat 提出感 ...

  6. 深度学习调用TensorFlow、PyTorch等框架

    深度学习调用TensorFlow.PyTorch等框架 一.开发目标目标 提供统一接口的库,它可以从C++和Python中的多个框架中运行深度学习模型.欧米诺使研究人员能够在自己选择的框架内轻松建立模 ...

  7. 深度学习之TensorFlow构建神经网络层

    深度学习之TensorFlow构建神经网络层 基本法 深度神经网络是一个多层次的网络模型,包含了:输入层,隐藏层和输出层,其中隐藏层是最重要也是深度最多的,通过TensorFlow,python代码可 ...

  8. 深度学习之 GAN 进行 mnist 图片的生成

    深度学习之 GAN 进行 mnist 图片的生成 mport numpy as np import os import codecs import torch from PIL import Imag ...

  9. 深度学习(TensorFlow)环境搭建:(三)Ubuntu16.04+CUDA8.0+cuDNN7+Anaconda4.4+Python3.6+TensorFlow1.3

    紧接着上一篇的文章<深度学习(TensorFlow)环境搭建:(二)Ubuntu16.04+1080Ti显卡驱动>,这篇文章,主要讲解如何安装CUDA+CUDNN,不过前提是我们是已经把N ...

  10. 分享《机器学习实战基于Scikit-Learn和TensorFlow》中英文PDF源代码+《深度学习之TensorFlow入门原理与进阶实战》PDF+源代码

    下载:https://pan.baidu.com/s/1qKaDd9PSUUGbBQNB3tkDzw <机器学习实战:基于Scikit-Learn和TensorFlow>高清中文版PDF+ ...

随机推荐

  1. Julia - 变量

    变量的赋值 julia> a = 1 # 把 10 赋给变量 a 1 julia> a + 1 # 变量 a 的值加 1 2 julia> a = 4 # 重新赋值给变量 a 4 j ...

  2. 基于JNI,JAVA 调用 C++入门

    1.步骤一览 2.步骤详情 2.1. 编写Java类 native package com.ibugs.jni; /** * * @author i_bugs * */ public class CP ...

  3. PHP class 继承

    1.执行结果 成员名 成员修饰符 方法名 方法修饰符 执行结果 name private setName private 在构造函数函数中执行父类私有方法,子类未能覆盖private成员变量和方法,修 ...

  4. 判断修改的中的值,用前面的,否则容易获得空值;this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue; VS bool b = (bool)this.dataGridView1.Rows[i].Cells[0].Value;

    判断修改的中的值,用前面的,否则容易获得空值:this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue;  VS     bool b = (b ...

  5. ubuntu安装vsftpd

    使用以下命令安装vsftpd: apt-get install vsftpd 安装完成后,文件服务器已经开启了. 然后就可以连接,可以使用xftp等工具,在上传和下载的时候要注意权限,不然会失败.

  6. sqlplus客户端 navicat 使用sqlplus OCI

    链接:http://pan.baidu.com/s/1i5otsUT 密码:cbux 解压后放到某个目录下 这是我的 sqlplus客户端出现乱码 - 一支小白 - 博客园  http://www.c ...

  7. git配置多用户多平台

    在Git使用中经常会碰到多用户问题,例如:你在公司里有一个git账户,在github上有一个账户,并且你想在一台电脑上同时对这两个git账户进行操作,此时就需要进行git多用户配置. 首先配置不同的S ...

  8. PHP格式化(文件)存储数据大小(SIZE)显示

    有时候我们需要在网页上显示某个文件的大小,或者是其它数据的大小数字. 这个数字往往从跨度很大,如果以B为单位的话可能是个位,如果1G则长达1073741824的数字,这个时候我们就需要根据大小来格式化 ...

  9. Mac notes

    1. Mac应用数据存放位置 ~/Library/Application Support/ 比如sublime text的应用数据~/Library/Application Support/Subli ...

  10. Luogu 4438 [HNOI/AHOI2018]道路

    $dp$. 这道题最关键的是这句话: 跳出思维局限大胆设状态,设$f_{x, i, j}$表示从$x$到根要经过$i$条公路,$j$条铁路的代价,那么对于一个叶子结点,有$f_{x, i, j} = ...