Tensorflow常用函数汇总_tensorflow函数

操作 描述
tf.nn.sigmoid_cross_entropy_with_logits(logits, targets, name=None)* 计算输入logits, targets的交叉熵
tf.nn.softmax(logits, name=None) 计算softmaxsoftmax[i, j] = exp(logits[i, j]) / sum_j(exp(logits[i, j]))
tf.nn.log_softmax(logits, name=None) logsoftmax[i, j] = logits[i, j] - log(sum(exp(logits[i])))
tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None) 计算logits和labels的softmax交叉熵logits, labels必须为相同的shape与数据类型
tf.nn.sparse_softmax_cross_entropy_with_logits(logits, labels, name=None) 计算logits和labels的softmax交叉熵
tf.nn.weighted_cross_entropy_with_logits(logits, targets, pos_weight, name=None) 与sigmoid_cross_entropy_with_logits()相似,但给正向样本损失加了权重pos_weight
  • 符号嵌入(Embeddings)
操作 描述
tf.nn.embedding_lookup(params, ids, partition_strategy=’mod’, name=None, validate_indices=True) 根据索引ids查询embedding列表params中的tensor值如果len(params) > 1,id将会安照partition_strategy策略进行分割1、如果partition_strategy为”mod”,id所分配到的位置为p = id % len(params)比如有13个ids,分为5个位置,那么分配方案为:[[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8], [4, 9]]2、如果partition_strategy为”div”,那么分配方案为:[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]
tf.nn.embedding_lookup_sparse(params, sp_ids, sp_weights, partition_strategy=’mod’, name=None, combiner=’mean’) 对给定的ids和权重查询embedding1、sp_ids为一个N x M的稀疏tensor,N为batch大小,M为任意,数据类型int642、sp_weights的shape与sp_ids的稀疏tensor权重,浮点类型,若为None,则权重为全’1’
  • 循环神经网络(Recurrent Neural Networks)
操作 描述
tf.nn.rnn(cell, inputs, initial_state=None, dtype=None, sequence_length=None, scope=None) 基于RNNCell类的实例cell建立循环神经网络
tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None) 基于RNNCell类的实例cell建立动态循环神经网络与一般rnn不同的是,该函数会根据输入动态展开返回(outputs,state)
tf.nn.state_saving_rnn(cell, inputs, state_saver, state_name, sequence_length=None, scope=None) 可储存调试状态的RNN网络
tf.nn.bidirectional_rnn(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None,sequence_length=None, scope=None) 双向RNN, 返回一个3元组tuple(outputs, output_state_fw, output_state_bw)

— tf.nn.rnn简要介绍— 
cell: 一个RNNCell实例 
inputs: 一个shape为[batch_size, input_size]的tensor 
initial_state: 为RNN的state设定初值,可选 
sequence_length:制定输入的每一个序列的长度,size为[batch_size],值范围为[0, T)的int型数据 
其中T为输入数据序列的长度 

@针对输入batch中序列长度不同,所设置的动态计算机制 
@对于在时间t,和batch的b行,有 
(output, state)(b, t) = ? (zeros(cell.output_size), states(b, sequence_length(b) - 1)) : cell(input(b, t), state(b, t - 1))


  • 求值网络(Evaluation)
操作 描述
tf.nn.top_k(input, k=1, sorted=True, name=None) 返回前k大的值及其对应的索引
tf.nn.in_top_k(predictions, targets, k, name=None) 返回判断是否targets索引的predictions相应的值是否在在predictions前k个位置中,返回数据类型为bool类型,len与predictions同

对于有巨大量的多分类与多标签模型,如果使用全连接softmax将会占用大量的时间与空间资源,所以采用候选采样方法仅使用一小部分类别与标签作为监督以加速训练。

操作 描述
Sampled Loss Functions
tf.nn.nce_loss(weights, biases, inputs, labels, num_sampled,num_classes, num_true=1, sampled_values=None,remove_accidental_hits=False, partition_strategy=’mod’,name=’nce_loss’) 返回noise-contrastive的训练损失结果
tf.nn.sampled_softmax_loss(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None,remove_accidental_hits=True, partition_strategy=’mod’, name=’sampled_softmax_loss’) 返回sampled softmax的训练损失参考- Jean et al., 2014第3部分
Candidate Samplers
tf.nn.uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None) 通过均匀分布的采样集合返回三元tuple1、sampled_candidates 候选集合。2、期望的true_classes个数,为浮点值3、期望的sampled_candidates个数,为浮点值
tf.nn.log_uniform_candidate_sampler(true_classes, num_true,num_sampled, unique, range_max, seed=None, name=None) 通过log均匀分布的采样集合,返回三元tuple
tf.nn.learned_unigram_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None) 根据在训练过程中学习到的分布状况进行采样返回三元tuple
tf.nn.fixed_unigram_candidate_sampler(true_classes, num_true,num_sampled, unique, range_max, vocab_file=”, distortion=1.0, num_reserved_ids=0, num_shards=1, shard=0, unigrams=(), seed=None, name=None) 基于所提供的基本分布进行采样

保存与恢复变量

操作 描述
类tf.train.Saver(Saving and Restoring Variables)
tf.train.Saver.__init__(var_list=None, reshape=False, sharded=False, max_to_keep=5, keep_checkpoint_every_n_hours=10000.0, name=None, restore_sequentially=False,saver_def=None, builder=None) 创建一个存储器Savervar_list定义需要存储和恢复的变量
tf.train.Saver.save(sess, save_path, global_step=None, latest_filename=None, meta_graph_suffix=’meta’,write_meta_graph=True) 保存变量
tf.train.Saver.restore(sess, save_path) 恢复变量
tf.train.Saver.last_checkpoints 列出最近未删除的checkpoint 文件名
tf.train.Saver.set_last_checkpoints(last_checkpoints) 设置checkpoint文件名列表
tf.train.Saver.set_last_checkpoints_with_time(last_checkpoints_with_time) 设置checkpoint文件名列表和时间戳

第二部分

1、tensorflow的基本运作

为了快速的熟悉TensorFlow编程,下面从一段简单的代码开始:

import tensorflow as tf
 #定义‘符号’变量,也称为占位符
 a = tf.placeholder("float")
 b = tf.placeholder("float")

 y = tf.mul(a, b) #构造一个op节点

 sess = tf.Session()#建立会话
 #运行会话,输入数据,并计算节点,同时打印结果
 print sess.run(y, feed_dict={a: 3, b: 3})
 # 任务完成, 关闭会话.
 sess.close()

其中tf.mul(a, b)函数便是tf的一个基本的算数运算,接下来介绍跟多的相关函数。

2、tf函数

TensorFlow 将图形定义转换成分布式执行的操作, 以充分利用可用的计算资源(如 CPU 或 GPU。一般你不需要显式指定使用 CPU 还是 GPU, TensorFlow 能自动检测。如果检测到 GPU, TensorFlow 会尽可能地利用找到的第一个 GPU 来执行操作.
并行计算能让代价大的算法计算加速执行,TensorFlow也在实现上对复杂操作进行了有效的改进。大部分核相关的操作都是设备相关的实现,比如GPU。本文主要涉及的相关概念或操作有以下内容:
操作组 操作
Building Graphs Core graph data structures,Tensor types,Utility functions
Inputs and Readers Placeholders,Readers,Converting,Queues,Input pipeline
2.1 建立图(Building Graphs)

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

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

tf.Graph

操作 描述
class tf.Graph tensorflow中的计算以图数据流的方式表示一个图包含一系列表示计算单元的操作对象以及在图中流动的数据单元以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]):# de 将在 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()
#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
#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)
# 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"

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.inputstf.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.dtype tensor中
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值