本文介紹了tensorflow的經常使用函數,源自網上整理。git
TensorFlow 將圖形定義轉換成分佈式執行的操做, 以充分利用可用的計算資源(如 CPU 或 GPU。通常你不須要顯式指定使用 CPU 仍是 GPU, TensorFlow 能自動檢測。若是檢測到 GPU, TensorFlow 會盡量地利用找到的第一個 GPU 來執行操做.
並行計算能讓代價大的算法計算加速執行,TensorFlow也在實現上對複雜操做進行了有效的改進。大部分核相關的操做都是設備相關的實現,好比GPU。
算法
下面是一些重要的操做/核:
api
操做組 | 操做 |
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 |
操做 | 描述 |
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.ide |
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.sqrt(x, name=None) | 開根號 (y = \sqrt{x} = x^{1/2}). |
tf.pow(x, y, name=None) | 冪次方 (元素級)ui # tensor ‘x’ is [[2, 2], [3, 3]] |
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 |
操做 | 描述 |
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 |
操做 | 描述 |
tf.shape(input, name=None) | 返回數據的shape # ‘t’ is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] |
tf.size(input, name=None) | 返回數據的元素數量 # ‘t’ is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]] |
tf.rank(input, name=None) | 返回tensor的rank(維度) 注意:此rank不一樣於矩陣的rank, |
tf.reshape(tensor, shape, name=None) | 改變tensor的形狀 # tensor ‘t’ is [1, 2, 3, 4, 5, 6, 7, 8, 9] |
tf.expand_dims(input, dim, name=None) | 插入維度1進入一個tensor中 #該操做要求-1-input.dims() |
操做 | 描述 |
tf.slice(input_, begin, size, name=None) | 對tensor進行切片操做,從input中抽取部份內容 inputs:能夠是list,array,tensor begin:n維列表,begin[i] 表示從inputs中第i維抽取數據時,相對0的起始偏移量,也就是從第i維的begin[i]開始抽取數據 size:n維列表,size[i]表示要抽取的第i維元素的數目 有幾個關係式以下: (1) i in [0,n] (2)tf.shape(inputs)[0]=len(begin)=len(size) (3)begin[i]>=0 抽取第i維元素的起始位置要大於等於0 (4)begin[i]+size[i]<=tf.shape(inputs)[i] #’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] |
tf.concat(concat_dim, values, name=’concat’) | 沿着某一維度連結tensor (總體維度不變) t1 = [[1, 2, 3], [4, 5, 6]] 若是想沿着tensor一新軸連結打包,那麼能夠: tf.concat(axis, [tf.expand_dims(t, axis) for t in tensors]) |
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] |
tf.reverse(tensor, dims, name=None) | 沿着某維度進行序列反轉 # tensor ‘t’ is |
tf.transpose(a, perm=None, name=’transpose’) | 調換tensor的維度順序(軸變換) # ‘x’ is [[1 2 3],[4 5 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) |
獨熱編碼(ont-hot encoing) indices = [0, 2, -1, 1] |
操做 | 描述 |
tf.diag(diagonal, name=None) | 返回一個給定對角值的對角tensor # ‘diagonal’ is [1, 2, 3, 4] |
tf.diag_part(input, name=None) | 功能與上面相反 |
tf.trace(x, name=None) | 求一個2維tensor的跡,即對角值diagonal之和 |
tf.transpose(a, perm=None, name=’transpose’) | 調換tensor的維度順序(軸變換) |
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) | 求解方程 matrix爲方陣shape爲[M,M],rhs的shape爲[M,K],output爲[M,K] |
操做 | 描述 |
tf.complex(real, imag, name=None) | 將兩實數轉換爲複數形式 # tensor ‘real’ is [2.25, 3.25] |
tf.complex_abs(x, name=None) | 計算複數的絕對值,即長度 # tensor ‘x’ is [[-2.25 + 4.75j], [-3.25 + 5.75j]] |
tf.conj(input, name=None) | 計算共軛複數 |
tf.imag(input, name=None) tf.real(input, name=None) |
提取複數的虛部和實部 |
tf.fft(input, name=None) | 計算一維的離散傅里葉變換,輸入數據類型爲complex64 |
操做 | 描述 |
tf.reduce_sum(input_tensor, |
計算輸入tensor元素的和,或者安照reduction_indices指定的軸進行求和 # ‘x’ is [[1, 1, 1] |
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 |
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]] |
tf.cumsum(x, axis=0, exclusive=False, reverse=False, name=None) |
求累積和 tf.cumsum([a, b, c]) ==> [a, a + b, a + b + c] |
操做 | 描述 |
tf.segment_sum(data, segment_ids, name=None) | 沿張量的片斷計算總和(第一維)
data:一個Tensor。 segment_ids:一個Tensor;必須是如下類型之一:int32,int64; 一維張量,其秩等於data第一維的秩;值應該被排序,而且能夠是重複的。 name:操做的名稱(可選)。
tf.segment_sum函數返回的是一個Tensor,它與data有相同的類型, 與data具備相同的形狀, 但大小爲 k(段的數目)的維度0除外。 |
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函數相似, |
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]]) |
操做 | 描述 |
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 |
tf.unique(x, name=None) | 返回一個元組tuple(y,idx),y爲x的列表的惟一化數據列表, # tensor ‘x’ is [1, 1, 2, 4, 4, 4, 7, 8, 8] |
tf.invert_permutation(x, name=None) | 置換x數據與索引的關係 y[x[i]] = i for i in [0, 1, ..., len(x) - 1] # tensor |
操做 | 描述 |
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) | 雙曲線切線激活函數 |
操做 | 描述 |
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] |
操做 | 描述 |
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 |
操做 | 描述 |
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) |
直接計算均值與方差 |
操做 | 描述 |
tf.nn.l2_loss(t, name=None) | output = sum(t ** 2) / 2 |
操做 | 描述 |
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 |
操做 | 描述 |
tf.nn.embedding_lookup (params, ids, partition_strategy=’mod’, name=None, validate_indices=True) |
根據索引ids查詢embedding列表params中的tensor值 一、若是partition_strategy爲」mod」, 二、若是partition_strategy爲」div」,那麼分配方案爲: |
tf.nn.embedding_lookup_sparse(params, sp_ids, sp_weights, partition_strategy=’mod’, name=None, combiner=’mean’) |
對給定的ids和權重查詢embedding 一、sp_ids爲一個N x M的稀疏tensor, 二、sp_weights的shape與sp_ids的稀疏tensor權重, |
操做 | 描述 |
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.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 一、sampled_candidates 候選集合。 二、指望的true_classes個數,爲浮點值 三、指望的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文件名列表和時間戳 |