Tensorflow实现的MNIST数据集的2层卷积2层全连接网络

2024-04-27 02:48

本文主要是介绍Tensorflow实现的MNIST数据集的2层卷积2层全连接网络,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

import tensorflow as tf
"""
h=w 图片尺寸
f=卷积核
p=padding 边界填补 ‘SAME’补充
s=strides 每一次走的步长
(h-f+2*p)/s + 1
"""
# 10 分类,输入图片尺寸 784*784
n_input=784
n_output=10
# 获取数据MNIST
mnist=('data/',one_hot = True)weights={# [3,3,1,64] 3*3 = h*w  卷积核, 1 channel, 64个特征图'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))
}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']))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)conv2 = tf.nn.conv2d(pool_dr1,w['wc2'],strides=[1,1,1,1],padding='SAME')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, 'pool_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)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(_pred,y))
optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)_corr = tf.equal(tf.argmax(_pred,1),tf.argmax(y,1))
accr = tf.redece_mean(tf.cast(_corr,tf.float32))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 =10for i in range(total_batch):# 以 batch_size 大小来依次的获取数据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(loss,feed_dict={x:batch_xs,y:batch_ys,keepratio:1.})/total_batchif epoch % display_step==0:print('Epoch: %03d/%03d loss: %9f'%(epoch,training_epochs, avg_cost))train_acc = sess.run(accr, feed_dict={x:batch_xs,y:batch_ys,keepratio:0.7})

 

这篇关于Tensorflow实现的MNIST数据集的2层卷积2层全连接网络的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/939332

相关文章

网络程序设计课程总结

项目主要内容我的Pull Request项目demo实现 运行环境项目说明 图像处理深度学习和机器学习 逻辑斯特回归深度学习 项目整合 项目demo 课程学习心得 项目主要内容 课程主要实现运用机器学习的方法对一份血常规报告进行分析,主要实现性别和年龄的预测。NP2016 我的Pull Request 1.ocr识别 pytesseract 调用 tesserac

hdu 5012 2014西安网络赛

当时手一残,有点小bug,被其他队的先a了。哎。 #include<iostream>#include<cstring>#include<stdio.h>#include<queue>using namespace std;int a[7],b[7];bool visit[7][7][7][7][7][7];int bfs(){queue<int> q[6];queue<int>

由于安全设置错误,远程桌面连接失败怎么办?

问题:远程桌面安全设置错误? “我是一名IT经理,需要经常使用远程桌面连接到办公室的电脑。近期,我在使用远程桌面时,远程桌面提示‘由于安全设置错误,客户端无法连接到远程计算机。’我不清楚是什么原因所导致的,有什么方法可以解决这个问题吗?谢谢!” 如何解决远程桌面连接由于安全设置错误? 远程桌面安全设置错误是比较常见的RDP问题,别担心,在这篇文章中,我们为您提供了三种解决方案,以帮助您轻

C语言实现通讯录,包括增删改查以及动态开辟内存,写入文件等功能

文章目录 前言一、注意二、源码1. test.c源文件2. contact.h头文件3. contact.c源文件 总结 前言 C语言实现通讯录,包括增删改查以及动态开辟内存,写入文件等功能 一、注意 在通讯录菜单栏使用枚举定义PeoInfo类型时,每个结构体类型的成员也使用枚举来确定长度刚开始动态开辟3个PeoInfo类型的内存若通讯录满员,则每次动态开辟2个PeoIn

tensorflow 获取graph中的所有tensor

[n.name for n in tf.get_default_graph().as_graph_def().node] 摘自https://stackoverflow.com/questions/36883949/in-tensorflow-get-the-names-of-all-the-tensors-in-a-graph

tensorflow 仅初始化指定的variables及未初始化的variables

1. 已知variables v0,v1,v2,对特定的variables进行初始化可使用以下方法: initialize_op = tf.variables_initializer([v0,v1,v2])sess.run(initialize_op)  2. restore graph 进行了fine_tuning, 但仍保留restored weights,仅对新的未被初始化的tenso

tensorflow统计graph中的trainable_variables

最简单的做法: 转自: https://blog.csdn.net/feynman233/article/details/79187304, 版权归原作者所有。 print(np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])) 另有篇博客讲解的很详细:原文地址https://blog.csdn

tensorflow训练过程的日志与监控

转自博客:  https://blog.csdn.net/vagrantabc2017/article/details/77507168 原博主总结的很好,转载一下,不懂的时候再来复习。 tf.logging.set_verbosity(tf.logging.INFO) 当设置INFO级别后,tf.contrib.learn会自动每百步后输出损失度量数据到标准输出。

tensorflow: 常用术语总结

参考自: https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#evaluate https://developers.google.com/machine-learning/glossary/#epoch steps :  steps  batches are processed

tensorflow: 查看安装版本及安装路径

import tensorflow as tf tf.__version__  # version ID tf.__path__      # installation path