Tensorflow的基本概念與常用函數


Tensorflow一些常用基本概念與函數(一)

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。下面是一些重要的操作/核:
操作組 操作
Maths Add, Sub, Mul, Div, Exp, Log, Greater, Less, Equal
Array Concat, Slice, Split, Constant, Rank, Shape, Shuffle
Matrix MatMul, MatrixInverse, MatrixDeterminant
Neuronal Network SoftMax, Sigmoid, ReLU, Convolution2D, MaxPool
Checkpointing Save, Restore
Queues and syncronizations Enqueue, Dequeue, MutexAcquire, MutexRelease
Flow control Merge, 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.gather
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同

對於有巨大量的多分類與多標簽模型,如果使用全連接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文件名列表和時間戳

Tensorflow一些常用基本概念與函數(二)

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]):
# `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之后再執行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.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.dtype tensor中數據類型
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)

 

 



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)

 

 


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.FLAGS def _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.images labels = data_set.labels num_examples = data_set.num_examples if 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() 

 

 


隊列(Queues)

tensorflow提供了幾個隊列應用,用來將tf計算圖與tensors的階段流水組織到一起。隊列是使用tensorflow計算的一個強大的機制,正如其他Tensorflow的元素一樣,一個隊列也是tf圖中的一個節點(node),它是一個有狀態的node,就像一個變量:其他節點可以改變其內容。 
我們來看一個簡單的例子,如下gif圖,我們將創建一個先入先出隊列(FIFOQueue)並且將值全設為0,然后我們構建一個圖以獲取隊列出來的元素,對該元素加1操作,並將結果再放入隊列末尾。漸漸地,隊列中的數字便增加。 
這里寫圖片描述

操作 描述
class tf.QueueBase 基本的隊列應用類.隊列(queue)是一種數據結構,
該結構通過多個步驟存儲tensors,
並且對tensors進行入列(enqueue)與出列(dequeue)操作
tf.QueueBase.enqueue(vals, name=None) 將一個元素編入該隊列中。如果在執行該操作時隊列已滿,
那么將會阻塞直到元素編入隊列之中
tf.QueueBase.enqueue_many(vals, name=None) 將零個或多個元素編入該隊列中
tf.QueueBase.dequeue(name=None) 將元素從隊列中移出。如果在執行該操作時隊列已空,
那么將會阻塞直到元素出列,返回出列的tensors的tuple
tf.QueueBase.dequeue_many(n, name=None) 將一個或多個元素從隊列中移出
tf.QueueBase.size(name=None) 計算隊列中的元素個數
tf.QueueBase.close
(cancel_pending_enqueues=False, name=None)
關閉該隊列
f.QueueBase.dequeue_up_to(n, name=None) 從該隊列中移出n個元素並將之連接
tf.QueueBase.dtypes 列出組成元素的數據類型
tf.QueueBase.from_list(index, queues) 根據queues[index]的參考隊列創建一個隊列
tf.QueueBase.name 返回最隊列下面元素的名稱
tf.QueueBase.names 返回隊列每一個組成部分的名稱
class tf.FIFOQueue 在出列時依照先入先出順序,其他方法與tf.QueueBase雷同
class tf.PaddingFIFOQueue 一個FIFOQueue ,同時根據padding支持batching變長的tensor
class tf.RandomShuffleQueue 該隊列將隨機元素出列,其他方法與tf.QueueBase雷同

文件系統的處理(Dealing with the filesystem)

操作 描述
tf.matching_files(pattern, name=None) 返回與pattern匹配模式的文件名稱
tf.read_file(filename, name=None) 讀取並輸出輸入文件的整個內容

輸入管道(Input pipeline)

用於設置輸入預取數的管道TF函數,函數 “producer”添加一個隊列至圖中,同時一個相應用於運行隊列中子圖(subgraph)的QueueRunner

操作 描述
tf.train.match_filenames_once(pattern, name=None) 保存與pattern的文件列表
tf.train.limit_epochs(tensor, num_epochs=None, name=None) 返回一個num_epochs次數,然后報告OutOfRange錯誤
tf.train.input_producer(input_tensor, element_shape=None, 
num_epochs=None, shuffle=True, seed=None, capacity=32, 
shared_name=None, summary_name=None, name=None)
為一個輸入管道輸出input_tensor中的多行至一個隊列中
tf.train.range_input_producer(limit, num_epochs=None, 
shuffle=True, seed=None, capacity=32, 
shared_name=None, name=None)
產生一個從1至limit-1的整數至隊列中
tf.train.slice_input_producer(tensor_list, num_epochs=None, 
shuffle=True, seed=None, capacity=32, 
shared_name=None, name=None)
對tensor_list中的每一個tensor切片
tf.train.string_input_producer(string_tensor, num_epochs=None,
shuffle=True, seed=None, capacity=32, 
shared_name=None, name=None)
為一個輸入管道輸出一組字符串(比如文件名)至隊列中

在輸入管道末端批量打包(Batching at the end of an input pipeline)

該相關函數增添一個隊列至圖中以將數據一樣本打包為batch。它們也會添加 一個QueueRunner,以便執行的已經被填滿隊列的子圖

操作 描述
tf.train.batch(tensors, batch_size, num_threads=1,
capacity=32, enqueue_many=False, shapes=None, 
dynamic_pad=False, allow_smaller_final_batch=False, 
shared_name=None, name=None)
在輸入的tensors中創建一些tensor數據格式的batch,
若輸入為shape[*, x, y, z],那么輸出則為[batch_size, x, y, z]
返回一個列表或者一個具有與輸入tensors相同類型tensors的字典
tf.train.batch_join(tensors_list, batch_size, 
capacity=32, enqueue_many=False, shapes=None, 
dynamic_pad=False, allow_smaller_final_batch=False, 
shared_name=None, name=None)
將一個tensors的列表添加至一個隊列中以創建樣本的batches
len(tensors_list)個線程將啟動,
線程i將tensors_list[i]的tensors入列
tensors_list[i1][j]與tensors_list[i2][j]有相同的類型和shape
tf.train.shuffle_batch(tensors, batch_size, capacity, 
min_after_dequeue, num_threads=1, seed=None, 
enqueue_many=False, shapes=None, 
allow_smaller_final_batch=False,
shared_name=None, name=None)
使用隨機亂序的方法創建batches
tensors:用於入列的一個list或者dict
capacity:一個整數,表示隊列中元素最大數目
tf.train.shuffle_batch_join(tensors_list, batch_size, 
capacity, min_after_dequeue, seed=None, 
enqueue_many=False, shapes=None, 
allow_smaller_final_batch=False, 
shared_name=None, name=None)
隨機亂序的tensors創建batches,
其中tensors_list參數為tensors元組或tensors字典的列表
len(tensors_list)個線程將啟動,
線程i將tensors_list[i]的tensors入列
tensors_list[i1][j]與tensors_list[i2][j]有相同的類型和shape
# 一個簡單例子,使用tf.train.shuffle_batch創建一個具有32張圖像和32個標簽的batches. image_batch, label_batch = tf.train.shuffle_batch( [single_image, single_label], batch_size=32, num_threads=4, capacity=50000, min_after_dequeue=10000) 

 

 

#Batching函數相關例子,以函數tf.train.shuffle_batch為例 #為training, evaluation等操作將樣本batching,以下代碼使用隨機順序打包樣本 def read_my_file_format(filename_queue): reader = tf.SomeReader() key, record_string = reader.read(filename_queue) example, label = tf.some_decoder(record_string) processed_example = some_processing(example) return processed_example, label def input_pipeline(filenames, batch_size, num_epochs=None): filename_queue = tf.train.string_input_producer( filenames, num_epochs=num_epochs, shuffle=True) example, label = read_my_file_format(filename_queue) # min_after_dequeue defines how big a buffer we will randomly sample # from -- bigger means better shuffling but slower start up and more # memory used. # capacity must be larger than min_after_dequeue and the amount larger # determines the maximum we will prefetch. Recommendation: # min_after_dequeue + (num_threads + a small safety margin) * batch_size min_after_dequeue = 10000 capacity = min_after_dequeue + 3 * batch_size example_batch, label_batch = tf.train.shuffle_batch( [example, label], batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue) return example_batch, label_batch

 

 

#如果需要跟多的並行或文件之間的樣本亂序操作,可以使用函數tf.train.shuffle_batch_join多實例化reader def read_my_file_format(filename_queue): # 與上例子相同 def input_pipeline(filenames, batch_size, read_threads, num_epochs=None): filename_queue = tf.train.string_input_producer( filenames, num_epochs=num_epochs, shuffle=True) example_list = [read_my_file_format(filename_queue) for _ in range(read_threads)] min_after_dequeue = 10000 capacity = min_after_dequeue + 3 * batch_size example_batch, label_batch = tf.train.shuffle_batch_join( example_list, batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue) 

Tensorflow一些常用基本概念與函數(三)

摘要:本系列主要對tf的一些常用概念與方法進行描述。本文主要針對tensorflow的數據IO、圖的運行等相關函數進行講解。為‘Tensorflow一些常用基本概念與函數’系列之三。

1、序言

本文所講的內容主要為以下相關函數:

操作組 操作
Data IO (Python functions) TFRecordWrite,rtf_record_iterator
Running Graphs Session management,Error classes

2、tf函數

2.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文件中讀取記錄的迭代器

2.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 sess print(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) 使用該形式方法創建以上各種錯誤類

Tensorflow一些常用基本概念與函數(四)

摘要:本系列主要對tf的一些常用概念與方法進行描述。本文主要針對tensorflow的模型訓練Training與測試Testing等相關函數進行講解。為‘Tensorflow一些常用基本概念與函數’系列之四。

1、序言

本文所講的內容主要為以下列表中相關函數。函數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)
操作組 操作
Training Optimizers,Gradient Computation,Gradient Clipping,Distributed execution
Testing Unit tests,Utilities,Gradient checking

2、Tensorflow函數

2.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 period coord.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。可用server.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(): break if is_chief and step % 100 == 0: # Create the summary every 100 chief steps. sv.summary_computed(sess, sess.run(my_summary_op)) else: # Train normally sess.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(): break sess.run(<my training op>) ...do other things needed at each training step...

 

 

▷ 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"]})

 

 

▷ 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 graph v1 = tf.Variable(...) # assigned to /job:ps/task:0 v2 = tf.Variable(...) # assigned to /job:ps/task:1 v3 = 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)

 

 

 

█ 訓練的通用函數及其他(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 below return np.sinh(x) inp = tf.placeholder(tf.float32, [...]) y = py_func(my_func, [inp], [tf.float32]) 

 

 

2.2 測試 (Testing)

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

import tensorflow as tf class 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

注:本教程不是原創 轉自http://blog.csdn.net/lenbow/article/details/52218551

感謝作者  的總結  與付出

  1 #一個簡單的tf.Session例子
  2 # 建立一個graph.
  3 a = tf.constant(5.0)
  4 b = tf.constant(6.0)
  5 c = a * b
  6 
  7 # 將graph載入到一個會話session中
  8 sess = tf.Session()
  9 
 10 # 計算tensor `c`.
 11 print(sess.run(c))#一個會話可能會占用一些資源,比如變量、隊列和讀取器(reader)。釋放這些不再使用的資源非常重要。
 12 #使用close()方法關閉會話,或者使用上下文管理器,釋放資源。
 13 # 使用`close()`方法.
 14 sess = tf.Session()
 15 sess.run(...)
 16 sess.close()
 17 
 18 # 使用上下文管理器
 19 with tf.Session() as sess:
 20   sess.run(...)# Launch the graph in a session that allows soft device placement and
 21 # logs the placement decisions.
 22 sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
 23                                         log_device_placement=True))a = tf.constant([10, 20])
 24    b = tf.constant([1.0, 2.0])
 25    # 'fetches' 可以為單個數
 26    v = session.run(a)
 27    # v is the numpy array [10, 20]
 28    # 'fetches' 可以為一個list.
 29    v = session.run([a, b])
 30    # v a Python list with 2 numpy arrays: the numpy array [10, 20] and the
 31    # 1-D array [1.0, 2.0]
 32    # 'fetches' 可以是 lists, tuples, namedtuple, dicts中的任意:
 33    MyData = collections.namedtuple('MyData', ['a', 'b'])
 34    v = session.run({'k1': MyData(a, b), 'k2': [b, a]})
 35    # v 為一個dict,並有
 36    # v['k1'] is a MyData namedtuple with 'a' the numpy array [10, 20] and
 37    # 'b' the numpy array [1.0, 2.0]
 38    # v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array
 39    # [10, 20].c = tf.constant(..)
 40 sess = tf.Session()
 41 
 42 with sess.as_default():
 43   assert tf.get_default_session() is sess
 44   print(c.eval())c = tf.constant(...)
 45 sess = tf.Session()
 46 with sess.as_default():
 47   print(c.eval())
 48 # ...
 49 with sess.as_default():
 50   print(c.eval())
 51 #關閉會話
 52 sess.close()
 53 #使用 with tf.Session()方式可以創建並自動關閉會話sess = tf.InteractiveSession()
 54 a = tf.constant(5.0)
 55 b = tf.constant(6.0)
 56 c = a * b
 57 # 我們直接使用'c.eval()' 而沒有通過'sess'
 58 print(c.eval())
 59 sess.close()a = tf.constant(5.0)
 60 b = tf.constant(6.0)
 61 c = a * b
 62 with tf.Session():
 63   # We can also use 'c.eval()' here.
 64   print(c.eval())optimizer = tf.train.GradientDescentOptimizer(learning_rate)global_step = tf.Variable(0, name='global_step', trainable=False)
 65 train_op = optimizer.minimize(loss, global_step=global_step)# Create an optimizer with the desired parameters.
 66 opt = GradientDescentOptimizer(learning_rate=0.1)
 67 # Add Ops to the graph to minimize a cost by updating a list of variables.
 68 # "cost" is a Tensor, and the list of variables contains tf.Variable objects.
 69 opt_op = opt.minimize(cost, var_list=<list of variables>)
 70 # Execute opt_op to do one step of training:
 71 opt_op.run()1、使用函數compute_gradients()計算梯度
 72 2、按照自己的願望處理梯度
 73 3、使用函數apply_gradients()應用處理過后的梯度# 創建一個optimizer.
 74 opt = GradientDescentOptimizer(learning_rate=0.1)
 75 
 76 # 計算<list of variables>相關的梯度
 77 grads_and_vars = opt.compute_gradients(loss, <list of variables>)
 78 
 79 # grads_and_vars為tuples (gradient, variable)組成的列表。
 80 #對梯度進行想要的處理,比如cap處理
 81 capped_grads_and_vars = [(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars]
 82 
 83 # 令optimizer運用capped的梯度(gradients)
 84 opt.apply_gradients(capped_grads_and_vars)m_0 <- 0 (Initialize initial 1st moment vector)
 85 v_0 <- 0 (Initialize initial 2nd moment vector)
 86 t <- 0 (Initialize timestep)t <- t + 1
 87 lr_t <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t)
 88 
 89 m_t <- beta1 * m_{t-1} + (1 - beta1) * g
 90 v_t <- beta2 * v_{t-1} + (1 - beta2) * g * g
 91 variable <- variable - lr_t * m_t / (sqrt(v_t) + epsilon)#該函數返回以下結果
 92 decayed_learning_rate = learning_rate *
 93          decay_rate ^ (global_step / decay_steps)
 94 ##例: 以0.96為基數,每100000 步進行一次學習率的衰退
 95 global_step = tf.Variable(0, trainable=False)
 96 starter_learning_rate = 0.1
 97 learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,
 98                                            100000, 0.96, staircase=True)
 99 # Passing global_step to minimize() will increment it at each step.
100 learning_step = (
101     tf.train.GradientDescentOptimizer(learning_rate)
102     .minimize(...my loss..., global_step=global_step)
103 )# Example usage when creating a training model:
104 # Create variables.
105 var0 = tf.Variable(...)
106 var1 = tf.Variable(...)
107 # ... use the variables to build a training model...
108 ...
109 # Create an op that applies the optimizer. This is what we usually
110 # would use as a training op.
111 opt_op = opt.minimize(my_loss, [var0, var1])
112 
113 # Create an ExponentialMovingAverage object
114 ema = tf.train.ExponentialMovingAverage(decay=0.9999)
115 
116 # Create the shadow variables, and add ops to maintain moving averages
117 # of var0 and var1.
118 maintain_averages_op = ema.apply([var0, var1])
119 
120 # Create an op that will update the moving averages after each training
121 # step. This is what we will use in place of the usual training op.
122 with tf.control_dependencies([opt_op]):
123     training_op = tf.group(maintain_averages_op)
124 
125 ...train the model by running training_op...
126 
127 #Example of restoring the shadow variable values:
128 # Create a Saver that loads variables from their saved shadow values.
129 shadow_var0_name = ema.average_name(var0)
130 shadow_var1_name = ema.average_name(var1)
131 saver = tf.train.Saver({shadow_var0_name: var0, shadow_var1_name: var1})
132 saver.restore(...checkpoint filename...)
133 # var0 and var1 now hold the moving average valuesvariables_to_restore = ema.variables_to_restore()
134   saver = tf.train.Saver(variables_to_restore)#Coordinator的使用,用於多線程的協調
135 try:
136   ...
137   coord = Coordinator()
138   # Start a number of threads, passing the coordinator to each of them.
139   ...start thread 1...(coord, ...)
140   ...start thread N...(coord, ...)
141   # Wait for all the threads to terminate, give them 10s grace period
142   coord.join(threads, stop_grace_period_secs=10)
143 except RuntimeException:
144   ...one of the threads took more than 10s to stop after request_stop()
145   ...was called.
146 except Exception:
147   ...exception that was passed to coord.request_stop()with coord.stop_on_exception():
148   # Any exception raised in the body of the with
149   # clause is reported to the coordinator before terminating
150   # the execution of the body.
151   ...body...
152 #等價於
153 try:
154   ...body...
155 exception Exception as ex:
156   coord.request_stop(ex)server = tf.train.Server(...)
157 with tf.Session(server.target):
158   # ...with tf.Graph().as_default():
159   ...add operations to the graph...
160   # Create a Supervisor that will checkpoint the model in '/tmp/mydir'.
161   sv = Supervisor(logdir='/tmp/mydir')
162   # Get a TensorFlow session managed by the supervisor.
163   with sv.managed_session(FLAGS.master) as sess:
164     # Use the session to train the graph.
165     while not sv.should_stop():
166       sess.run(<my_train_op>)
167 # 在上下文管理器with sv.managed_session()內,所有在graph的變量都被初始化。
168 # 或者說,一些服務器checkpoint相應模型並增加summaries至事件log中。
169 # 如果有例外發生,should_stop()將返回True# Choose a task as the chief. This could be based on server_def.task_index,
170 # or job_def.name, or job_def.tasks. It's entirely up to the end user.
171 # But there can be only one *chief*.
172 is_chief = (server_def.task_index == 0)
173 server = tf.train.Server(server_def)
174 
175 with tf.Graph().as_default():
176   ...add operations to the graph...
177   # Create a Supervisor that uses log directory on a shared file system.
178   # Indicate if you are the 'chief'
179   sv = Supervisor(logdir='/shared_directory/...', is_chief=is_chief)
180   # Get a Session in a TensorFlow server on the cluster.
181   with sv.managed_session(server.target) as sess:
182     # Use the session to train the graph.
183     while not sv.should_stop():
184       sess.run(<my_train_op>)#例如: 開啟一個線程用於打印loss. 設置每60秒該線程運行一次,我們使用sv.loop()
185  ...
186   sv = Supervisor(logdir='/tmp/mydir')
187   with sv.managed_session(FLAGS.master) as sess:
188     sv.loop(60, print_loss, (sess))
189     while not sv.should_stop():
190       sess.run(my_train_op)在chief中每100個step,創建summaries
191   # Create a Supervisor with no automatic summaries.
192   sv = Supervisor(logdir='/tmp/mydir', is_chief=is_chief, summary_op=None)
193   # As summary_op was None, managed_session() does not start the
194   # summary thread.
195   with sv.managed_session(FLAGS.master) as sess:
196     for step in xrange(1000000):
197       if sv.should_stop():
198         break
199       if is_chief and step % 100 == 0:
200         # Create the summary every 100 chief steps.
201         sv.summary_computed(sess, sess.run(my_summary_op))
202       else:
203         # Train normally
204         sess.run(my_train_op)def train():
205   sv = tf.train.Supervisor(...)
206   with sv.managed_session(<master>) as sess:
207     for step in xrange(..):
208       if sv.should_stop():
209         break
210       sess.run(<my training op>)
211       ...do other things needed at each training step...with tf.Graph().as_default():
212    ...add operations to the graph...
213   # Create a SessionManager that will checkpoint the model in '/tmp/mydir'.
214   sm = SessionManager()
215   sess = sm.prepare_session(master, init_op, saver, checkpoint_dir)
216   # Use the session to train the graph.
217   while True:
218     sess.run(<my_train_op>)
219 #其中prepare_session()初始化和恢復一個模型參數。 
220 
221 #另一個進程將等待model准備完成,代碼如下
222 with tf.Graph().as_default():
223   ...add operations to the graph...
224   # Create a SessionManager that will wait for the model to become ready.
225   sm = SessionManager()
226   sess = sm.wait_for_session(master)
227   # Use the session to train the graph.
228   while True:
229     sess.run(<my_train_op>)
230 #wait_for_session()等待一個model被其他進程初始化cluster = tf.train.ClusterSpec({"worker": ["worker0.example.com:2222",
231                                            "worker1.example.com:2222",
232                                            "worker2.example.com:2222"],
233                                 "ps": ["ps0.example.com:2222",
234                                        "ps1.example.com:2222"]})# To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker
235 # jobs on hosts worker0, worker1 and worker2.
236 cluster_spec = {
237     "ps": ["ps0:2222", "ps1:2222"],
238     "worker": ["worker0:2222", "worker1:2222", "worker2:2222"]}
239 with tf.device(tf.replica_device_setter(cluster=cluster_spec)):
240   # Build your graph
241   v1 = tf.Variable(...)  # assigned to /job:ps/task:0
242   v2 = tf.Variable(...)  # assigned to /job:ps/task:1
243   v3 = tf.Variable(...)  # assigned to /job:ps/task:0
244 # Run compute...create a graph...
245 # Launch the graph in a session.
246 sess = tf.Session()
247 # Create a summary writer, add the 'graph' to the event file.
248 writer = tf.train.SummaryWriter(<some-directory>, sess.graph)#打印時間文件中的內容
249 for e in tf.train.summary_iterator(path to events file):
250     print(e)
251 
252 #打印指定的summary值
253 # This example supposes that the events file contains summaries with a
254 # summary value tag 'loss'. These could have been added by calling
255 # `add_summary()`, passing the output of a scalar summary op created with
256 # with: `tf.scalar_summary(['loss'], loss_tensor)`.
257 for e in tf.train.summary_iterator(path to events file):
258     for v in e.summary.value:
259         if v.tag == 'loss':
260             print(v.simple_value)# Creates a variable to hold the global_step.
261 global_step_tensor = tf.Variable(10, trainable=False, name='global_step')
262 # Creates a session.
263 sess = tf.Session()
264 # Initializes the variable.
265 sess.run(global_step_tensor.initializer)
266 print('global_step: %s' % tf.train.global_step(sess, global_step_tensor))
267 
268 global_step: 10v = tf.Variable(0, name='my_variable')
269 sess = tf.Session()
270 tf.train.write_graph(sess.graph_def, '/tmp/my-model', 'train.pbtxt')#tf.py_func(func, inp, Tout, stateful=True, name=None)
271 #func:為一個python函數
272 #inp:為輸入函數的參數,Tensor列表
273 #Tout: 指定func返回的輸出的數據類型,是一個列表
274 def my_func(x):
275   # x will be a numpy array with the contents of the placeholder below
276   return np.sinh(x)
277 inp = tf.placeholder(tf.float32, [...])
278 y = py_func(my_func, [inp], [tf.float32])import tensorflow as tf
279 
280 
281 class SquareTest(tf.test.TestCase):
282 
283   def testSquare(self):
284     with self.test_session():
285       x = tf.square([2, 3])
286       self.assertAllEqual(x.eval(), [4, 9])
287 
288 
289 if __name__ == '__main__':
290   tf.test.main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM