`
wx1568037608
  • 浏览: 33464 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

第十六节,使用函数封装库tf.contrib.layers

 
阅读更多

目录

 


这一节,介绍TensorFlow中的一个封装好的高级库,里面有前面讲过的很多函数的高级封装,使用这个高级库来开发程序将会提高效率。

我们改写第十三节的程序,卷积函数我们使用tf.contrib.layers.conv2d(),池化函数使用tf.contrib.layers.max_pool2d()和tf.contrib.layers.avg_pool2d(),全连接函数使用tf.contrib.layers.fully_connected()。

一 tf.contrib.layers中的具体函数介绍

1.tf.contrib.layers.conv2d()函数的定义如下:

复制代码
def convolution(inputs,
                num_outputs,
                kernel_size,
                stride=1,
                padding='SAME',
                data_format=None,
                rate=1,
                activation_fn=nn.relu,
                normalizer_fn=None,
                normalizer_params=None,
                weights_initializer=initializers.xavier_initializer(),
                weights_regularizer=None,
                biases_initializer=init_ops.zeros_initializer(),
                biases_regularizer=None,
                reuse=None,
                variables_collections=None,
                outputs_collections=None,
                trainable=True,
                scope=None):
复制代码

常用的参数说明如下:

  • inputs:形状为[batch_size, height, width, channels]的输入。
  • num_outputs:代表输出几个channel。这里不需要再指定输入的channel了,因为函数会自动根据inpus的shpe去判断。
  • kernel_size:卷积核大小,不需要带上batch和channel,只需要输入尺寸即可。[5,5]就代表5x5的卷积核,如果长和宽都一样,也可以只写一个数5.
  • stride:步长,默认是长宽都相等的步长。卷积时,一般都用1,所以默认值也是1.如果长和宽都不相等,也可以用一个数组[1,2]。
  • padding:填充方式,'SAME'或者'VALID'。
  • activation_fn:激活函数。默认是ReLU。也可以设置为None
  • weights_initializer:权重的初始化,默认为initializers.xavier_initializer()函数。
  • weights_regularizer:权重正则化项,可以加入正则函数。biases_initializer:偏置的初始化,默认为init_ops.zeros_initializer()函数。
  • biases_regularizer:偏置正则化项,可以加入正则函数。
  • trainable:是否可训练,如作为训练节点,必须设置为True,默认即可。如果我们是微调网络,有时候需要冻结某一层的参数,则设置为False。

2.tf.contrib.layers.max_pool2d()函数的定义如下:

复制代码
def max_pool2d(inputs,
               kernel_size,
               stride=2,
               padding='VALID',
               data_format=DATA_FORMAT_NHWC,
               outputs_collections=None,
               scope=None):
复制代码

参数说明如下:

  • inputs: A 4-D tensor of shape `[batch_size, height, width, channels]` if`data_format` is `NHWC`, and `[batch_size, channels, height, width]` if `data_format` is `NCHW`.
  • kernel_size: A list of length 2: [kernel_height, kernel_width] of the pooling kernel over which the op is computed. Can be an int if both values are the same.
  • stride: A list of length 2: [stride_height, stride_width].Can be an int if both strides are the same. Note that presently both strides must have the same value.
  • padding: The padding method, either 'VALID' or 'SAME'.
  • data_format: A string. `NHWC` (default) and `NCHW` are supported.
  • outputs_collections: The collections to which the outputs are added.
  • scope: Optional scope for name_scope.

3.tf.contrib.layers.avg_pool2d()函数定义

 

复制代码
def avg_pool2d(inputs,
               kernel_size,
               stride=2,
               padding='VALID',
               data_format=DATA_FORMAT_NHWC,
               outputs_collections=None,
               scope=None):
复制代码

参数说明如下:

  • inputs: A 4-D tensor of shape `[batch_size, height, width, channels]` if`data_format` is `NHWC`, and `[batch_size, channels, height, width]` if `data_format` is `NCHW`.
  • kernel_size: A list of length 2: [kernel_height, kernel_width] of the pooling kernel over which the op is computed. Can be an int if both values are the same.
  • stride: A list of length 2: [stride_height, stride_width].Can be an int if both strides are the same. Note that presently both strides must have the same value.
  • padding: The padding method, either 'VALID' or 'SAME'.
  • data_format: A string. `NHWC` (default) and `NCHW` are supported.
  • outputs_collections: The collections to which the outputs are added.
  • scope: Optional scope for name_scope.

4.tf.contrib.layers.fully_connected()函数的定义如下:

复制代码
def fully_connected(inputs,
                    num_outputs,
                    activation_fn=nn.relu,
                    normalizer_fn=None,
                    normalizer_params=None,
                    weights_initializer=initializers.xavier_initializer(),
                    weights_regularizer=None,
                    biases_initializer=init_ops.zeros_initializer(),
                    biases_regularizer=None,
                    reuse=None,
                    variables_collections=None,
                    outputs_collections=None,
                    trainable=True,
                    scope=None):
复制代码

参数说明如下:

  • inputs: A tensor of at least rank 2 and static value for the last dimension; i.e. `[batch_size, depth]`, `[None, None, None, channels]`.
  • num_outputs: Integer or long, the number of output units in the layer.
  • activation_fn: Activation function. The default value is a ReLU function.Explicitly set it to None to skip it and maintain a linear activation.
  • normalizer_fn: Normalization function to use instead of `biases`. If `normalizer_fn` is provided then `biases_initializer` and
  • `biases_regularizer` are ignored and `biases` are not created nor added.default set to None for no normalizer function
  • normalizer_params: Normalization function parameters.
  • weights_initializer: An initializer for the weights.
  • weights_regularizer: Optional regularizer for the weights.
  • biases_initializer: An initializer for the biases. If None skip biases.
  • biases_regularizer: Optional regularizer for the biases.
  • reuse: Whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given.
  • variables_collections: Optional list of collections for all the variables or a dictionary containing a different list of collections per variable.
  • outputs_collections: Collection to add the outputs.
  • trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).如果我们是微调网络,有时候需要冻结某一层的参数,则设置为False。
  • scope: Optional scope for variable_scope.

 

二 改写cifar10分类

代码如下:

复制代码
# -*- coding: utf-8 -*-
"""
Created on Thu May  3 12:29:16 2018

@author: zy
"""

'''
建立一个带有全连接层的卷积神经网络  并对CIFAR-10数据集进行分类
1.使用2个卷积层的同卷积操作,滤波器大小为5x5,每个卷积层后面都会跟一个步长为2x2的池化层,滤波器大小为2x2
2.对输出的64个feature map进行全局平均池化,得到64个特征
3.加入一个全连接层,使用softmax激活函数,得到分类
'''

import cifar10_input
import tensorflow as tf
import numpy as np

def print_op_shape(t):
    '''
    输出一个操作op节点的形状
    '''
    print(t.op.name,'',t.get_shape().as_list())

'''
一 引入数据集
'''
batch_size = 128
learning_rate = 1e-4
training_step = 15000
display_step = 200
#数据集目录
data_dir = './cifar10_data/cifar-10-batches-bin'
print('begin')
#获取训练集数据
images_train,labels_train = cifar10_input.inputs(eval_data=False,data_dir = data_dir,batch_size=batch_size)
print('begin data')


'''
二 定义网络结构
'''

#定义占位符
input_x = tf.placeholder(dtype=tf.float32,shape=[None,24,24,3])   #图像大小24x24x
input_y = tf.placeholder(dtype=tf.float32,shape=[None,10])        #0-9类别 

x_image = tf.reshape(input_x,[batch_size,24,24,3])

#1.卷积层 ->池化层

h_conv1 = tf.contrib.layers.conv2d(inputs=x_image,num_outputs=64,kernel_size=5,stride=1,padding='SAME', activation_fn=tf.nn.relu)    #输出为[-1,24,24,64]
print_op_shape(h_conv1)
h_pool1 = tf.contrib.layers.max_pool2d(inputs=h_conv1,kernel_size=2,stride=2,padding='SAME')         #输出为[-1,12,12,64]
print_op_shape(h_pool1)


#2.卷积层 ->池化层

h_conv2 =tf.contrib.layers.conv2d(inputs=h_pool1,num_outputs=64,kernel_size=[5,5],stride=[1,1],padding='SAME', activation_fn=tf.nn.relu)    #输出为[-1,12,12,64]
print_op_shape(h_conv2)
h_pool2 =  tf.contrib.layers.max_pool2d(inputs=h_conv2,kernel_size=[2,2],stride=[2,2],padding='SAME')   #输出为[-1,6,6,64]
print_op_shape(h_pool2)



#3全连接层

nt_hpool2 = tf.contrib.layers.avg_pool2d(inputs=h_pool2,kernel_size=6,stride=6,padding='SAME')          #输出为[-1,1,1,64]
print_op_shape(nt_hpool2)
nt_hpool2_flat = tf.reshape(nt_hpool2,[-1,64])            
y_conv = tf.contrib.layers.fully_connected(inputs=nt_hpool2_flat,num_outputs=10,activation_fn=tf.nn.softmax)
print_op_shape(y_conv)

'''
三 定义求解器
'''

#softmax交叉熵代价函数
cost = tf.reduce_mean(-tf.reduce_sum(input_y * tf.log(y_conv),axis=1))

#求解器
train = tf.train.AdamOptimizer(learning_rate).minimize(cost)

#返回一个准确度的数据
correct_prediction = tf.equal(tf.arg_max(y_conv,1),tf.arg_max(input_y,1))
#准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,dtype=tf.float32))

'''
四 开始训练
'''
sess = tf.Session();
sess.run(tf.global_variables_initializer())
# 启动计算图中所有的队列线程 调用tf.train.start_queue_runners来将文件名填充到队列,否则read操作会被阻塞到文件名队列中有值为止。
tf.train.start_queue_runners(sess=sess)

for step in range(training_step):
    #获取batch_size大小数据集
    image_batch,label_batch = sess.run([images_train,labels_train])
    
    #one hot编码
    label_b = np.eye(10,dtype=np.float32)[label_batch]
    
    #开始训练
    train.run(feed_dict={input_x:image_batch,input_y:label_b},session=sess)
    
    if step % display_step == 0:
        train_accuracy = accuracy.eval(feed_dict={input_x:image_batch,input_y:label_b},session=sess)
        print('Step {0} tranining accuracy {1}'.format(step,train_accuracy))
复制代码

 

分享到:
评论

相关推荐

    tf API:网络构建模块tf.nn,tf.layers, tf.contrib

    在使用tensorflow构建神经网络时,经常看到tf.nn,tf.layers,tf.contrib这三个模块,它们有很多函数的功能是相同的,部分可以混用,这就导致使用者很容易被迷惑,本文在此做一下笔记以理清思路。 tf.nn:用于原始...

    tensorflow.contrib安装

    import tensorflow.contrib.layers as tf_layers tf_layers.fully_connected(xxxx) ``` 改为: ``` import tf_slim as tf_layers tf_layers.fully_connected(xxxx) ``` 此外,还需要注意一些包的名称已经改变,...

    Tensorflow:tf.contrib.rnn.DropoutWrapper函数(谷歌已经为Dropout申请了专利!)、MultiRNNCell函数的解读与理解

    Tensorflow:tf.contrib.rnn.DropoutWrapper函数(谷歌已经为Dropout申请了专利!)、MultiRNNCell函数的解读与理解 目录 1、tf.contrib.rnn.DropoutWrapper函数解读与理解 1.1、源代码解读 1.2、案例应用 2、tf....

    tf.nn,tf.layers, tf.contrib模块

    在TensorFlow库中,我们经常会遇到`tf.nn`,`tf.layers`,以及`tf.contrib`这三个模块。它们各自有着不同的特性和用途,为开发者提供了丰富的工具来构建复杂的深度学习模型,尤其是对于卷积神经网络(CNNs)的实现。...

    TensorFlow2没有contrib_slim包的问题.pdf

    tensorflow2.0弃用了tf.contrib.slim库 在tf.compat.v1兼容模式下解决slim no module的问题 修改说明一点: 必须用第一种方法安装tf-slim库!!!经测试第二种方法安装的slim库仍然可能会报错。

    不降级解决No module named ‘tensorflow.contrib‘.pdf

    这涉及到查找替代的API或者使用新的第三方库来实现原本`tensorflow.contrib`中的功能。例如,如描述中提到的`viterbi_decode`函数,它现在可能在`tensorflow_addons`库中可以找到。 关于`tensorflow_addons`库的...

    Tensorflow 利用tf.contrib.learn建立输入函数的方法

    在TensorFlow中,`tf.contrib.learn`库提供了一种便捷的方式来构建机器学习模型,特别是对于数据预处理和输入管道的管理。本篇文章将详细介绍如何利用`tf.contrib.learn`中的`input_fn`方法来构建自定义的输入管道,...

    对tensorflow中tf.nn.conv1d和layers.conv1d的区别详解

    当然,随着TensorFlow版本的更新,新的API如`tf.keras.layers.Conv1D`(属于Keras API)也提供了更丰富的功能和更好的兼容性,使得模型构建更加容易和高效。 总结来说,`tf.nn.conv1d`和`layers.conv1d`都是执行一...

    Python库 | pyats.contrib-21.10.3b0-py3-none-any.whl

    **Python库pyats.contrib详解** `pyats.contrib`是Python中的一个开源库,它是Extreme Networks公司的自动化测试系统(pyATS)的一部分。pyATS是一个强大的框架,用于构建和执行网络设备的自动化测试用例,旨在简化...

    Python库 | pantsbuild.pants.contrib.avro-1.5.0.dev5.tar.gz

    《Python库深度解析:pantsbuild.pants.contrib.avro-1.5.0.dev5》 在Python的世界里,库是开发者的重要工具,它们为各种任务提供了便利和效率。本篇文章将深入探讨`pantsbuild.pants.contrib.avro-1.5.0.dev5`这一...

    Python库 | pantsbuild.pants.contrib.avro-1.5.0.tar.gz

    《Python库pantsbuild.pants.contrib.avro-1.5.0深度解析》 在Python的世界里,库扮演着至关重要的角色,它们为开发者提供了丰富的功能和便利性。今天,我们将聚焦于一个特定的库——pantsbuild.pants.contrib.avro...

    Python库 | schematec.contrib-0.1.9-py2.py3-none-any.whl

    标题中的"Python库 | schematec.contrib-0.1.9-py2.py3-none-any.whl"指的是一款名为`schematec.contrib`的Python库,版本为0.1.9。它以`.whl`文件形式提供,这是一种Python的预编译包格式,用于方便安装和分发...

    Python库 | pantsbuild.pants.contrib.findbugs-1.2.1.tar.gz

    《Python库深度解析:pantsbuild.pants.contrib.findbugs-1.2.1》 在Python的开发领域,库是开发者的重要工具,它们提供了丰富的功能,极大地提升了开发效率。本篇文章将深入探讨`pantsbuild.pants.contrib....

    Python库 | piped.contrib.manhole-0.1.0.tar.gz

    Python库piped.contrib.manhole-0.1.0是一个用于Python编程的重要工具,它扩展了Piped框架的功能,特别关注远程调试和管理。这个库的核心是`manhole`概念,这是一个安全的网络接口,允许开发者在运行时通过网络连接...

    hadoop.contrib/lucene源码

    Lucene是Java实现的全文搜索引擎库,它提供了高性能、可扩展的文本搜索功能。倒排索引是Lucene的核心数据结构,它允许快速地进行关键词查找。倒排索引通过将每个单词映射到包含该单词的文档列表,极大地提高了搜索...

    PyPI 官网下载 | pantsbuild.pants.contrib.node-0.0.56.tar.gz

    PyPI是Python开发者分享和获取第三方库的主要平台,用户可以使用pip工具从这里方便地安装各种Python库。 标签中的"Python库"揭示了这个资源的核心性质——它是一个用于Python编程的软件库。Python库通常包含一系列...

    PyPI 官网下载 | pantsbuild.pants.contrib.cpp-1.3.1rc1.tar.gz

    《PyPI官网下载:pantsbuild.pants.contrib.cpp-1.3.1rc1.tar.gz——深入解析Python C++扩展库》 在Python的世界里,为了增强其功能和性能,开发者们有时会借助C++这样的底层语言来编写扩展模块。PyPI(Python ...

    Python库 | piped.contrib.zookeeper-0.5.1.tar.gz

    "piped.contrib.zookeeper"是一个基于Python的库,它与描述中的“zookeeper”相关联,Zookeeper是一个分布式协调服务,广泛用于分布式系统中。版本号"0.5.1"表明这是该库的一个特定发行版,通常包含修复的错误、新增...

    Python库 | pantsbuild.pants.contrib.android-1.3.0rc3.tar.gz

    标题中的"pantsbuild.pants.contrib.android-1.3.0rc3.tar.gz"是一个Python库,专注于Android开发的工具包。这个库是pantsbuild项目的一部分,pantsbuild是一个强大的构建工具,用于管理和构建复杂的代码库,支持...

Global site tag (gtag.js) - Google Analytics