您的位置:首页 > 其它

TensorFlow(五)常用函数与基本操作

2018-02-02 22:05 405 查看

tensorflow的基本运作

1、tensorflow的基本运作

2、tf函数

TensorFlow 将图形定义转换成分布式执行的操作, 以充分利用可用的计算资源
(如 CPU 或 GPU。一般你不需要显式指定使用 CPU 还是 GPU,TensorFlow 能自动检测。
如果检测到 GPU, TensorFlow 会尽可能地利用找到的第一个 GPU 来执行操作.
并行计算能让代价大的算法计算加速执行,TensorFlow也在实现上对复杂操作进行了有效的改进。
大部分核相关的操作都是设备相关的实现,比如GPU。
1
2
3
[/code]

操作组操作
Building GraphsCore graph data structures,Tensor types,Utility functions
Inputs and ReadersPlaceholders,Readers,Converting,Queues,Input pipeline

2.1 建立图(Building Graphs)

本节主要介绍建立tensorflow图的相关类或函数

* 核心图的数据结构(Core graph data structures)

tf.Graph

操作描述
class tf.Graphtensorflow中的计算以图数据流的方式表示
一个图包含一系列表示计算单元的操作对象
以及在图中流动的数据单元以tensor对象表现
tf.Graph.__init__()建立一个空图
tf.Graph.as_default()一个将某图设置为默认图,并返回一个上下文管理器
如果不显式添加一个默认图,系统会自动设置一个全局的默认图。
所设置的默认图,在模块范围内所定义的节点都将默认加入默认图中
tf.Graph.as_graph_def
(from_version=None, add_shapes=False)
返回一个图的序列化的GraphDef表示
序列化的GraphDef可以导入至另一个图中(使用 import_graph_def())
或者使用C++ Session API
tf.Graph.finalize()完成图的构建,即将其设置为只读模式
tf.Graph.finalized返回True,如果图被完成
tf.Graph.control_dependencies(control_inputs)定义一个控制依赖,并返回一个上下文管理器
with g.control_dependencies([a, b, c]):
# `d` 和 `e` 将在 `a`, `b`, 和`c`执行完之后运行.
d = …
e = …
tf.Graph.device(device_name_or_function)定义运行图所使用的设备,并返回一个上下文管理器
with g.device('/gpu:0'): ...

with g.device('/cpu:0'): ...
tf.Graph.name_scope(name)为节点创建层次化的名称,并返回一个上下文管理器
tf.Graph.add_to_collection(name, value)将value以name的名称存储在收集器(collection)中
tf.Graph.get_collection(name, scope=None)根据name返回一个收集器中所收集的值的列表
tf.Graph.as_graph_element
(obj, allow_tensor=True, allow_operation=True)
返回一个图中与obj相关联的对象,为一个操作节点或者tensor数据
tf.Graph.get_operation_by_name(name)根据名称返回操作节点
tf.Graph.get_tensor_by_name(name)根据名称返回tensor数据
tf.Graph.get_operations()返回图中的操作节点列表
tf.Graph.gradient_override_map(op_type_map)用于覆盖梯度函数的上下文管理器
#class tf.Graph
#tensorflow运行时需要设置默认的图
g = tf.Graph()
with g.as_default():
# Define operations and tensors in `g`.
c = tf.constant(30.0)
assert c.graph is g

##也可以使用tf.get_default_graph()获得默认图,也可在基础上加入节点或子图
c = tf.constant(4.0)
assert c.graph is tf.get_default_graph()
1
2
3
4
5
6
7
8
9
10
11
[/code]

#tf.Graph.as_default
#以下两段代码功能相同
#1、使用Graph.as_default():
g = tf.Graph()
with g.as_default():
c = tf.constant(5.0)
assert c.graph is g

#2、构造和设置为默认
with tf.Graph().as_default() as g:
c = tf.constant(5.0)
assert c.graph is g
1
2
3
4
5
6
7
8
9
10
11
12
[/code]

#tf.Graph.control_dependencies(control_inputs)
# 错误代码
def my_func(pred, tensor):
t = tf.matmul(tensor, tensor)
with tf.control_dependencies([pred]):
# 乘法操作(op)没有创建在该上下文,所以没有被加入依赖控制
return t

# 正确代码
def my_func(pred, tensor):
with tf.control_dependencies([pred]):
# 乘法操作(op)创建在该上下文,所以被加入依赖控制中
#执行完pred之后再执行matmul
return tf.matmul(tensor, tensor)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[/code]

# tf.Graph.name_scope(name)
# 一个图中包含有一个名称范围的堆栈,在使用name_scope(...)之后,将压(push)新名称进栈中,
#并在下文中使用该名称
with tf.Graph().as_default() as g:
c = tf.constant(5.0, name="c")
assert c.op.name == "c"
c_1 = tf.constant(6.0, name="c")
assert c_1.op.name == "c_1"

# Creates a scope called "nested"
with g.name_scope("nested") as scope:
nested_c = tf.constant(10.0, name="c")
assert nested_c.op.name == "nested/c"

# Creates a nested scope called "inner".
with g.name_scope("inner"):
nested_inner_c = tf.constant(20.0, name="c")
assert nested_inner_c.op.name == "nested/inner/c"

# Create a nested scope called "inner_1".
with g.name_scope("inner"):
nested_inner_1_c = tf.constant(30.0, name="c")
assert nested_inner_1_c.op.name == "nested/inner_1/c"

# Treats `scope` as an absolute name scope, and
# switches to the "nested/" scope.
with g.name_scope(scope):
nested_d = tf.constant(40.0, name="d")
assert nested_d.op.name == "nested/d"

with g.name_scope(""):
e = tf.constant(50.0, name="e")
assert e.op.name == "e"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
[/code]

tf.Operation

操作描述
class tf.Operation代表图中的一个节点,用于计算tensors数据
该类型将由python节点构造器产生(比如tf.matmul())
或者Graph.create_op()
例如c = tf.matmul(a, b)创建一个Operation类
为类型为”MatMul”,输入为’a’,’b’,输出为’c’的操作类
tf.Operation.name操作节点(op)的名称
tf.Operation.type操作节点(op)的类型,比如”MatMul”
tf.Operation.inputs
tf.Operation.outputs
操作节点的输入与输出
tf.Operation.control_inputs操作节点的依赖
tf.Operation.run(feed_dict=None, session=None)在会话(Session)中运行该操作
tf.Operation.get_attr(name)获取op的属性值
tf.Tensor

操作描述
class tf.Tensor表示一个由操作节点op产生的值,
TensorFlow程序使用tensor数据结构来代表所有的数据,
计算图中, 操作间传递的数据都是 tensor,一个tensor是一个符号handle,
里面并没有表示实际数据,而相当于数据流的载体
tf.Tensor.dtypetensor中数据类型
tf.Tensor.name该tensor名称
tf.Tensor.value_index该tensor输出外op的index
tf.Tensor.graph该tensor所处在的图
tf.Tensor.op产生该tensor的op
tf.Tensor.consumers()返回使用该tensor的op列表
tf.Tensor.eval(feed_dict=None, session=None)在会话中求tensor的值
需要使用
with sess.as_default()
或者
eval(session=sess)
tf.Tensor.get_shape()返回用于表示tensor的shape的类TensorShape
tf.Tensor.set_shape(shape)更新tensor的shape
tf.Tensor.device设置计算该tensor的设备
#tf.Tensor.get_shape()
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
==> TensorShape([Dimension(2), Dimension(3)])
1
2
3
4
[/code]

#现在有个用于图像处理的tensor->image
print(image.get_shape())
==> TensorShape([Dimension(None), Dimension(None), Dimension(3)])
# 假如我们知道数据集中图像尺寸为28 x 28,那么可以设置
image.set_shape([28, 28, 3])
print(image.get_shape())
==> TensorShape([Dimension(28), Dimension(28), Dimension(3)])
1
2
3
4
5
6
7
[/code]

* tensor类型(Tensor types)

tf.DType

操作描述
class tf.DType数据类型主要包含
tf.float16,tf.float16,tf.float32,tf.float64,
tf.bfloat16,tf.complex64,tf.complex128,
tf.int8,tf.uint8,tf.uint16,tf.int16,tf.int32,
tf.int64,tf.bool,tf.string
tf.DType.is_compatible_with(other)判断other的数据类型是否将转变为该DType
tf.DType.name数据类型名称
tf.DType.base_dtype返回该DType的基础DType,而非参考的数据类型(non-reference)
tf.DType.as_ref返回一个基于DType的参考数据类型
tf.DType.is_floating判断是否为浮点类型
tf.DType.is_complex判断是否为复数
tf.DType.is_integer判断是否为整数
tf.DType.is_unsigned判断是否为无符号型数据
tf.DType.as_numpy_dtype返回一个基于DType的numpy.dtype类型
tf.DType.max
tf.DType.min
返回这种数据类型能表示的最大值及其最小值
tf.as_dtype(type_value)返回由type_value转变得的相应tf数据类型

* 通用函数(Utility functions)

操作描述
tf.device(device_name_or_function)基于默认的图,其功能便为Graph.device()
tf.container(container_name)基于默认的图,其功能便为Graph.container()
tf.name_scope(name)基于默认的图,其功能便为 Graph.name_scope()
tf.control_dependencies(control_inputs)基于默认的图,其功能便为Graph.control_dependencies()
tf.convert_to_tensor
(value, dtype=None, name=None, as_ref=False)
将value转变为tensor数据类型
tf.get_default_graph()返回返回当前线程的默认图
tf.reset_default_graph()清除默认图的堆栈,并设置全局图为默认图
tf.import_graph_def(graph_def, input_map=None,
return_elements=None, name=None, op_dict=None,
producer_op_list=None)
将graph_def的图导入到python中

* 图收集(Graph collections)

操作描述
tf.add_to_collection(name, value)基于默认的图,其功能便为Graph.add_to_collection()
tf.get_collection(key, scope=None)基于默认的图,其功能便为Graph.get_collection()

* 定义新操作节点(Defining new operations)

tf.RegisterGradient

操作描述
class tf.RegisterGradient返回一个用于寄存op类型的梯度函数的装饰器
tf.NoGradient(op_type)设置操作节点类型op_type的节点没有指定的梯度
class tf.RegisterShape返回一个用于寄存op类型的shape函数的装饰器
class tf.TensorShape表示tensor的shape
tf.TensorShape.merge_with(other)与other合并shape信息,返回一个TensorShape类
tf.TensorShape.concatenate(other)与other的维度相连结
tf.TensorShape.ndims返回tensor的rank
tf.TensorShape.dims返回tensor的维度
tf.TensorShape.as_list()以list的形式返回tensor的shape
tf.TensorShape.is_compatible_with(other)判断shape是否为兼容
TensorShape(None)与其他任何shape值兼容
class tf.Dimension
tf.Dimension.is_compatible_with(other)判断dims是否为兼容
tf.Dimension.merge_with(other)与other合并dims信息
tf.op_scope(values, name, default_name=None)在python定义op时,返回一个上下文管理器
#tf.RegisterGradient
#该装饰器只使用于定义一个新的op类型时候,如果一个op有m个输入,n个输出。那么该梯度函数应该设置原始的
#操作类型,以及n个Tensor对象(表示每一个op输出的梯度),以及m个对象(表示每一个op输入的偏梯度)
#以操作节点类型为'Sub'为例,两输入为x,y。为一个输出x-y
@tf.RegisterGradient("Sub")
def _sub_grad(unused_op, grad):
return grad, tf.neg(grad)
1
2
3
4
5
6
7
[/code]

#tf.op_scope
#定义一个名称为my_op的python操作节点op
def my_op(a, b, c, name=None):
with tf.op_scope([a, b, c], name, "MyOp") as scope:
a = tf.convert_to_tensor(a, name="a")
b = tf.convert_to_tensor(b, name="b")
c = tf.convert_to_tensor(c, name="c")
# Define some computation that uses `a`, `b`, and `c`.
return foo_op(..., name=scope)
1
2
3
4
5
6
7
8
9
[/code]

2.2 输入和读取器(Inputs and Readers)

本节主要介绍tensorflow中数据的读入相关类或函数

* 占位符(Placeholders)

tf提供一种占位符操作,在执行时需要为其提供数据data。

操作描述
tf.placeholder(dtype, shape=None, name=None)为一个tensor插入一个占位符
eg:x = tf.placeholder(tf.float32, shape=(1024, 1024))
tf.placeholder_with_default(input, shape, name=None)当输出没有fed时,input通过一个占位符op
tf.sparse_placeholder(dtype, shape=None, name=None)为一个稀疏tensor插入一个占位符

* 读取器(Readers)

tf提供一系列读取各种数据格式的类。对于多文件输入,可以使用函数tf.train.string_input_producer,该函数将创建一个保持文件的FIFO队列,以供reader使用。或者如果输入的这些文件名有相雷同的字符串,也可以使用函数tf.train.match_filenames_once

操作描述
class tf.ReaderBase不同的读取器类型的基本类
tf.ReaderBase.read(queue, name=None)返回下一个记录对(key, value),queue为tf文件队列FIFOQueue
tf.ReaderBase.read_up_to(queue, num_records, name=None)返回reader产生的num_records对(key, value)
tf.ReaderBase.reader_ref返回应用在该reader上的Op
tf.ReaderBase.reset(name=None)恢复reader为初始状态
tf.ReaderBase.restore_state(state, name=None)恢复reader为之前的保存状态state
tf.ReaderBase.serialize_state(name=None)返回一个reader解码后产生的字符串tansor
class tf.TextLineReader
tf.TextLineReader.num_records_produced(name=None)返回reader已经产生的记录(records )数目
tf.TextLineReader.num_work_units_completed(name=None)返回该reader已经完成的处理的work数目
tf.TextLineReader.read(queue, name=None)返回reader所产生的下一个记录对 (key, value),该reader可以限定新产生输出的行数
tf.TextLineReader.reader_ref返回应用在该reader上的Op
tf.TextLineReader.reset(name=None)恢复reader为初始状态
tf.TextLineReader.restore_state(state, name=None)恢复reader为之前的保存状态state
tf.TextLineReader.serialize_state(name=None)返回一个reader解码后产生的字符串tansor
class tf.WholeFileReader一个阅读器,读取整个文件,返回文件名称key,以及文件中所有的内容value,该类的方法同上,不赘述
class tf.IdentityReader一个reader,以key和value的形式,输出一个work队列。该类其他方法基本同上
class tf.TFRecordReader读取TFRecord格式文件的reader。该类其他方法基本同上
class tf.FixedLengthRecordReader输出

* 数据转换(Converting)

tf提供一系列方法将各种格式数据转换为tensor表示。

操作描述
tf.decode_csv(records, record_defaults, field_delim=None, name=None)将csv转换为tensor,与tf.TextLineReader搭配使用
tf.decode_raw(bytes, out_type, little_endian=None, name=None)将bytes转换为一个数字向量表示,bytes为一个字符串类型的tensor与函数 tf.FixedLengthRecordReader搭配使用,详见tf的CIFAR-10例子
选取与要输入的文件格式相匹配的reader,并将文件队列提供给reader的读方法( read method)。读方法将返回文件唯一标识的key,以及一个记录(record)(有助于对出现一些另类的records时debug),以及一个标量的字符串值。再使用一个(或多个)解码器(decoder) 或转换操作(conversion ops)将字符串转换为tensor类型。

#读取文件队列,使用reader中read的方法,返回key与value
filename_queue = tf.train.string_input_producer(["file0.csv", "file1.csv"])
reader = tf.TextLineReader()
key, value = reader.read(filename_queue)

record_defaults = [[1], [1], [1], [1], [1]]
col1, col2, col3, col4, col5 = tf.decode_csv(
value, record_defaults=record_defaults)
features = tf.pack([col1, col2, col3, col4])

with tf.Session() as sess:
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

for i in range(1200):
# Retrieve a single instance:
example, label = sess.run([features, col5])

coord.request_stop()
coord.join(threads)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: