日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Tensorflow一些常用基本概念与函数

發布時間:2023/12/13 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Tensorflow一些常用基本概念与函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

參考文獻

Tensorflow一些常用基本概念與函數 http://www.cnblogs.com/wuzhitj/archive/2017/03.html

Tensorflow筆記:常用函數說明: http://blog.csdn.net/u014595019/article/details/52805444

Tensorflow一些常用基本概念與函數(1) http://blog.csdn.net/lenbow/article/details/52152766
Tensorflow一些常用基本概念與函數(2) http://blog.csdn.net/lenbow/article/details/52181159
Tensorflow一些常用基本概念與函數(3) http://blog.csdn.net/lenbow/article/details/52213105

Tensorflow一些常用基本概念與函數(4)http://blog.csdn.net/lenbow/article/details/52218551


-------------------------------------------------------------------

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。下面是一些重要的操作/核: 操作組操作
MathsAdd, Sub, Mul, Div, Exp, Log, Greater, Less, Equal
ArrayConcat, Slice, Split, Constant, Rank, Shape, Shuffle
MatrixMatMul, MatrixInverse, MatrixDeterminant
Neuronal NetworkSoftMax, Sigmoid, ReLU, Convolution2D, MaxPool
CheckpointingSave, Restore
Queues and syncronizationsEnqueue, Dequeue, MutexAcquire, MutexRelease
Flow controlMerge, Switch, Enter, Leave, NextIteration

TensorFlow的算術操作如下:

操作描述
tf.add(x, y, name=None)求和
tf.sub(x, y, name=None)減法
tf.mul(x, y, name=None)乘法
tf.div(x, y, name=None)除法
tf.mod(x, y, name=None)取模
tf.abs(x, name=None)求絕對值
tf.neg(x, name=None)取負 (y = -x).
tf.sign(x, name=None)返回符號 y = sign(x) = -1 if x < 0; 0 if x == 0; 1 if x > 0.
tf.inv(x, name=None)取反
tf.square(x, name=None)計算平方 (y = x * x = x^2).
tf.round(x, name=None)舍入最接近的整數
# ‘a’ is [0.9, 2.5, 2.3, -4.4]
tf.round(a) ==> [ 1.0, 3.0, 2.0, -4.0 ]
tf.sqrt(x, name=None)開根號 (y = \sqrt{x} = x^{1/2}).
tf.pow(x, y, name=None)冪次方
# tensor ‘x’ is [[2, 2], [3, 3]]
# tensor ‘y’ is [[8, 16], [2, 3]]
tf.pow(x, y) ==> [[256, 65536], [9, 27]]
tf.exp(x, name=None)計算e的次方
tf.log(x, name=None)計算log,一個輸入計算e的ln,兩輸入以第二輸入為底
tf.maximum(x, y, name=None)返回最大值 (x > y ? x : y)
tf.minimum(x, y, name=None)返回最小值 (x < y ? x : y)
tf.cos(x, name=None)三角函數cosine
tf.sin(x, name=None)三角函數sine
tf.tan(x, name=None)三角函數tan
tf.atan(x, name=None)三角函數ctan

張量操作Tensor Transformations

  • 數據類型轉換Casting
操作描述
tf.string_to_number
(string_tensor, out_type=None, name=None)
字符串轉為數字
tf.to_double(x, name=’ToDouble’)轉為64位浮點類型–float64
tf.to_float(x, name=’ToFloat’)轉為32位浮點類型–float32
tf.to_int32(x, name=’ToInt32’)轉為32位整型–int32
tf.to_int64(x, name=’ToInt64’)轉為64位整型–int64
tf.cast(x, dtype, name=None)將x或者x.values轉換為dtype
# tensor a is [1.8, 2.2], dtype=tf.float
tf.cast(a, tf.int32) ==> [1, 2] # dtype=tf.int32
??
  • 形狀操作Shapes and Shaping
操作描述
tf.shape(input, name=None)返回數據的shape
# ‘t’ is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]
shape(t) ==> [2, 2, 3]
tf.size(input, name=None)返回數據的元素數量
# ‘t’ is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]]
size(t) ==> 12
tf.rank(input, name=None)返回tensor的rank
注意:此rank不同于矩陣的rank,
tensor的rank表示一個tensor需要的索引數目來唯一表示任何一個元素
也就是通常所說的 “order”, “degree”或”ndims”
#’t’ is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]
# shape of tensor ‘t’ is [2, 2, 3]
rank(t) ==> 3
tf.reshape(tensor, shape, name=None)改變tensor的形狀
# tensor ‘t’ is [1, 2, 3, 4, 5, 6, 7, 8, 9]
# tensor ‘t’ has shape [9]
reshape(t, [3, 3]) ==>
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
#如果shape有元素[-1],表示在該維度打平至一維
# -1 將自動推導得為 9:
reshape(t, [2, -1]) ==>
[[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]]
tf.expand_dims(input, dim, name=None)插入維度1進入一個tensor中
#該操作要求-1-input.dims()
# ‘t’ is a tensor of shape [2]
shape(expand_dims(t, 0)) ==> [1, 2]
shape(expand_dims(t, 1)) ==> [2, 1]
shape(expand_dims(t, -1)) ==> [2, 1] <= dim <= input.dims()
  • 切片與合并(Slicing and Joining)
操作描述
tf.slice(input_, begin, size, name=None)對tensor進行切片操作
其中size[i] = input.dim_size(i) - begin[i]
該操作要求 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]
#’input’ is
#[[[1, 1, 1], [2, 2, 2]],[[3, 3, 3], [4, 4, 4]],[[5, 5, 5], [6, 6, 6]]]
tf.slice(input, [1, 0, 0], [1, 1, 3]) ==> [[[3, 3, 3]]]
tf.slice(input, [1, 0, 0], [1, 2, 3]) ==>
[[[3, 3, 3],
[4, 4, 4]]]
tf.slice(input, [1, 0, 0], [2, 1, 3]) ==>
[[[3, 3, 3]],
[[5, 5, 5]]]
tf.split(split_dim, num_split, value, name=’split’)沿著某一維度將tensor分離為num_split tensors
# ‘value’ is a tensor with shape [5, 30]
# Split ‘value’ into 3 tensors along dimension 1
split0, split1, split2 = tf.split(1, 3, value)
tf.shape(split0) ==> [5, 10]
tf.concat(concat_dim, values, name=’concat’)沿著某一維度連結tensor
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat(0, [t1, t2]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
如果想沿著tensor一新軸連結打包,那么可以:
tf.concat(axis, [tf.expand_dims(t, axis) for t in tensors])
等同于tf.pack(tensors, axis=axis)
tf.pack(values, axis=0, name=’pack’)將一系列rank-R的tensor打包為一個rank-(R+1)的tensor
# ‘x’ is [1, 4], ‘y’ is [2, 5], ‘z’ is [3, 6]
pack([x, y, z]) => [[1, 4], [2, 5], [3, 6]]
# 沿著第一維pack
pack([x, y, z], axis=1) => [[1, 2, 3], [4, 5, 6]]
等價于tf.pack([x, y, z]) = np.asarray([x, y, z])
tf.reverse(tensor, dims, name=None)沿著某維度進行序列反轉
其中dim為列表,元素為bool型,size等于rank(tensor)
# tensor ‘t’ is
[[[[ 0, 1, 2, 3],
#[ 4, 5, 6, 7],

#[ 8, 9, 10, 11]],
#[[12, 13, 14, 15],
#[16, 17, 18, 19],
#[20, 21, 22, 23]]]]
# tensor ‘t’ shape is [1, 2, 3, 4]
# ‘dims’ is [False, False, False, True]
reverse(t, dims) ==>
[[[[ 3, 2, 1, 0],
[ 7, 6, 5, 4],
[ 11, 10, 9, 8]],
[[15, 14, 13, 12],
[19, 18, 17, 16],
[23, 22, 21, 20]]]]
tf.transpose(a, perm=None, name=’transpose’)調換tensor的維度順序
按照列表perm的維度排列調換tensor順序,
如為定義,則perm為(n-1…0)
# ‘x’ is [[1 2 3],[4 5 6]]
tf.transpose(x) ==> [[1 4], [2 5],[3 6]]
# Equivalently
tf.transpose(x, perm=[1, 0]) ==> [[1 4],[2 5], [3 6]]
tf.gather(params, indices, validate_indices=None, name=None)合并索引indices所指示params中的切片
tf.one_hot
(indices, depth, on_value=None, off_value=None,
axis=None, dtype=None, name=None)
indices = [0, 2, -1, 1]
depth = 3
on_value = 5.0
off_value = 0.0
axis = -1
#Then output is [4 x 3]:
output =
[5.0 0.0 0.0] // one_hot(0)
[0.0 0.0 5.0] // one_hot(2)
[0.0 0.0 0.0] // one_hot(-1)
[0.0 5.0 0.0] // one_hot(1)

矩陣相關運算

操作描述
tf.diag(diagonal, name=None)返回一個給定對角值的對角tensor
# ‘diagonal’ is [1, 2, 3, 4]
tf.diag(diagonal) ==>
[[1, 0, 0, 0]
[0, 2, 0, 0]
[0, 0, 3, 0]
[0, 0, 0, 4]]
tf.diag_part(input, name=None)功能與上面相反
tf.trace(x, name=None)求一個2維tensor足跡,即對角值diagonal之和
tf.transpose(a, perm=None, name=’transpose’)調換tensor的維度順序
按照列表perm的維度排列調換tensor順序,
如為定義,則perm為(n-1…0)
# ‘x’ is [[1 2 3],[4 5 6]]
tf.transpose(x) ==> [[1 4], [2 5],[3 6]]
# Equivalently
tf.transpose(x, perm=[1, 0]) ==> [[1 4],[2 5], [3 6]]
tf.matmul(a, b, transpose_a=False,
transpose_b=False, a_is_sparse=False,
b_is_sparse=False, name=None)
矩陣相乘
tf.matrix_determinant(input, name=None)返回方陣的行列式
tf.matrix_inverse(input, adjoint=None, name=None)求方陣的逆矩陣,adjoint為True時,計算輸入共軛矩陣的逆矩陣
tf.cholesky(input, name=None)對輸入方陣cholesky分解,
即把一個對稱正定的矩陣表示成一個下三角矩陣L和其轉置的乘積的分解A=LL^T
tf.matrix_solve(matrix, rhs, adjoint=None, name=None)求解tf.matrix_solve(matrix, rhs, adjoint=None, name=None)
matrix為方陣shape為[M,M],rhs的shape為[M,K],output為[M,K]

復數操作

操作描述
tf.complex(real, imag, name=None)將兩實數轉換為復數形式
# tensor ‘real’ is [2.25, 3.25]
# tensor imag is [4.75, 5.75]
tf.complex(real, imag) ==> [[2.25 + 4.75j], [3.25 + 5.75j]]
tf.complex_abs(x, name=None)計算復數的絕對值,即長度。
# tensor ‘x’ is [[-2.25 + 4.75j], [-3.25 + 5.75j]]
tf.complex_abs(x) ==> [5.25594902, 6.60492229]
tf.conj(input, name=None)計算共軛復數
tf.imag(input, name=None)
tf.real(input, name=None)
提取復數的虛部和實部
tf.fft(input, name=None)計算一維的離散傅里葉變換,輸入數據類型為complex64

歸約計算(Reduction)

操作描述
tf.reduce_sum(input_tensor, reduction_indices=None,
keep_dims=False, name=None)
計算輸入tensor元素的和,或者安照reduction_indices指定的軸進行求和
# ‘x’ is [[1, 1, 1]
# [1, 1, 1]]
tf.reduce_sum(x) ==> 6
tf.reduce_sum(x, 0) ==> [2, 2, 2]
tf.reduce_sum(x, 1) ==> [3, 3]
tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]
tf.reduce_sum(x, [0, 1]) ==> 6
tf.reduce_prod(input_tensor,
reduction_indices=None,
keep_dims=False, name=None)
計算輸入tensor元素的乘積,或者安照reduction_indices指定的軸進行求乘積
tf.reduce_min(input_tensor,
reduction_indices=None,
keep_dims=False, name=None)
求tensor中最小值
tf.reduce_max(input_tensor,
reduction_indices=None,
keep_dims=False, name=None)
求tensor中最大值
tf.reduce_mean(input_tensor,
reduction_indices=None,
keep_dims=False, name=None)
求tensor中平均值
tf.reduce_all(input_tensor,
reduction_indices=None,
keep_dims=False, name=None)
對tensor中各個元素求邏輯’與’
# ‘x’ is
# [[True, True]
# [False, False]]
tf.reduce_all(x) ==> False
tf.reduce_all(x, 0) ==> [False, False]
tf.reduce_all(x, 1) ==> [True, False]
tf.reduce_any(input_tensor,
reduction_indices=None,
keep_dims=False, name=None)
對tensor中各個元素求邏輯’或’
tf.accumulate_n(inputs, shape=None,
tensor_dtype=None, name=None)
計算一系列tensor的和
# tensor ‘a’ is [[1, 2], [3, 4]]
# tensor b is [[5, 0], [0, 6]]
tf.accumulate_n([a, b, a]) ==> [[7, 4], [6, 14]]
tf.cumsum(x, axis=0, exclusive=False,
reverse=False, name=None)
求累積和
tf.cumsum([a, b, c]) ==> [a, a + b, a + b + c]
tf.cumsum([a, b, c], exclusive=True) ==> [0, a, a + b]
tf.cumsum([a, b, c], reverse=True) ==> [a + b + c, b + c, c]
tf.cumsum([a, b, c], exclusive=True, reverse=True) ==> [b + c, c, 0]
??

分割(Segmentation)

操作描述
tf.segment_sum(data, segment_ids, name=None)根據segment_ids的分段計算各個片段的和
其中segment_ids為一個size與data第一維相同的tensor
其中id為int型數據,最大id不大于size
c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
tf.segment_sum(c, tf.constant([0, 0, 1]))
==>[[0 0 0 0]
[5 6 7 8]]
上面例子分為[0,1]兩id,對相同id的data相應數據進行求和,
并放入結果的相應id中,
且segment_ids只升不降
tf.segment_prod(data, segment_ids, name=None)根據segment_ids的分段計算各個片段的積
tf.segment_min(data, segment_ids, name=None)根據segment_ids的分段計算各個片段的最小值
tf.segment_max(data, segment_ids, name=None)根據segment_ids的分段計算各個片段的最大值
tf.segment_mean(data, segment_ids, name=None)根據segment_ids的分段計算各個片段的平均值
tf.unsorted_segment_sum(data, segment_ids,
num_segments, name=None)
與tf.segment_sum函數類似,
不同在于segment_ids中id順序可以是無序的
tf.sparse_segment_sum(data, indices,
segment_ids, name=None)
輸入進行稀疏分割求和
c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
# Select two rows, one segment.
tf.sparse_segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0]))
==> [[0 0 0 0]]
對原data的indices為[0,1]位置的進行分割,
并按照segment_ids的分組進行求和

序列比較與索引提取(Sequence Comparison and Indexing)

操作描述
tf.argmin(input, dimension, name=None)返回input最小值的索引index
tf.argmax(input, dimension, name=None)返回input最大值的索引index
tf.listdiff(x, y, name=None)返回x,y中不同值的索引
tf.where(input, name=None)返回bool型tensor中為True的位置
# ‘input’ tensor is
#[[True, False]
#[True, False]]
# ‘input’ 有兩個’True’,那么輸出兩個坐標值.
# ‘input’的rank為2, 所以每個坐標為具有兩個維度.
where(input) ==>
[[0, 0],
[1, 0]]
tf.unique(x, name=None)返回一個元組tuple(y,idx),y為x的列表的唯一化數據列表,
idx為x數據對應y元素的index
# tensor ‘x’ is [1, 1, 2, 4, 4, 4, 7, 8, 8]
y, idx = unique(x)
y ==> [1, 2, 4, 7, 8]
idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]
tf.invert_permutation(x, name=None)置換x數據與索引的關系
# tensor x is [3, 4, 0, 2, 1]
invert_permutation(x) ==> [2, 4, 3, 0, 1]

神經網絡(Neural Network)

  • 激活函數(Activation Functions)
操作描述
tf.nn.relu(features, name=None)整流函數:max(features, 0)
tf.nn.relu6(features, name=None)以6為閾值的整流函數:min(max(features, 0), 6)
tf.nn.elu(features, name=None)elu函數,exp(features) - 1 if < 0,否則features
Exponential Linear Units (ELUs)
tf.nn.softplus(features, name=None)計算softplus:log(exp(features) + 1)
tf.nn.dropout(x, keep_prob,
noise_shape=None, seed=None, name=None)
計算dropout,keep_prob為keep概率
noise_shape為噪聲的shape
tf.nn.bias_add(value, bias, data_format=None, name=None)對value加一偏置量
此函數為tf.add的特殊情況,bias僅為一維,
函數通過廣播機制進行與value求和,
數據格式可以與value不同,返回為與value相同格式
tf.sigmoid(x, name=None)y = 1 / (1 + exp(-x))
tf.tanh(x, name=None)雙曲線切線激活函數
  • 卷積函數(Convolution)
操作描述
tf.nn.conv2d(input, filter, strides, padding,
use_cudnn_on_gpu=None, data_format=None, name=None)
在給定的4D input與 filter下計算2D卷積
輸入shape為 [batch, height, width, in_channels]
tf.nn.conv3d(input, filter, strides, padding, name=None)在給定的5D input與 filter下計算3D卷積
輸入shape為[batch, in_depth, in_height, in_width, in_channels]
  • 池化函數(Pooling)
操作描述
tf.nn.avg_pool(value, ksize, strides, padding,
data_format=’NHWC’, name=None)
平均方式池化
tf.nn.max_pool(value, ksize, strides, padding,
data_format=’NHWC’, name=None)
最大值方法池化
tf.nn.max_pool_with_argmax(input, ksize, strides,
padding, Targmax=None, name=None)
返回一個二維元組(output,argmax),最大值pooling,返回最大值及其相應的索引
tf.nn.avg_pool3d(input, ksize, strides,
padding, name=None)
3D平均值pooling
tf.nn.max_pool3d(input, ksize, strides,
padding, name=None)
3D最大值pooling
  • 數據標準化(Normalization)
操作描述
tf.nn.l2_normalize(x, dim, epsilon=1e-12, name=None)對維度dim進行L2范式標準化
output = x / sqrt(max(sum(x**2), epsilon))
tf.nn.sufficient_statistics(x, axes, shift=None,
keep_dims=False, name=None)
計算與均值和方差有關的完全統計量
返回4維元組,*元素個數,*元素總和,*元素的平方和,*shift結果
參見算法介紹
tf.nn.normalize_moments(counts, mean_ss, variance_ss, shift, name=None)基于完全統計量計算均值和方差
tf.nn.moments(x, axes, shift=None,
name=None, keep_dims=False)
直接計算均值與方差
  • 損失函數(Losses)
操作描述
tf.nn.l2_loss(t, name=None)output = sum(t ** 2) / 2
  • 分類函數(Classification)
操作描述
tf.nn.sigmoid_cross_entropy_with_logits
(logits, targets, name=None)*
計算輸入logits, targets的交叉熵
tf.nn.softmax(logits, name=None)計算softmax
softmax[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和權重查詢embedding
1、sp_ids為一個N x M的稀疏tensor,
N為batch大小,M為任意,數據類型int64
2、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同
  • 監督候選采樣網絡(Candidate Sampling)

對于有巨大量的多分類與多標簽模型,如果使用全連接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)
通過均勻分布的采樣集合
返回三元tuple
1、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)
創建一個存儲器Saver
var_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文件名列表和時間戳


3.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() #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之后再執行matmulreturn 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.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)]) #現在有個用于圖像處理的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)])

* 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) #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)

3.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)

* Example protocol buffer

提供了一些Example protocol buffers,tf所推薦的用于訓練樣本的數據格式,它們包含特征信息,詳情可見。
這是一種與前述將手上現有的各種數據類型轉換為支持的格式的方法,這種方法更容易將網絡結構與數據集融合或匹配。這種tensorflow所推薦的數據格式是一個包含tf.train.Example protocol buffers (包含特征Features域)的TFRecords文件。
1、獲取這種格式的文件方式為,首先將一般的數據格式填入Example protocol buffer中,再將 protocol buffer序列化為一個字符串,然后使用tf.python_io.TFRecordWriter類的相關方法將字符串寫入一個TFRecords文件中,參見MNIST例子,將MNIST 數據轉換為該類型數據。
2、讀取TFRecords格式文件的方法為,使用tf.TFRecordReader讀取器和tf.parse_single_example解碼器。parse_single_example操作將 example protocol buffers解碼為tensor形式。參見MNIST例子

操作描述
class tf.VarLenFeature解析變長的輸入特征feature相關配置
class tf.FixedLenFeature解析定長的輸入特征feature相關配置
class tf.FixedLenSequenceFeature序列項目中的稠密(dense )輸入特征的相關配置
tf.parse_example(serialized, features,
name=None, example_names=None)
將一組Example protos解析為tensor的字典形式
解析serialized所給予的序列化的一些Example protos
返回一個由特征keys映射Tensor和SparseTensor值的字典
tf.parse_single_example(serialized, features,
name=None, example_names=None)
解析一個單獨的Example proto,與tf.parse_example方法雷同
tf.decode_json_example(json_examples, name=None)將JSON編碼的樣本記錄轉換為二進制protocol buffer字符串

#tf.parse_example的使用舉例 #輸入序列化數據如下: serialized = [features{ feature { key: "ft" value { float_list { value: [1.0, 2.0] } } } },features{ feature []},features{ feature { key: "ft" value { float_list { value: [3.0] } } } ] #那么輸出為一個字典(dict),如下: {"ft": SparseTensor(indices=[[0, 0], [0, 1], [2, 0]],values=[1.0, 2.0, 3.0],shape=(3, 2)) } ######### #再來看一個例子,給定兩個序列化的原始輸入樣本: [features {feature { key: "kw" value { bytes_list { value: [ "knit", "big" ] } } }feature { key: "gps" value { float_list { value: [] } } }},features {feature { key: "kw" value { bytes_list { value: [ "emmy" ] } } }feature { key: "dank" value { int64_list { value: [ 42 ] } } }feature { key: "gps" value { } }} ] #相關參數如下: example_names: ["input0", "input1"], features: {"kw": VarLenFeature(tf.string),"dank": VarLenFeature(tf.int64),"gps": VarLenFeature(tf.float32), } #那么有如下輸出: {"kw": SparseTensor(indices=[[0, 0], [0, 1], [1, 0]],values=["knit", "big", "emmy"]shape=[2, 2]),"dank": SparseTensor(indices=[[1, 0]],values=[42],shape=[2, 1]),"gps": SparseTensor(indices=[],values=[],shape=[2, 0]), } ######### #對于兩個樣本的輸出稠密結果情況 [features {feature { key: "age" value { int64_list { value: [ 0 ] } } }feature { key: "gender" value { bytes_list { value: [ "f" ] } } }},features {feature { key: "age" value { int64_list { value: [] } } }feature { key: "gender" value { bytes_list { value: [ "f" ] } } }} ] #我們可以使用以下參數 example_names: ["input0", "input1"], features: {"age": FixedLenFeature([], dtype=tf.int64, default_value=-1),"gender": FixedLenFeature([], dtype=tf.string), } #期望的結果如下 {"age": [[0], [-1]],"gender": [["f"], ["f"]], } ##Example protocol buffer相關使用的例子 #將mnist的數據轉換為TFRecords文件格式 import os import tensorflow as tf from tensorflow.contrib.learn.python.learn.datasets import mnist SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'TRAIN_IMAGES = 'train-images-idx3-ubyte.gz' # MNIST filenames TRAIN_LABELS = 'train-labels-idx1-ubyte.gz' TEST_IMAGES = 't10k-images-idx3-ubyte.gz' TEST_LABELS = 't10k-labels-idx1-ubyte.gz'tf.app.flags.DEFINE_string('directory', '/tmp/data','Directory to download data files and write the ''converted result') tf.app.flags.DEFINE_integer('validation_size', 5000,'Number of examples to separate from the training ''data for the validation set.') FLAGS = tf.app.flags.FLAGSdef _int64_feature(value):return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))def _bytes_feature(value):return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))def convert_to(data_set, name):images = data_set.imageslabels = data_set.labelsnum_examples = data_set.num_examplesif images.shape[0] != num_examples:raise ValueError('Images size %d does not match label size %d.' %(images.shape[0], num_examples))rows = images.shape[1]cols = images.shape[2]depth = images.shape[3]filename = os.path.join(FLAGS.directory, name + '.tfrecords')print('Writing', filename)writer = tf.python_io.TFRecordWriter(filename)for index in range(num_examples):image_raw = images[index].tostring()example = tf.train.Example(features=tf.train.Features(feature={'height': _int64_feature(rows),'width': _int64_feature(cols),'depth': _int64_feature(depth),'label': _int64_feature(int(labels[index])),'image_raw': _bytes_feature(image_raw)}))writer.write(example.SerializeToString())writer.close()def main(argv):# Get the data.data_sets = mnist.read_data_sets(FLAGS.directory,dtype=tf.uint8,reshape=False)# Convert to Examples and write the result to TFRecords.convert_to(data_sets.train, 'train')convert_to(data_sets.validation, 'validation')convert_to(data_sets.test, 'test')if __name__ == '__main__':tf.app.run()





4.1 數據IO {Data IO (Python functions)}

一個TFRecords 文件為一個字符串序列。這種格式并非隨機獲取,它比較適合大規模的數據流,而不太適合需要快速分區或其他非序列獲取方式。

數據IO {Data IO (Python functions)}

操作描述
class tf.python_io.TFRecordWriter一個用于將記錄(records)寫入TFRecords文件的類
tf.python_io.TFRecordWriter.__init__(path, options=None)打開文件路徑,并創建一個TFRecordWriter以供寫入
tf.python_io.TFRecordWriter.write(record)將一個字符串records寫入文件中
tf.python_io.TFRecordWriter.close()關閉文件
tf.python_io.tf_record_iterator(path, options=None)從TFRecords文件中讀取記錄的迭代器

4.2 運行圖(Running Graphs)

會話管理 (Session management)

操作描述
class tf.Session運行TF操作的類,
一個Session對象將操作節點op封裝在一定的環境內運行,
同時tensor對象將被計算求值
tf.Session.__init__(target=”, graph=None, config=None)創建一個新的會話
tf.Session.run(fetches, feed_dict=None,
options=None, run_metadata=None)
運行fetches中的操作節點并求其值
tf.Session.close()關閉會話
tf.Session.graph返回加載值該會話的圖(graph)
tf.Session.as_default()設置該對象為默認會話,并返回一個上下文管理器
tf.Session.reset(target, containers=None, config=None)重設target的資源容器,并關閉所有連接的會話
在0.10版本該功能僅應用在分布會話中
target:為執行引擎所連接的目標,其包含有資源容器,
該資源容器分布在同一個集群的所有works上
class tf.InteractiveSession使用在交互式上下文環境的tf會話,比如shell,ipython
tf.InteractiveSession.close()關閉一個InteractiveSession
tf.get_default_session()返回當前線程的默認會話

tf.Session

#一個簡單的tf.Session例子 # 建立一個graph. a = tf.constant(5.0) b = tf.constant(6.0) c = a * b# 將graph載入到一個會話session中 sess = tf.Session()# 計算tensor `c`. print(sess.run(c)) #一個會話可能會占用一些資源,比如變量、隊列和讀取器(reader)。釋放這些不再使用的資源非常重要。 #使用close()方法關閉會話,或者使用上下文管理器,釋放資源。 # 使用`close()`方法. sess = tf.Session() sess.run(...) sess.close()# 使用上下文管理器 with tf.Session() as sess:sess.run(...)

tf.Session()的變量設置, ConfigProto protocol buffer為會話提供了不同的配置選項。比如,創建一個會話,對設備布局使用軟約束條件,以及對分布

# Launch the graph in a session that allows soft device placement and # logs the placement decisions. sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,log_device_placement=True))

tf.Session.run

a = tf.constant([10, 20])b = tf.constant([1.0, 2.0])# 'fetches' 可以為單個數v = session.run(a)# v is the numpy array [10, 20]# 'fetches' 可以為一個list.v = session.run([a, b])# v a Python list with 2 numpy arrays: the numpy array [10, 20] and the# 1-D array [1.0, 2.0]# 'fetches' 可以是 lists, tuples, namedtuple, dicts中的任意:MyData = collections.namedtuple('MyData', ['a', 'b'])v = session.run({'k1': MyData(a, b), 'k2': [b, a]})# v 為一個dict,并有# v['k1'] is a MyData namedtuple with 'a' the numpy array [10, 20] and# 'b' the numpy array [1.0, 2.0]# v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array# [10, 20].

tf.Session.as_default()
使用關鍵字with指定會話, 可以在會話中執行Operation.run()或Tensor.eval(),以得到運行的tensor結果

c = tf.constant(..) sess = tf.Session()with sess.as_default():assert tf.get_default_session() is sessprint(c.eval())

使用函數tf.get_default_session()來得到當前默認的會話
需要注意的是,退出該as_default上下文管理器時,并沒有關閉該會話(session ),必須明確的關閉會話

c = tf.constant(...) sess = tf.Session() with sess.as_default():print(c.eval()) # ... with sess.as_default():print(c.eval()) #關閉會話 sess.close() #使用 with tf.Session()方式可以創建并自動關閉會話

tf.InteractiveSession

sess = tf.InteractiveSession() a = tf.constant(5.0) b = tf.constant(6.0) c = a * b # 我們直接使用'c.eval()' 而沒有通過'sess' print(c.eval()) sess.close()

以上的例子,在非交互會話的版本中為,

a = tf.constant(5.0) b = tf.constant(6.0) c = a * b with tf.Session():# We can also use 'c.eval()' here.print(c.eval())

ABC

錯誤類 (Error classes)

操作描述
class tf.OpError一個基本的錯誤類型,在當TF執行失敗時候報錯
tf.OpError.op返回執行失敗的操作節點,
有的操作如Send或Recv可能不會返回,那就要用用到node_def方法
tf.OpError.node_def以NodeDef proto形式表示失敗的op
tf.OpError.error_code描述該錯誤的整數錯誤代碼
tf.OpError.message返回錯誤信息
class tf.errors.CancelledError當操作或者階段唄取消時候報錯
class tf.errors.UnknownError未知錯誤類型
class tf.errors.InvalidArgumentError在接收到非法參數時候報錯
class tf.errors.NotFoundError當發現不存在所請求的一個實體時候,比如文件或目錄
class tf.errors.AlreadyExistsError當創建的實體已經存在的時候報錯
class tf.errors.PermissionDeniedError沒有執行權限做某操作的時候報錯
class tf.errors.ResourceExhaustedError資源耗盡時報錯
class tf.errors.FailedPreconditionError系統沒有條件執行某個行為時候報錯
class tf.errors.AbortedError操作中止時報錯,常常發生在并發情形
class tf.errors.OutOfRangeError超出范圍報錯
class tf.errors.UnimplementedError某個操作沒有執行時報錯
class tf.errors.InternalError當系統經歷了一個內部錯誤時報出
class tf.errors.DataLossError當出現不可恢復的錯誤
例如在運行 tf.WholeFileReader.read()讀取整個文件的同時文件被刪減
tf.errors.XXXXX.__init__(node_def, op, message)使用該形式方法創建以上各種錯誤類

----------------------------------------------------------------------------------------------------------------------------------------------------------------------


本文所講的內容主要為以下列表中相關函數。函數training()通過梯度下降法為最小化損失函數增加了相關的優化操作,在訓練過程中,先實例化一個優化函數,比如 tf.train.GradientDescentOptimizer,并基于一定的學習率進行梯度優化訓練:

optimizer = tf.train.GradientDescentOptimizer(learning_rate)

然后,可以設置 一個用于記錄全局訓練步驟的單值。以及使用minimize()操作,該操作不僅可以優化更新訓練的模型參數,也可以為全局步驟(global step)計數。與其他tensorflow操作類似,這些訓練操作都需要在tf.session會話中進行

global_step = tf.Variable(0, name='global_step', trainable=False) train_op = optimizer.minimize(loss, global_step=global_step) 操作組操作
TrainingOptimizers,Gradient Computation,Gradient Clipping,Distributed execution
TestingUnit tests,Utilities,Gradient checking

5、Tensorflow函數

5.1 訓練 (Training)

一個TFRecords 文件為一個字符串序列。這種格式并非隨機獲取,它比較適合大規模的數據流,而不太適合需要快速分區或其他非序列獲取方式。

優化 (Optimizers)

tf中各種優化類提供了為損失函數計算梯度的方法,其中包含比較經典的優化算法,比如GradientDescent 和Adagrad。

??class tf.train.Optimizer

操作描述
class tf.train.Optimizer基本的優化類,該類不常常被直接調用,而較多使用其子類,
比如GradientDescentOptimizer, AdagradOptimizer
或者MomentumOptimizer
tf.train.Optimizer.__init__(use_locking, name)創建一個新的優化器,
該優化器必須被其子類(subclasses)的構造函數調用
tf.train.Optimizer.minimize(loss, global_step=None,
var_list=None, gate_gradients=1,
aggregation_method=None, colocate_gradients_with_ops=False,
name=None, grad_loss=None)
添加操作節點,用于最小化loss,并更新var_list
該函數是簡單的合并了compute_gradients()與apply_gradients()函數
返回為一個優化更新后的var_list,如果global_step非None,該操作還會為global_step做自增操作
tf.train.Optimizer.compute_gradients(loss,var_list=None, gate_gradients=1,
aggregation_method=None,
colocate_gradients_with_ops=False, grad_loss=None)
對var_list中的變量計算loss的梯度
該函數為函數minimize()的第一部分,返回一個以元組(gradient, variable)組成的列表
tf.train.Optimizer.apply_gradients(grads_and_vars, global_step=None, name=None)將計算出的梯度應用到變量上,是函數minimize()的第二部分,返回一個應用指定的梯度的操作Operation,對global_step做自增操作
tf.train.Optimizer.get_name()獲取名稱

? class tf.train.Optimizer
用法

# Create an optimizer with the desired parameters. opt = GradientDescentOptimizer(learning_rate=0.1) # Add Ops to the graph to minimize a cost by updating a list of variables. # "cost" is a Tensor, and the list of variables contains tf.Variable objects. opt_op = opt.minimize(cost, var_list=<list of variables>) # Execute opt_op to do one step of training: opt_op.run()

??在使用它們之前處理梯度
使用minimize()操作,該操作不僅可以計算出梯度,而且還可以將梯度作用在變量上。如果想在使用它們之前處理梯度,可以按照以下三步驟使用optimizer :

1、使用函數compute_gradients()計算梯度 2、按照自己的愿望處理梯度 3、使用函數apply_gradients()應用處理過后的梯度

例如:

# 創建一個optimizer. opt = GradientDescentOptimizer(learning_rate=0.1)# 計算<list of variables>相關的梯度 grads_and_vars = opt.compute_gradients(loss, <list of variables>)# grads_and_vars為tuples (gradient, variable)組成的列表。 #對梯度進行想要的處理,比如cap處理 capped_grads_and_vars = [(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars]# 令optimizer運用capped的梯度(gradients) opt.apply_gradients(capped_grads_and_vars)

??選通梯度(Gating Gradients)
函數minimize() 與compute_gradients()都含有一個參數gate_gradient,用于控制在應用這些梯度時并行化的程度。

其值可以取:GATE_NONE, GATE_OP 或 GATE_GRAPH
GATE_NONE : 并行地計算和應用梯度。提供最大化的并行執行,但是會導致有的數據結果沒有再現性。比如兩個matmul操作的梯度依賴輸入值,使用GATE_NONE可能會出現有一個梯度在其他梯度之前便應用到某個輸入中,導致出現不可再現的(non-reproducible)結果
GATE_OP: 對于每個操作Op,確保每一個梯度在使用之前都已經計算完成。這種做法防止了那些具有多個輸入,并且梯度計算依賴輸入情形中,多輸入Ops之間的競爭情況出現。
GATE_GRAPH: 確保所有的變量對應的所有梯度在他們任何一個被使用前計算完成。該方式具有最低級別的并行化程度,但是對于想要在應用它們任何一個之前處理完所有的梯度計算時很有幫助的。


Slots

一些optimizer的之類,比如 MomentumOptimizer 和 AdagradOptimizer 分配和管理著額外的用于訓練的變量。這些變量稱之為’Slots’,Slots有相應的名稱,可以向optimizer訪問的slots名稱。有助于在log debug一個訓練算法以及報告slots狀態

操作描述
tf.train.Optimizer.get_slot_names()返回一個由Optimizer所創建的slots的名稱列表
tf.train.Optimizer.get_slot(var, name)返回一個name所對應的slot,name是由Optimizer為var所創建
var為用于傳入 minimize() 或 apply_gradients()的變量
class tf.train.GradientDescentOptimizer使用梯度下降算法的Optimizer
tf.train.GradientDescentOptimizer.__init__(learning_rate,
use_locking=False, name=’GradientDescent’)
構建一個新的梯度下降優化器(Optimizer)
class tf.train.AdadeltaOptimizer使用Adadelta算法的Optimizer
tf.train.AdadeltaOptimizer.__init__(learning_rate=0.001,
rho=0.95, epsilon=1e-08,
use_locking=False, name=’Adadelta’)
創建Adadelta優化器
class tf.train.AdagradOptimizer使用Adagrad算法的Optimizer
tf.train.AdagradOptimizer.__init__(learning_rate,
initial_accumulator_value=0.1,
use_locking=False, name=’Adagrad’)
創建Adagrad優化器
class tf.train.MomentumOptimizer使用Momentum算法的Optimizer
tf.train.MomentumOptimizer.__init__(learning_rate,
momentum, use_locking=False,
name=’Momentum’, use_nesterov=False)
創建momentum優化器
momentum:動量,一個tensor或者浮點值
class tf.train.AdamOptimizer使用Adam 算法的Optimizer
tf.train.AdamOptimizer.__init__(learning_rate=0.001,
beta1=0.9, beta2=0.999, epsilon=1e-08,
use_locking=False, name=’Adam’)
創建Adam優化器
class tf.train.FtrlOptimizer使用FTRL 算法的Optimizer
tf.train.FtrlOptimizer.__init__(learning_rate,
learning_rate_power=-0.5,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0,
use_locking=False, name=’Ftrl’)
創建FTRL算法優化器
class tf.train.RMSPropOptimizer使用RMSProp算法的Optimizer
tf.train.RMSPropOptimizer.__init__(learning_rate,
decay=0.9, momentum=0.0, epsilon=1e-10,
use_locking=False, name=’RMSProp’)
創建RMSProp算法優化器

? tf.train.AdamOptimizer
Adam 的基本運行方式,首先初始化:

m_0 <- 0 (Initialize initial 1st moment vector) v_0 <- 0 (Initialize initial 2nd moment vector) t <- 0 (Initialize timestep)

在論文中的 section2 的末尾所描述了更新規則,該規則使用梯度g來更新變量:

t <- t + 1 lr_t <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t)m_t <- beta1 * m_{t-1} + (1 - beta1) * g v_t <- beta2 * v_{t-1} + (1 - beta2) * g * g variable <- variable - lr_t * m_t / (sqrt(v_t) + epsilon)

其中epsilon 的默認值1e-8可能對于大多數情況都不是一個合適的值。例如,當在ImageNet上訓練一個 Inception network時比較好的選擇為1.0或者0.1。
需要注意的是,在稠密數據中即便g為0時, m_t, v_t 以及variable都將會更新。而在稀疏數據中,m_t, v_t 以及variable不被更新且值為零。

梯度計算與截斷(Gradient Computation and Clipping)

TensorFlow 提供了計算給定tf計算圖的求導函數,并在圖的基礎上增加節點。優化器(optimizer )類可以自動的計算網絡圖的導數,但是優化器中的創建器(creators )或者專業的人員可以通過本節所述的函數調用更底層的方法。

操作描述
tf.gradients(ys, xs, grad_ys=None, name=’gradients’,
colocate_gradients_with_ops=False, gate_gradients=False,
aggregation_method=None)
構建一個符號函數,計算ys關于xs中x的偏導的和,
返回xs中每個x對應的sum(dy/dx)
tf.stop_gradient(input, name=None)停止計算梯度,
在EM算法、Boltzmann機等可能會使用到
tf.clip_by_value(t, clip_value_min, clip_value_max, name=None)基于定義的min與max對tesor數據進行截斷操作,
目的是為了應對梯度爆發或者梯度消失的情況
tf.clip_by_norm(t, clip_norm, axes=None, name=None)使用L2范式標準化tensor最大值為clip_norm
返回 t * clip_norm / l2norm(t)
tf.clip_by_average_norm(t, clip_norm, name=None)使用平均L2范式規范tensor數據t,
并以clip_norm為最大值
返回 t * clip_norm / l2norm_avg(t)
tf.clip_by_global_norm(t_list,
clip_norm, use_norm=None, name=None)
返回t_list[i] * clip_norm / max(global_norm, clip_norm)
其中global_norm = sqrt(sum([l2norm(t)**2 for t in t_list]))
tf.global_norm(t_list, name=None)返回global_norm = sqrt(sum([l2norm(t)**2 for t in t_list]))


退化學習率(Decaying the learning rate)

操作描述
tf.train.exponential_decay(learning_rate, global_step,
decay_steps, decay_rate, staircase=False, name=None)
對學習率進行指數衰退

? tf.train.exponential_decay

#該函數返回以下結果 decayed_learning_rate = learning_rate *decay_rate ^ (global_step / decay_steps) ##例: 以0.96為基數,每100000 步進行一次學習率的衰退 global_step = tf.Variable(0, trainable=False) starter_learning_rate = 0.1 learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,100000, 0.96, staircase=True) # Passing global_step to minimize() will increment it at each step. learning_step = (tf.train.GradientDescentOptimizer(learning_rate).minimize(...my loss..., global_step=global_step) )


移動平均(Moving Averages)

一些訓練優化算法,比如GradientDescent 和Momentum 在優化過程中便可以使用到移動平均方法。使用移動平均常??梢暂^明顯地改善結果。

操作描述
class tf.train.ExponentialMovingAverage將指數衰退加入到移動平均中
tf.train.ExponentialMovingAverage.apply(var_list=None)對var_list變量保持移動平均
tf.train.ExponentialMovingAverage.average_name(var)返回var均值的變量名稱
tf.train.ExponentialMovingAverage.average(var)返回var均值變量
tf.train.ExponentialMovingAverage.variables_to_restore(moving_avg_variables=None)返回用于保存的變量名稱的映射

? tf.train.ExponentialMovingAverage

# Example usage when creating a training model: # Create variables. var0 = tf.Variable(...) var1 = tf.Variable(...) # ... use the variables to build a training model... ... # Create an op that applies the optimizer. This is what we usually # would use as a training op. opt_op = opt.minimize(my_loss, [var0, var1])# Create an ExponentialMovingAverage object ema = tf.train.ExponentialMovingAverage(decay=0.9999)# Create the shadow variables, and add ops to maintain moving averages # of var0 and var1. maintain_averages_op = ema.apply([var0, var1])# Create an op that will update the moving averages after each training # step. This is what we will use in place of the usual training op. with tf.control_dependencies([opt_op]):training_op = tf.group(maintain_averages_op)...train the model by running training_op...#Example of restoring the shadow variable values: # Create a Saver that loads variables from their saved shadow values. shadow_var0_name = ema.average_name(var0) shadow_var1_name = ema.average_name(var1) saver = tf.train.Saver({shadow_var0_name: var0, shadow_var1_name: var1}) saver.restore(...checkpoint filename...) # var0 and var1 now hold the moving average values

? tf.train.ExponentialMovingAverage.variables_to_restore

variables_to_restore = ema.variables_to_restore()saver = tf.train.Saver(variables_to_restore)


協調器和隊列運行器(Coordinator and QueueRunner)

查看queue中,queue相關的內容,了解tensorflow中隊列的運行方式。

操作描述
class tf.train.Coordinator線程的協調器
tf.train.Coordinator.clear_stop()清除停止標記
tf.train.Coordinator.join(threads=None, stop_grace_period_secs=120)等待線程終止
threads:一個threading.Threads的列表,啟動的線程,將額外加入到registered的線程中
tf.train.Coordinator.register_thread(thread)Register一個用于join的線程
tf.train.Coordinator.request_stop(ex=None)請求線程結束
tf.train.Coordinator.should_stop()檢查是否被請求停止
tf.train.Coordinator.stop_on_exception()上下文管理器,當一個例外出現時請求停止
tf.train.Coordinator.wait_for_stop(timeout=None)等待Coordinator提示停止進程
class tf.train.QueueRunner持有一個隊列的入列操作列表,用于線程中運行
queue:一個隊列
enqueue_ops: 用于線程中運行的入列操作列表
tf.train.QueueRunner.create_threads(sess,
coord=None, daemon=False, start=False)
創建運行入列操作的線程,返回一個線程列表
tf.train.QueueRunner.from_proto(queue_runner_def)返回由queue_runner_def創建的QueueRunner對象
tf.train.add_queue_runner(qr, collection=’queue_runners’)增加一個QueueRunner到graph的收集器(collection )中
tf.train.start_queue_runners(sess=None, coord=None, daemon=True, start=True, collection=’queue_runners’)啟動所有graph收集到的隊列運行器(queue runners)

? class tf.train.Coordinator

#Coordinator的使用,用于多線程的協調 try:...coord = Coordinator()# Start a number of threads, passing the coordinator to each of them....start thread 1...(coord, ...)...start thread N...(coord, ...)# Wait for all the threads to terminate, give them 10s grace periodcoord.join(threads, stop_grace_period_secs=10) except RuntimeException:...one of the threads took more than 10s to stop after request_stop()...was called. except Exception:...exception that was passed to coord.request_stop()

? tf.train.Coordinator.stop_on_exception()

with coord.stop_on_exception():# Any exception raised in the body of the with# clause is reported to the coordinator before terminating# the execution of the body....body... #等價于 try:...body... exception Exception as ex:coord.request_stop(ex)


布執行(Distributed execution)

可以閱讀TensorFlow的分布式學習框架簡介 查看更多tensorflow分布式細節。

操作描述
class tf.train.Server一個進程內的tensorflow服務,用于分布式訓練
tf.train.Server.init(server_or_cluster_def,
job_name=None, task_index=None, protocol=None,
config=None, start=True)
創建一個新的服務,其中job_name, task_index,
和protocol為可選參數,
優先級高于server_or_cluster_def中相關信息
server_or_cluster_def : 為一個tf.train.ServerDef
或 tf.train.ClusterDef 協議(protocol)的buffer,
或者一個tf.train.ClusterSpec對象
tf.train.Server.create_local_server(config=None, start=True)創建一個新的運行在本地主機的單進程集群
tf.train.Server.target返回tf.Session所連接的目標服務器
tf.train.Server.server_def返回該服務的tf.train.ServerDef
tf.train.Server.start()開啟服務
tf.train.Server.join()阻塞直到服務已經關閉
#?
class tf.train.Supervisor一個訓練輔助器,用于checkpoints模型以及計算的summaries。該監視器只是一個小的外殼(wrapper),用于Coordinator, a Saver, 和a SessionManager周圍
tf.train.Supervisor.__init__(graph=None, ready_op=0, is_chief=True, init_op=0, init_feed_dict=None, local_init_op=0, logdir=None,
summary_op=0, saver=0, global_step=0,
save_summaries_secs=120, save_model_secs=600,
recovery_wait_secs=30, stop_grace_secs=120,
checkpoint_basename=’model.ckpt’, session_manager=None, summary_writer=0, init_fn=None)
創建一個監視器Supervisor
tf.train.Supervisor.managed_session(master=”, config=None, start_standard_services=True, close_summary_writer=True)返回一個管路session的上下文管理器
tf.train.Supervisor.prepare_or_wait_for_session(master=”, config=None, wait_for_checkpoint=False, max_wait_secs=7200, start_standard_services=True)確保model已經準備好
tf.train.Supervisor.start_standard_services(sess)為sess啟動一個標準的服務
tf.train.Supervisor.start_queue_runners(sess, queue_runners=None)為QueueRunners啟動一個線程,queue_runners為一個QueueRunners列表
tf.train.Supervisor.summary_computed(sess, summary, global_step=None)指示計算的summary
tf.train.Supervisor.stop(threads=None, close_summary_writer=True)停止服務以及協調器(coordinator),并沒有關閉session
tf.train.Supervisor.request_stop(ex=None)參考Coordinator.request_stop()
tf.train.Supervisor.should_stop()參考Coordinator.should_stop()
tf.train.Supervisor.stop_on_exception()參考 Coordinator.stop_on_exception()
tf.train.Supervisor.Loop(timer_interval_secs, target, args=None, kwargs=None)開啟一個循環器線程用于調用一個函數
每經過timer_interval_secs秒執行,target(*args, **kwargs)
tf.train.Supervisor.coord返回監督器(Supervisor)使用的協調器(Coordinator )
#?
class tf.train.SessionManager訓練的輔助器,用于從checkpoint恢復數據以及創建一個session
tf.train.SessionManager.__init__(local_init_op=None, ready_op=None, graph=None, recovery_wait_secs=30)創建一個SessionManager
tf.train.SessionManager.prepare_session(master, init_op=None, saver=None, checkpoint_dir=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, init_feed_dict=None, init_fn=None)創建一個session,并確保model可以被使用
tf.train.SessionManager.recover_session(master, saver=None, checkpoint_dir=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None)創建一個session,如果可以的話,使用恢復方法創建
tf.train.SessionManager.wait_for_session(master, config=None, max_wait_secs=inf)創建一個session,并等待model準備完成
#?
class tf.train.ClusterSpec將一個集群表示為一系列“tasks”,并整合至“jobs”中
tf.train.ClusterSpec.as_cluster_def()返回該cluster中一個tf.train.ClusterDef協議的buffer
tf.train.ClusterSpec.as_dict()返回一個字典,由job名稱對應于網絡地址
tf.train.ClusterSpec.job_tasks(job_name)返回一個給定的job對應的task列表
tf.train.ClusterSpec.jobs返回該cluster的job名稱列表
tf.train.replica_device_setter(ps_tasks=0, ps_device=’/job:ps’, worker_device=’/job:worker’, merge_devices=True, cluster=None, ps_ops=None)返回一個設備函數(device function),以在建立一個副本graph的時候使用,設備函數(device function)用在with tf.device(device_function)中

? tf.train.Server

server = tf.train.Server(...) with tf.Session(server.target):# ...

? tf.train.Supervisor
相關參數:
ready_op : 一維 字符串 tensor。該tensor是用過監視器在prepare_or_wait_for_session()計算,檢查model是否準備好可以使用。如果準備好,將返回一個空陣列,如果為None,該model沒有被檢查。
is_chief : 如果為True,創建一個主監視器用于負責初始化與模型的恢復,若為False,則依賴主監視器。
init_op : 一個操作,用于模型不能恢復時的初始化操作。默認初始化所有操作
local_init_op : 可被所有監視器運行的初始化操作。
logdir : 設置log目錄
summary_op : 一個操作(Operation ),返回Summary 和事件logs,需要設置 logdir
saver : 一個Saver對象
save_summaries_secs : 保存summaries的間隔秒數
save_model_secs : 保存model的間隔秒數
checkpoint_basename : checkpoint保存的基本名稱

  • 使用在單進程中
with tf.Graph().as_default():...add operations to the graph...# Create a Supervisor that will checkpoint the model in '/tmp/mydir'.sv = Supervisor(logdir='/tmp/mydir')# Get a TensorFlow session managed by the supervisor.with sv.managed_session(FLAGS.master) as sess:# Use the session to train the graph.while not sv.should_stop():sess.run(<my_train_op>) # 在上下文管理器with sv.managed_session()內,所有在graph的變量都被初始化。 # 或者說,一些服務器checkpoint相應模型并增加summaries至事件log中。 # 如果有例外發生,should_stop()將返回True
  • 使用在多副本運行情況中
    要使用副本訓練已經部署在集群上的相同程序,必須指定其中一個task為主要,該task處理 initialization, checkpoints, summaries, 和recovery相關事物。其他task依賴該task。
# Choose a task as the chief. This could be based on server_def.task_index, # or job_def.name, or job_def.tasks. It's entirely up to the end user. # But there can be only one *chief*. is_chief = (server_def.task_index == 0) server = tf.train.Server(server_def)with tf.Graph().as_default():...add operations to the graph...# Create a Supervisor that uses log directory on a shared file system.# Indicate if you are the 'chief'sv = Supervisor(logdir='/shared_directory/...', is_chief=is_chief)# Get a Session in a TensorFlow server on the cluster.with sv.managed_session(server.target) as sess:# Use the session to train the graph.while not sv.should_stop():sess.run(<my_train_op>)

如果有task崩潰或重啟,managed_session() 將檢查是否Model被初始化。如果已經初始化,它只需要創建一個session并將其返回至正在訓練的正常代碼中。如果model需要被初始化,主task將對它進行重新初始化,而其他task將等待模型初始化完成。
注意:該程序方法一樣適用于單進程的work,該單進程標注自己為主要的便行

? supervisor中master的字符串形式
無論運行在本機或者集群上,都可以使用以下值設定master flag:

  • 定義為 ” ,要求一個進程內且沒有使用RPC的session
  • 定義為 ‘local’,要求一個使用基于RPC的主服務接口(“Master interface” )的session來運行tensorflow程序。更多細節可以查看 tf.train.Server.create_local_server()相關內容。
  • 定義為 ‘grpc://hostname:port’,要求一個指定的RPC接口的session,同時運行內部進程的master接入遠程的tensorflow workers??捎胹erver.target返回該形式

? supervisor高級用法

  • 啟動額外的服務
    managed_session()啟動了 Checkpoint 和Summary服務。如果需要運行更多的服務,可以在managed_session()控制的模塊中啟動他們。
#例如: 開啟一個線程用于打印loss. 設置每60秒該線程運行一次,我們使用sv.loop()...sv = Supervisor(logdir='/tmp/mydir')with sv.managed_session(FLAGS.master) as sess:sv.loop(60, print_loss, (sess))while not sv.should_stop():sess.run(my_train_op)
  • 啟動更少的的服務
    managed_session() 啟動了 “summary” 和 “checkpoint” 線程,這些線程通過構建器或者監督器默認自動創建了summary_op 和saver操作。如果想運行自己的 summary 和checkpointing方法,關閉這些服務,通過傳遞None值給summary_op 和saver參數。
在chief中每100個step,創建summaries# Create a Supervisor with no automatic summaries.sv = Supervisor(logdir='/tmp/mydir', is_chief=is_chief, summary_op=None)# As summary_op was None, managed_session() does not start the# summary thread.with sv.managed_session(FLAGS.master) as sess:for step in xrange(1000000):if sv.should_stop():breakif is_chief and step % 100 == 0:# Create the summary every 100 chief steps.sv.summary_computed(sess, sess.run(my_summary_op))else:# Train normallysess.run(my_train_op)

? tf.train.Supervisor.managed_session

def train():sv = tf.train.Supervisor(...)with sv.managed_session(<master>) as sess:for step in xrange(..):if sv.should_stop():breaksess.run(<my training op>)...do other things needed at each training step...
  • 1

? tf.train.SessionManager

with tf.Graph().as_default():...add operations to the graph...# Create a SessionManager that will checkpoint the model in '/tmp/mydir'.sm = SessionManager()sess = sm.prepare_session(master, init_op, saver, checkpoint_dir)# Use the session to train the graph.while True:sess.run(<my_train_op>) #其中prepare_session()初始化和恢復一個模型參數。 #另一個進程將等待model準備完成,代碼如下 with tf.Graph().as_default():...add operations to the graph...# Create a SessionManager that will wait for the model to become ready.sm = SessionManager()sess = sm.wait_for_session(master)# Use the session to train the graph.while True:sess.run(<my_train_op>) #wait_for_session()等待一個model被其他進程初始化

? tf.train.ClusterSpec
一個tf.train.ClusterSpec表示一系列的進程,這些進程都參與分布式tensorflow的計算。每一個 tf.train.Server都在一個獨有的集群中構建。
創建一個具有兩個jobs及其5個tasks的集群們需要定義從job名稱列表到網絡地址列表之間的映射。

cluster = tf.train.ClusterSpec({"worker": ["worker0.example.com:2222","worker1.example.com:2222","worker2.example.com:2222"],"ps": ["ps0.example.com:2222","ps1.example.com:2222"]})
  • 1

? tf.train.replica_device_setter

# To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker # jobs on hosts worker0, worker1 and worker2. cluster_spec = {"ps": ["ps0:2222", "ps1:2222"],"worker": ["worker0:2222", "worker1:2222", "worker2:2222"]} with tf.device(tf.replica_device_setter(cluster=cluster_spec)):# Build your graphv1 = tf.Variable(...) # assigned to /job:ps/task:0v2 = tf.Variable(...) # assigned to /job:ps/task:1v3 = tf.Variable(...) # assigned to /job:ps/task:0 # Run compute


匯總操作(Summary Operations)

我們可以在一個session中獲取summary操作的輸出,并將其傳輸到SummaryWriter以添加至一個事件記錄文件中。

操作描述
tf.scalar_summary(tags, values, collections=None, name=None)輸出一個標量值的summary協議buffer
tag的shape需要與values的相同,用來做summaries的tags,為字符串
tf.image_summary(tag, tensor, max_images=3, collections=None, name=None)輸出一個圖像tensor的summary協議buffer
tf.audio_summary(tag, tensor, sample_rate, max_outputs=3, collections=None, name=None)輸出一個音頻tensor的summary協議buffer
tf.histogram_summary(tag, values, collections=None, name=None)輸出一個直方圖的summary協議buffer
tf.nn.zero_fraction(value, name=None)返回0在value中的小數比例
tf.merge_summary(inputs, collections=None, name=None)合并summary
tf.merge_all_summaries(key=’summaries’)合并在默認graph中手機的summaries

??將記錄匯總寫入文件中(Adding Summaries to Event Files)

操作描述
class tf.train.SummaryWriter將summary協議buffer寫入事件文件中
tf.train.SummaryWriter.__init__(logdir, graph=None, max_queue=10, flush_secs=120, graph_def=None)創建一個SummaryWriter實例以及新建一個事件文件
tf.train.SummaryWriter.add_summary(summary, global_step=None)將一個summary添加到事件文件中
tf.train.SummaryWriter.add_session_log(session_log, global_step=None)添加SessionLog到一個事件文件中
tf.train.SummaryWriter.add_event(event)添加一個事件到事件文件中
tf.train.SummaryWriter.add_graph(graph, global_step=None, graph_def=None)添加一個Graph到時間文件中
tf.train.SummaryWriter.add_run_metadata(run_metadata, tag, global_step=None)為一個單一的session.run()調用添加一個元數據信息
tf.train.SummaryWriter.flush()刷新時間文件到硬盤中
tf.train.SummaryWriter.close()將事件問價寫入硬盤中并關閉該文件
tf.train.summary_iterator(path)一個用于從時間文件中讀取時間協議buffer的迭代器

? tf.train.SummaryWriter
創建一個SummaryWriter 和事件文件。如果我們傳遞一個Graph進入該構建器中,它將被添加到事件文件當中,這一點與使用add_graph()具有相同功能。
TensorBoard 將從事件文件中提取該graph,并將其顯示。所以我們能直觀地看到我們建立的graph。我們通常從我們啟動的session中傳遞graph:

...create a graph... # Launch the graph in a session. sess = tf.Session() # Create a summary writer, add the 'graph' to the event file. writer = tf.train.SummaryWriter(<some-directory>, sess.graph)

? tf.train.summary_iterator

#打印時間文件中的內容 for e in tf.train.summary_iterator(path to events file):print(e)#打印指定的summary值 # This example supposes that the events file contains summaries with a # summary value tag 'loss'. These could have been added by calling # `add_summary()`, passing the output of a scalar summary op created with # with: `tf.scalar_summary(['loss'], loss_tensor)`. for e in tf.train.summary_iterator(path to events file):for v in e.summary.value:if v.tag == 'loss':print(v.simple_value)
  • 1


訓練的通用函數及其他(Training utilities)

操作描述
tf.train.global_step(sess, global_step_tensor)一個用于獲取全局step的小輔助器
tf.train.write_graph(graph_def, logdir, name, as_text=True)將一個graph proto寫入一個文件中
#?
?:—
class tf.train.LooperThread可重復地執行代碼的線程
tf.train.LooperThread.init(coord, timer_interval_secs, target=None, args=None, kwargs=None)創建一個LooperThread
tf.train.LooperThread.is_alive()返回是否該線程是活躍的
tf.train.LooperThread.join(timeout=None)等待線程結束
tf.train.LooperThread.loop(coord, timer_interval_secs, target, args=None, kwargs=None)啟動一個LooperThread,用于周期地調用某個函數
調用函數target(args)
tf.py_func(func, inp, Tout, stateful=True, name=None)將python函數包裝成tf中操作節點

? tf.train.global_step

# Creates a variable to hold the global_step. global_step_tensor = tf.Variable(10, trainable=False, name='global_step') # Creates a session. sess = tf.Session() # Initializes the variable. sess.run(global_step_tensor.initializer) print('global_step: %s' % tf.train.global_step(sess, global_step_tensor))global_step: 10

? tf.train.write_graph

v = tf.Variable(0, name='my_variable') sess = tf.Session() tf.train.write_graph(sess.graph_def, '/tmp/my-model', 'train.pbtxt')

? tf.py_func

#tf.py_func(func, inp, Tout, stateful=True, name=None) #func:為一個python函數 #inp:為輸入函數的參數,Tensor列表 #Tout: 指定func返回的輸出的數據類型,是一個列表 def my_func(x):# x will be a numpy array with the contents of the placeholder belowreturn np.sinh(x) inp = tf.placeholder(tf.float32, [...]) y = py_func(my_func, [inp], [tf.float32])

5.2 測試 (Testing)

TensorFlow 提供了一個方便的繼承unittest.TestCase類的方法,該類增加有關TensorFlow 測試的方法。如下例子:

import tensorflow as tfclass SquareTest(tf.test.TestCase):def testSquare(self):with self.test_session():x = tf.square([2, 3])self.assertAllEqual(x.eval(), [4, 9])if __name__ == '__main__':tf.test.main()


共用(Utilities)

操作描述
tf.test.main()運行所有的單元測試
tf.test.assert_equal_graph_def(actual, expected)斷言 兩個GraphDefs 是否幾乎一樣
tf.test.get_temp_dir()返回測試期間使用的臨時目錄
tf.test.is_built_with_cuda()返回是否Tensorflow支持CUDA(GPU)的build


梯度檢查(Gradient checking)

可對比compute_gradient 和compute_gradient_error函數的用法

操作描述
tf.test.compute_gradient(x, x_shape, y, y_shape, x_init_value=None, delta=0.001, init_targets=None)計算并返回理論的和數值的Jacobian矩陣
tf.test.compute_gradient_error(x, x_shape, y, y_shape, x_init_value=None, delta=0.001, init_targets=None)計算梯度的error。在計算所得的與數值估計的Jacobian中 為dy/dx計算最大的error


--------------------------------------------------------------------------------------------------------------------

參考文獻

Tensorflow一些常用基本概念與函數 http://www.cnblogs.com/wuzhitj/archive/2017/03.html

Tensorflow筆記:常用函數說明: http://blog.csdn.net/u014595019/article/details/52805444

Tensorflow一些常用基本概念與函數(1) http://blog.csdn.net/lenbow/article/details/52152766
Tensorflow一些常用基本概念與函數(2) http://blog.csdn.net/lenbow/article/details/52181159
Tensorflow一些常用基本概念與函數(3) http://blog.csdn.net/lenbow/article/details/52213105

Tensorflow一些常用基本概念與函數(4)http://blog.csdn.net/lenbow/article/details/52218551


創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Tensorflow一些常用基本概念与函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。