#coding:utf-8
import tensorflow as tf
import os
def read_and_decode(filename):
#根据文件名生成一个队列
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue) #返回文件名和文件
features = tf.parse_single_example(serialized_example,
features={
'label': tf.FixedLenFeature([], tf.int64),
'img_raw' : tf.FixedLenFeature([], tf.string),
}) img = tf.decode_raw(features['img_raw'], tf.uint8)
img = tf.reshape(img, [227, 227, 3])
img = (tf.cast(img, tf.float32) * (1. / 255) - 0.5)*2
label = tf.cast(features['label'], tf.int32)
print img,label
return img, label def get_batch(image, label, batch_size,crop_size):
#数据扩充变换
distorted_image = tf.random_crop(image, [crop_size, crop_size, 3])#随机裁剪
distorted_image = tf.image.random_flip_up_down(distorted_image)#上下随机翻转
distorted_image = tf.image.random_brightness(distorted_image,max_delta=63)#亮度变化
distorted_image = tf.image.random_contrast(distorted_image,lower=0.2, upper=1.8)#对比度变化 #生成batch
#shuffle_batch的参数:capacity用于定义shuttle的范围,如果是对整个训练数据集,获取batch,那么capacity就应该够大
#保证数据打的足够乱
images, label_batch = tf.train.shuffle_batch([distorted_image, label],batch_size=batch_size,
num_threads=1,capacity=2000,min_after_dequeue=1000) return images, label_batch class network(object): def lenet(self,images,keep_prob): '''
根据tensorflow中的conv2d函数,我们先定义几个基本符号
输入矩阵 W×W,这里只考虑输入宽高相等的情况,如果不相等,推导方法一样,不多解释。
filter矩阵 F×F,卷积核
stride值 S,步长
输出宽高为 new_height、new_width
在Tensorflow中对padding定义了两种取值:VALID、SAME。下面分别就这两种定义进行解释说明。
VALID
new_height = new_width = (W – F + 1) / S #结果向上取整
SAME
new_height = new_width = W / S #结果向上取整
''' images = tf.reshape(images,shape=[-1,32,32,3])
#images = (tf.cast(images,tf.float32)/255.0-0.5)*2
#第一层,卷积层 32,32,3--->5,5,3,6--->28,28,6
#卷积核大小为5*5 输入层深度为3即三通道图像 卷积核深度为6即卷积核的个数
conv1_weights = tf.get_variable("conv1_weights",[5,5,3,6],initializer = tf.truncated_normal_initializer(stddev=0.1))
conv1_biases = tf.get_variable("conv1_biases",[6],initializer = tf.constant_initializer(0.0))
#移动步长为1 不使用全0填充
conv1 = tf.nn.conv2d(images,conv1_weights,strides=[1,1,1,1],padding='VALID')
#激活函数Relu去线性化
relu1 = tf.nn.relu(tf.nn.bias_add(conv1,conv1_biases)) #第二层 最大池化层 28,28,6--->1,2,2,1--->14,14,6
#池化层过滤器大小为2*2 移动步长为2 使用全0填充
pool1 = tf.nn.max_pool(relu1, ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') #第三层 卷积层 14,14,6--->5,5,6,16--->10,10,16
#卷积核大小为5*5 当前层深度为6 卷积核的深度为16
conv2_weights = tf.get_variable("conv_weights",[5,5,6,16],initializer = tf.truncated_normal_initializer(stddev=0.1))
conv2_biases = tf.get_variable("conv2_biases",[16],initializer = tf.constant_initializer(0.0)) conv2 = tf.nn.conv2d(pool1,conv2_weights,strides=[1,1,1,1],padding='VALID') #移动步长为1 不使用全0填充
relu2 = tf.nn.relu(tf.nn.bias_add(conv2,conv2_biases)) #第四层 最大池化层 10,10,16--->1,2,2,1--->5,5,16
#池化层过滤器大小为2*2 移动步长为2 使用全0填充
pool2 = tf.nn.max_pool(relu2,ksize = [1,2,2,1],strides=[1,2,2,1],padding='SAME') #第五层 全连接层
fc1_weights = tf.get_variable("fc1_weights",[5*5*16,1024],initializer = tf.truncated_normal_initializer(stddev=0.1))
fc1_biases = tf.get_variable("fc1_biases",[1024],initializer = tf.constant_initializer(0.1)) #[1,1024]
pool2_vector = tf.reshape(pool2,[-1,5*5*16]) #特征向量扁平化 原始的每一张图变成了一行9×9*64列的向量
fc1 = tf.nn.relu(tf.matmul(pool2_vector,fc1_weights)+fc1_biases) #为了减少过拟合 加入dropout层 fc1_dropout = tf.nn.dropout(fc1,keep_prob) #第六层 全连接层
#神经元节点数为1024 分类节点2
fc2_weights = tf.get_variable("fc2_weights",[1024,2],initializer=tf.truncated_normal_initializer(stddev=0.1))
fc2_biases = tf.get_variable("fc2_biases",[2],initializer = tf.constant_initializer(0.1))
fc2 = tf.matmul(fc1_dropout,fc2_weights) + fc2_biases return fc2
def lenet_loss(self,fc2,y_): #第七层 输出层
#softmax
y_conv = tf.nn.softmax(fc2)
labels=tf.one_hot(y_,2)
#定义交叉熵损失函数
#cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),reduction_indices=[1]))
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = y_conv, labels =labels))
self.cost = loss
return self.cost def lenet_optimer(self,loss):
train_optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss)
return train_optimizer def train():
image,label=read_and_decode("./train.tfrecords")
batch_image,batch_label=get_batch(image,label,batch_size=30,crop_size=32)
#建立网络,训练所用
x = tf.placeholder("float",shape=[None,32,32,3],name='x-input')
y_ = tf.placeholder("int32",shape=[None])
keep_prob = tf.placeholder(tf.float32) net=network()
#inf=net.buildnet(batch_image)
inf = net.lenet(x,keep_prob)
loss=net.lenet_loss(inf,y_) #计算loss
opti=net.optimer(loss) #梯度下降 correct_prediction = tf.equal(tf.cast(tf.argmax(inf,1),tf.int32),batch_label)
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) init=tf.global_variables_initializer()
with tf.Session() as session:
with tf.device("/gpu:0"):
session.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
max_iter=10000
iter=0
if os.path.exists(os.path.join("model",'model.ckpt')) is True:
tf.train.Saver(max_to_keep=None).restore(session, os.path.join("model",'model.ckpt'))
while iter<max_iter:
#loss_np,_,label_np,image_np,inf_np=session.run([loss,opti,batch_image,batch_label,inf])
b_batch_image,b_batch_label = session.run([batch_image,batch_label])
loss_np,_=session.run([loss,opti],feed_dict={x:b_batch_image,y_:b_batch_label,keep_prob:0.6})
if iter%50==0:
print 'trainloss:',loss_np
if iter%500==0:
#accuracy_np = session.run([accuracy])
accuracy_np = session.run([accuracy],feed_dict={x:b_batch_image,y_:b_batch_label,keep_prob:1.0})
print 'xxxxxxxxxxxxxxxxxxxxxx',accuracy_np
iter+=1
coord.request_stop()#queue需要关闭,否则报错
coord.join(threads)
if __name__ == '__main__':
train()

Tensorflow学习教程------实现lenet并且进行二分类的更多相关文章

  1. Tensorflow学习教程------普通神经网络对mnist数据集分类

    首先是不含隐层的神经网络, 输入层是784个神经元 输出层是10个神经元 代码如下 #coding:utf-8 import tensorflow as tf from tensorflow.exam ...

  2. Tensorflow学习教程------过拟合

    Tensorflow学习教程------过拟合   回归:过拟合情况 / 分类过拟合 防止过拟合的方法有三种: 1 增加数据集 2 添加正则项 3 Dropout,意思就是训练的时候隐层神经元每次随机 ...

  3. Tensorflow学习教程------代价函数

    Tensorflow学习教程------代价函数   二次代价函数(quadratic cost): 其中,C表示代价函数,x表示样本,y表示实际值,a表示输出值,n表示样本的总数.为简单起见,使用一 ...

  4. Tensorflow学习教程------读取数据、建立网络、训练模型,小巧而完整的代码示例

    紧接上篇Tensorflow学习教程------tfrecords数据格式生成与读取,本篇将数据读取.建立网络以及模型训练整理成一个小样例,完整代码如下. #coding:utf-8 import t ...

  5. Tensorflow学习教程------lenet多标签分类

    本文在上篇的基础上利用lenet进行多标签分类.五个分类标准,每个标准分两类.实际来说,本文所介绍的多标签分类属于多任务学习中的联合训练,具体代码如下. #coding:utf-8 import te ...

  6. tensorflow 学习教程

    tensorflow 学习手册 tensorflow 学习手册1:https://cloud.tencent.com/developer/section/1475687 tensorflow 学习手册 ...

  7. Tensorflow学习教程------创建图启动图

    Tensorflow作为目前最热门的机器学习框架之一,受到了工业界和学界的热门追捧.以下几章教程将记录本人学习tensorflow的一些过程. 在tensorflow这个框架里,可以讲是若数据类型,也 ...

  8. Tensorflow学习教程------非线性回归

    自己搭建神经网络求解非线性回归系数 代码 #coding:utf-8 import tensorflow as tf import numpy as np import matplotlib.pypl ...

  9. Tensorflow学习教程------tensorboard网络运行和可视化

    tensorboard可以将训练过程中的一些参数可视化,比如我们最关注的loss值和accuracy值,简单来说就是把这些值的变化记录在日志里,然后将日志里的这些数据可视化. 首先运行训练代码 #co ...

随机推荐

  1. 三、ReactJS、jsx、 Component 特性

    reactjs特性: 基于组件(Component)化思考 用 JSX 进行声明式(Declarative)UI 设计 使用 Virtual DOM Component PropType 错误校对机制 ...

  2. Python MySQL Order By

    章节 Python MySQL 入门 Python MySQL 创建数据库 Python MySQL 创建表 Python MySQL 插入表 Python MySQL Select Python M ...

  3. ZOJ - 3961 Let's Chat(区间相交)

    题意:给定一个长度为n的序列,A和B两人分别给定一些按递增顺序排列的区间,区间个数分别为x和y,问被A和B同时给定的区间中长度为m的子区间个数. 分析: 1.1 ≤ n ≤ 109,而1 ≤x, y  ...

  4. POJ 1004:Financial Management

    Financial Management Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 165062   Accepted: ...

  5. EUI库 - EXML

        EXML是可以运行时加载解析的   <e:Skin class="skins.ButtonSkin" states="up,down,disabled&qu ...

  6. ContentProvider ContentResolver ContentObserver 内容:提供、访问、监听

    内容提供 public class PersonContentProvider extends ContentProvider{ private static final String AUTHORI ...

  7. cf 766#

    天呢,太垃圾了我.. AB懵逼了半天题意,C最后搞了个DP还不对...DP太垃圾了,, #include<bits/stdc++.h> #define INF 0x7fffffff #de ...

  8. 全面掌握Nginx配置+快速搭建高可用架构 一 Nginx请求限制

    三次握手细节 语法: key为分配空间的关键字,以及分配空间的大小 示例: 压力测试工具ab

  9. UVA 10054 The Necklace 转化成欧拉回路

    题意比较简单,给你n个项链碎片,每个碎片的两半各有一种颜色,最后要把这n个碎片串成一个项链,要求就是相邻碎片必须是同种颜色挨着. 看了下碎片总共有1000个,颜色有50种,瞬间觉得普通方法是无法在可控 ...

  10. 服务器io资源查看

    资源查看命令安装 yum provides /usr/bin/find #查看命令是哪个软件包安装的 执行 yum provides */netstat 命令就可以看到提供命令的工具包net-tool ...