import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

#获取mnist数据集的新方式,旧方法已不能用
old_v = tf.logging.get_verbosity()
tf.logging.set_verbosity(tf.logging.ERROR)
mnist = input_data.read_data_sets(“MNIST_data/”, one_hot=True)
train_data = mnist.train.images # Returns np.array
train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
eval_data = mnist.test.images # Returns np.array
eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)
tf.logging.set_verbosity(old_v)

#定义网络的超参数
learning_rate = 0.001
training_iters = 200000
batch_size = 128
display_step = 10

#定义网络的参数
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

#构建网络模型
#定义卷积操作
def conv2d(name, x, W, b, strides=1):
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):
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([44256, 4096])),
‘wd2’: tf.Variable(tf.random_normal([4096, 4096])),
‘out’: tf.Variable(tf.random_normal([4096, 10]))
}

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([4096])),
‘out’: tf.Variable(tf.random_normal([n_classes])),
}

#定义AlexNet的网络模型
#定义整个网络
def alex_net(x, weights, biases, dropout):
# 改造输入图像的形状
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', conv1, weights['wc2'], biases['bc2'])
# 下采样
pool2 = maxpool2d('pool2', conv2, k=2)
# 规范化
norm2 = norm('norm2', pool2, lsize=4)# 第三层卷积
# 卷积
conv3 = conv2d('conv3', norm2, weights['wc3'], biases['bc3'])
# 下采样
pool3 = maxpool2d('pool3', conv3, k=2)
# 规范化
norm3 = norm('norm3', pool3, lsize=4)# 第四层卷积
# 卷积
conv4 = conv2d('conv4', norm3, weights['wc4'], biases['bc4'])
# 第五层卷积
conv5 = conv2d('conv5', norm3, 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['wd1'].get_shape().as_list()[0]])
fc2 = tf.add(tf.matmul(fc2, weights['wd1']), biases['bd1'])
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_v2(labels=pred, logits=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.}))

MNIST的AlexNet实现相关推荐

  1. 对抗机器学习系列——深度神经网络的盲点

    1.引言   近些年,深度学习在计算机视觉领域取得了很好的表现,引领了第三次人工智能的浪潮.目前大部分表现优异的应用都用到了深度学习,大红大紫的 AlphaGo 就使用到了深度学习.   但是本期讲的 ...

  2. 使用PYTORCH复现ALEXNET实现MNIST手写数字识别

    网络介绍: Alexnet网络是CV领域最经典的网络结构之一了,在2012年横空出世,并在当年夺下了不少比赛的冠军,下面是Alexnet的网络结构: 网络结构较为简单,共有五个卷积层和三个全连接层,原 ...

  3. TensorFlow MNIST AlexNet

    原始的AlexNet用来处理277*277*3的数据集, 并且采用5层卷积,3层全连接层来处理图像分类. 具体结构和参数信息见 http://blog.csdn.net/chenhaifeng2016 ...

  4. 吴裕雄 python 神经网络——TensorFlow实现AlexNet模型处理手写数字识别MNIST数据集...

    import tensorflow as tf# 输入数据 from tensorflow.examples.tutorials.mnist import input_datamnist = inpu ...

  5. Jürgen Schmidhuber发文纪念10年前的研究,网友:转折点非AlexNet?

    视学算法报道 编辑:魔王 转载自公众号:机器之心 LSTM 之父.深度学习元老 Jürgen Schmidhuber 发文纪念 10 年前发表的研究. Jürgen Schmidhuber 每次发博客 ...

  6. Deep Learning回顾#之LeNet、AlexNet、GoogLeNet、VGG、ResNet

    CNN的发展史 上一篇回顾讲的是2006年Hinton他们的Science Paper,当时提到,2006年虽然Deep Learning的概念被提出来了,但是学术界的大家还是表示不服.当时有流传的段 ...

  7. 从AlexNet到BERT:深度学习中那些最重要idea的最简单回顾

    本文作者Denny Britz按时间总结的深度学习比较重要的idea集锦,推荐新人看,几乎给自12年以来最重要的idea 都列了出来,这些 idea 可以说得上是养活了无数人,大家都基于这些发了无数的 ...

  8. Deep Learning回顾之LeNet、AlexNet、GoogLeNet、VGG、ResNet

    from:#Deep Learning回顾#之LeNet.AlexNet.GoogLeNet.VGG.ResNet CNN的发展史 上一篇回顾讲的是2006年Hinton他们的Science Pape ...

  9. Lesson 16.6Lesson 16.6 复现经典架构:LeNet5 复现经典架构 (2):AlexNet

    4 复现经典网络:LeNet5与AlexNet 4.1 现代CNN的奠基者:LeNet5 使用卷积层和池化层能够创造的最简单的网络是什么样呢?或许就是下面这样的架构: 首先,图像从左侧输入,从右侧输出 ...

最新文章

  1. 马斯克员工参与新冠研究,论文登上Nature子刊
  2. Machine Learning | (2) sklearn数据集与机器学习组成
  3. 如何完全卸载VMware
  4. java-unrar-0.3.jar_unrar.jar解压缩rar文件
  5. 新思科技助力IBM将AI计算性能提升1000倍
  6. table { border-collapse:collapse; }
  7. c语言中指针数组赋值字符串,C语言—用结构体指针给数组赋值(结构体指针指向字符串,给字符串赋值)...
  8. bat 发邮件与手机交互_售价17500元!华为首款5G折叠屏手机来了,更多新机细节曝光...
  9. 章琦:能坚持的唯一的原因就是兴趣
  10. python变量和字符串
  11. html上拉下拉查看文字内容,html5上拉下拉事件效果演示
  12. html菜鸟css,css菜鸟教程,css菜鸟教程官网
  13. sparksql处理mysql_Spark记录-SparkSQL远程操作MySQL和ORACLE
  14. .9图片处理报错Error: java.lang.RuntimeException: Crunching Cruncher ic_coupon2.9.png failed, see logs
  15. 如何清理和优化你的Mac:14个小技巧推荐给你!
  16. linux下的企业级DNS服务器的操作和加速
  17. 程序员常用的一些快捷键(持续更新)
  18. Oracle修改SEQUENCE起始值
  19. oracle数据库block、tigger、function、package
  20. 体育这事,除了抢IP、赞助,就真不能干点其他啥了?

热门文章

  1. -webkit-filter是神马?
  2. asp.net(c#)网页跳转七种方法小结
  3. 中国互联网络发展状况统计报告
  4. DolphinDB配置
  5. 判断sem信号量为零_kernel.sem信号量调优
  6. 数据3分钟丨MariaDB将借壳上市;前融云CTO杨攀加入涛思数据;​Elastic 8.0正式发布...
  7. 每日一题(易错):这条SQL语句,有什么作用?
  8. 资源放送丨《 MySQL中的索引探究 - 2020云和恩墨大讲堂》PPT视频
  9. 20个MySQL高性能架构设计原则(收藏版)
  10. TiFlash:并非另一个 T + 1 列存数据库