tensorflow学习笔记七----------卷积神经网络
卷积神经网络比神经网络稍微复杂一些,因为其多了一个卷积层(convolutional layer)和池化层(pooling layer)。
使用mnist数据集,n个数据,每个数据的像素为28*28*1=784。先让这些数据通过第一个卷积层,在这个卷积上指定一个3*3*1的feature,这个feature的个数设为64。接着经过一个池化层,让这个池化层的窗口为2*2。然后在经过一个卷积层,在这个卷积上指定一个3*3*64的feature,这个featurn的个数设置为128,。接着经过一个池化层,让这个池化层的窗口为2*2。让结果经过一个全连接层,这个全连接层大小设置为1024,在经过第二个全连接层,大小设置为10,进行分类。
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
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")
#像素点为784
n_input = 784
#十分类
n_output = 10
#wc1,第一个卷积层参数,3*3*1,共有64个
#wc2,第二个卷积层参数,3*3*64,共有128个
#wd1,第一个全连接层参数,经过两个池化层被压缩到7*7
#wd2,第二个全连接层参数
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))
}
定义前向传播函数。先将输入数据预处理,变成tensorflow支持的四维图像;进行第一层的卷积层处理,调用conv2d函数;将卷积结果用激活函数进行处理(relu函数);将结果进行池化层处理,ksize代表窗口大小;将池化层的结果进行随机删除节点;进行第二层卷积和池化...;进行全连接层,先将数据进行reshape(此处为7*7*128);进行激活函数处理;得出结果。前向传播结束。
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')
_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')
_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'])
# RETURN
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 out
print ("CNN READY")
定义损失函数,定义优化器
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(_pred, 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() # SAVER
save_step = 1
saver = tf.train.Saver(max_to_keep=3) print ("GRAPH READY")
进行迭代
do_train = 1
sess = tf.Session()
sess.run(init) training_epochs = 15
batch_size = 16
display_step = 1
if do_train == 1:
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
# 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))print ("OPTIMIZATION FINISHED")
tensorflow学习笔记七----------卷积神经网络的更多相关文章
- CNN学习笔记:卷积神经网络
CNN学习笔记:卷积神经网络 卷积神经网络 基本结构 卷积神经网络是一种层次模型,其输入是原始数据,如RGB图像.音频等.卷积神经网络通过卷积(convolution)操作.汇合(pooling)操作 ...
- 学习笔记TF027:卷积神经网络
卷积神经网络(Convolutional Neural Network,CNN),可以解决图像识别.时间序列信息问题.深度学习之前,借助SIFT.HoG等算法提取特征,集合SVM等机器学习算法识别图像 ...
- 深度学习笔记 (一) 卷积神经网络基础 (Foundation of Convolutional Neural Networks)
一.卷积 卷积神经网络(Convolutional Neural Networks)是一种在空间上共享参数的神经网络.使用数层卷积,而不是数层的矩阵相乘.在图像的处理过程中,每一张图片都可以看成一张“ ...
- 【学习笔记】卷积神经网络 (CNN )
前言 对于卷积神经网络(cnn)这一章不打算做数学方面深入了解,所以只是大致熟悉了一下原理和流程,了解了一些基本概念,所以只是做出了一些总结性的笔记. 感谢B站的视频 https://www.bili ...
- tensorflow学习之路-----卷积神经网络个人总结
卷积神经网络大总结(个人理解) 神经网络 1.概念:从功能他们模仿真实数据 2.结构:输入层.隐藏层.输出层.其中隐藏层要有的参数:权重.偏置.激励函数.过拟合 3.功能:能通过模仿,从而学到事件 其 ...
- Tensorflow学习教程------利用卷积神经网络对mnist数据集进行分类_利用训练好的模型进行分类
#coding:utf-8 import tensorflow as tf from PIL import Image,ImageFilter from tensorflow.examples.tut ...
- Tensorflow学习笔记03-使用神经网络做线性回归
import tensorflow as tf import numpy as np #input就是输入数据,输入矩阵,in_size就是输入矩阵的列数(数据属性数量),out_size输出矩阵列数 ...
- tensorflow学习笔记七----------RNN
和神经网络不同的是,RNN中的数据批次之间是有相互联系的.输入的数据需要是要求序列化的. 1.将数据处理成序列化: 2.将一号数据传入到隐藏层进行处理,在传入到RNN中进行处理,RNN产生两个结果,一 ...
- Python机器学习笔记:卷积神经网络最终笔记
这已经是我的第四篇博客学习卷积神经网络了.之前的文章分别是: 1,Keras深度学习之卷积神经网络(CNN),这是开始学习Keras,了解到CNN,其实不懂的还是有点多,当然第一次笔记主要是给自己心中 ...
随机推荐
- GO语言学习笔记2-int类型的取值范围
相比于C/C++语言的int类型,GO语言提供了多种int类型可供选择,有int8.int16.int32.int64.int.uint8.uint16.uint32.uint64.uint. 1.i ...
- java大文件上传
上次遇到这样一个问题,客户上传高清视频(1G以上)的时候上传失败. 一开始以为是session过期或者文件大小受系统限制,导致的错误.查看了系统的配置文件没有看到文件大小限制,web.xml中sees ...
- #417 Div2 Problem C Sagheer and Nubian Market (二分 && std::accumulate)
题目链接 : http://codeforces.com/problemset/problem/812/C 题意 : 给你 n 件物品和你拥有的钱 S, 接下来给出这 n 件物品的价格, 这些物品的价 ...
- CentOS7/RHEL7 pacemaker+corosync高可用集群搭建
TOC \o "1-3" \h \z \u 一.集群信息... PAGEREF _Toc502099174 \h 4 08D0C9EA79F9BACE118C8200AA004B ...
- centos网卡配置NM_CONTROLLED=”yes” 慎用
今天有1台服务器修改了 /etc/sysconfig/network-scripts/ifcfg-eth0 配置文件中的一个参数: NM_CONTROLLED=“yes” 修改成 NM_CONTROL ...
- 通过jedis连接redis单机成功,使用redis客户端可以连接集群,但使用JedisCluster连接redis集群一直报Could not get a resource from the pool
一,问题描述: (如题目)通过jedis连接redis单机成功,使用JedisCluster连接redis集群一直报Could not get a resource from the pool 但是使 ...
- nginx利用try_files实现多个源
比如一个视频网站,视频资源分散在几台机器上,但是给用要提供统一的IP,路径,端口.就需要nginx,先检查本机是否有改文件,如果没有就代理其他地方 location / { root /data/ww ...
- k8s 添加ingress 暴露服务
vim file.yaml apiVersion: extensions/v1beta1 kind: Ingress metadata: name: pgadmin labels: k8s-app: ...
- Vue的父子组件通信(转载)
Vue是一个轻量级的渐进式框架,对于它的一些特性和优点在此就不做赘述,本篇文章主要来探讨一下Vue子父组件通信的问题 首先我们先搭好开发环境,我们首先得装好git和npm这两个工具(如果有不清楚的同学 ...
- Mysql基本管理知识
数据库的启动 [root@node80 ~]# /etc/init.d/mysqld start #mysqld是从安装包拷贝的mysql.server Starting MySQL. SUCCESS ...