(Translated by https://www.hiragana.jp/)
TensorFlow - 维基教科书,自由的教学读本 とべ转到内容ないよう

TensorFlow

维基教科きょうか书,自由じゆうてき教学きょうがく读本

TensorFlow一个开源软件库,よう于各种机がく习与すうすえ处理にん务。TensorFlow最初さいしょよしたに公司こうしてきだい脑团队开发,よう于Googleてき研究けんきゅう和生かずお产,于2015ねん11月9にちざいApache 2.0开源许可证下发布。

ざいPythonちゅう需要じゅようくびさき导入つつみ

import tensorflow as tf

概念がいねん

[编辑]
  • TensorFlowさいようかずすえりゅう(data flow graphs)らい描述りょう计算てき过程。
  • 图中てき节点(Nodes)しょう为 op (operation てき缩写),もちいらい表示ひょうじほどこせてき计算にん务,ただし也可以表示ひょうじすうすえ输入(feed in)てき起点きてん/输出(push out)てき终点,あるもの读取/うつしにゅう持久じきゅう变量(persistent variable)てき终点。いち个 op 获得 0 个或个 tensor,执行计算产生 0 个或个张りょうtensor,まい个tensor一个类型化的多维数组。
    • みなもと op (source op)需要じゅようにんなん输入,れいつねりょう (Constant)。
  • 线(edges)则表示ひょうじざい节点间相互联けいてき维数すえすう组(そく张量)。ざいPythonちゅう,节点赋值给一个名字みょうじ,该名字みょうじ对应てき类型为ensorflow.python.framework.ops.Tensor,そく表示ひょうじ这个节点输出てき张量。一旦输入端的所有张量准备好,节点はた分配ぶんぱいいたかく种计さん设备完成かんせい异步并行计算。
  • 为了进行计算,图必须在しょうかい话 (Session) てき上下じょうげぶん (context) ちゅう执行。Session はた图的 op ぶん发到诸如 CPU ある GPU 类的设备じょうどう提供ていきょう执行 op てき方法ほうほう。这些方法ほうほう执行きさきはた产生てき tensor かえしかい
  • 变量 (Variable) よう于维护状态
  • feedつくえせい以用いち个 tensor 值临时替换图ちゅうてき任意にんい节点てき输出tensor;还可以直接ちょくせつ插入そうにゅういち个 tensor。feedすうすえさく为 Session 对象てきrun() 调用てきさんすう。feed ただざい调用它的方法ほうほうない有效ゆうこう方法ほうほう结束,feed 就会消失しょうしつ
  • fetch:为了かい操作そうさてき输出内容ないよう使用しよう Session 对象てき run() 调用执行图时,传入いち些(节点てき输出)tensor,,则run()かえしかい其计さん结果。ざい Python 语言ちゅう, tf.Sessionてきrunかえしかいてきtensor numpy.ndarray 对象;ざい C C++ 语言ちゅうかえしかいてき tensor tensorflow::Tensor 实例。Session需要じゅようclose()释放。

交互こうごしき运行环境

[编辑]

使用しよう InteractiveSession 代替だいたい Session 类,使用しよう Tensor.eval() かず Operation.run() 方法ほうほう代替だいたい Session.run().

# 进入いち交互こうごしき TensorFlow かい话.
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# 使用しようはつはじめ initializer op てき run() 方法ほうほうはつはじめ 'x' 
x.initializer.run()

# 增加ぞうかいち个减ほう sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果 
sub = tf.subtract(x, a)
print (sub.eval())

TensorBoard视化すうすえりゅう

[编辑]
import tensorflow as tf

a = tf.constant(2, name="a")
b = tf.constant(2, name="b")
x = tf.add(a, b, name="add") 
with tf.Session() as sess:
    writer = tf.summary.FileWriter('D:\\tmp', sess.graph) # if you prefer creating your writer using session's graph
    print(sess.run(x))
    writer.close()

しかきさきざいcmd运行程こうていじょ

$ python3 [my_program.py] 
$ tensorboard --logdir="\tmp" --port 6006

ざい浏览

http://ThisComputerName:6006/

なり员函すう

[编辑]

つねりょう

[编辑]
num = tf.constant(2, name="num")
# constant of 1d tensor (vector)
a = tf.constant([2, 2], name="vector")
# constant of 2x2 tensor (matrix)
b = tf.constant([[0, 1], [2, 3]], name="matrix")
# create a tensor of shape and all elements are zeros
tf.zeros([2, 3], tf.int32) ==> [[0, 0, 0], [0, 0, 0]]
# create a tensor of shape and type (unless type is specified) as the input_tensor but all elements are zeros. input_tensor [[0, 1], [2, 3], [4, 5]]
tf.zeros_like(input_tensor) ==> [[0, 0], [0, 0], [0, 0]]
# create a tensor of shape and all elements are ones
tf.ones([2, 3], tf.int32) ==> [[1, 1, 1], [1, 1, 1]]
# input_tensor is [[0, 1], [2, 3], [4, 5]]
tf.ones_like(input_tensor) ==> [[1, 1], [1, 1], [1, 1]]
# create a tensor filled with a scalar value.
tf.fill([2, 3], 8) ==> [[8, 8, 8], [8, 8, 8]]
#tf.lin_space(start, stop, num, name=None)
# create a sequence of num evenly-spaced values are generated beginning at start. If num > 1, the values in the sequence increase by (stop - start) / (num - 1), so that the last one is exactly stop. comparable to but slightly different from numpy.linspace
tf.lin_space(10.0, 13.0, 4, name="linspace") ==> [10.0 11.0 12.0 13.0]
#tf.range([start], limit=None, delta=1, dtype=None, name='range')
# create a sequence of numbers that begins at start and extends by increments of delta up to but not including limit. slight different from range in Python
# 'start' is 3, 'limit' is 18, 'delta' is 3
tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]
# 'start' is 3, 'limit' is 1,  'delta' is -0.5
tf.range(start, limit, delta) ==> [3, 2.5, 2, 1.5]
# 'limit' is 5
tf.range(limit) ==> [0, 1, 2, 3, 4]

ぞうNumpyあるものPython其他序列じょれつ,TensorFlow序列じょれつ不能ふのう迭代

for _ in np.linspace(0, 10, 4): # OK
for _ in tf.linspace(0.0, 10.0, 4): # TypeError: 'Tensor' object is not iterable.
for _ in range(4): # OK
for _ in tf.range(4): # TypeError: 'Tensor' object is not iterable.

生成せいせいずいつくえつねりょう

  • tf.random_normal
  • tf.truncated_normal
  • tf.random_uniform
  • tf.random_shuffle
  • tf.random_crop
  • tf.multinomial
  • tf.random_gamma
  • tf.set_random_seed

变量

[编辑]
  • tf.Variable(initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None) 如果检测到命名めいめい冲突,けい统会自己じこ处理。 每次まいじ创建しん对象
  • tf.get_variable(name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, custom_getter=None) 如果检测到命名めいめい冲突,けい统会报错。よし而,需要じゅようまたが作用さよういきどもとおる变量てき时候,应该使用しようtf.get_variable()
  • tf.global_variables_initializer はつはじめ全局ぜんきょく变量

tf.assign(variableName,value) 赋值给变りょう

数学すうがく运算

[编辑]

かく种除ほう

import tensorflow as tf
a = tf.constant([2, 2], name='a')
b = tf.constant([[0, 1], [2, 3]], name='b')
with tf.Session() as sess:
   #print(sess.run(tf.div(b, a)))             #  ⇒ [[0 0] [1 1]] 过时りょう
   print(sess.run(tf.divide(b, a)))          #  ⇒ [[0. 0.5] [1. 1.5]]
   print(sess.run(tf.truediv(b, a)))         #  ⇒ [[0. 0.5] [1. 1.5]]
   print(sess.run(tf.floordiv(b, a)))        #  ⇒ [[0 0] [1 1]]
   #print(sess.run(tf.realdiv(b, a)))         #  ⇒ # Error: only works for real values
   print(sess.run(tf.truncatediv(b, a)))     #  ⇒ [[0 0] [1 1]]
   print(sess.run(tf.floor_div(b, a)))       #  ⇒ [[0 0] [1 1]]
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) 幂次かた
  1. tensor ‘x’ is [[2, 2], [3, 3]]
  2. 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

かずすえ类型转换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
  1. tensor a is [1.8, 2.2], tf.cast(a, tf.int32) ==> [1, 2] # dtype=tf.int32

形状けいじょう操作そうさShapes and Shaping

操作そうさ 描述
tf.shape(input, name=None) かえし回数かいすうすえてきshape
  1. ‘t’ is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]

shape(t) ==> [2, 2, 3]

tf.size(input, name=None) かえし回数かいすうすえてき元素げんそ数量すうりょう
  1. ‘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”

  1. ’t’ is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]
  2. shape of tensor ‘t’ is [2, 2, 3]

rank(t) ==> 3 tf.reshape(tensor, shape, name=None) あらため变tensorてき形状けいじょう

  1. tensor ‘t’ is [1, 2, 3, 4, 5, 6, 7, 8, 9]
  2. tensor ‘t’ has shape [9]

reshape(t, [3, 3]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

  1. 如果shapeゆう元素げんそ[-1],表示ひょうじざい该维たいら至一しいち
  2. -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. 操作そうさ要求ようきゅう-1-input.dims()
  2. ‘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]

  1. ’input’ is
  2. [[[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

  1. ‘value’ is a tensor with shape [5, 30]
  2. 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

  1. ‘x’ is [1, 4], ‘y’ is [2, 5], ‘z’ is [3, 6]

pack([x, y, z]) => [[1, 4], [2, 5], [3, 6]]

  1. 沿着だいいち维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)

  1. tensor ‘t’ is

[[[[ 0, 1, 2, 3],

  1. [ 4, 5, 6, 7],
  1. [ 8, 9, 10, 11]],
  2. [[12, 13, 14, 15],
  3. [16, 17, 18, 19],
  4. [20, 21, 22, 23]]]]
  5. tensor ‘t’ shape is [1, 2, 3, 4]
  6. ‘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)

  1. ‘x’ is [[1 2 3],[4 5 6]]

tf.transpose(x) ==> [[1 4], [2 5],[3 6]]

  1. 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

  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

  1. ‘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)

  1. ‘x’ is [[1 2 3],[4 5 6]]

tf.transpose(x) ==> [[1 4], [2 5],[3 6]]

  1. 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) はた两实すう转换为复すう形式けいしき

  1. tensor ‘real’ is [2.25, 3.25]
  2. 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) 计算复数てき绝对值,そく长度。

  1. 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指定していてき轴进ぎょうもとめ

  1. ‘x’ is [[1, 1, 1]
  2. [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ちゅうかく元素げんそもとめ逻辑’あずか

  1. ‘x’ is
  2. [[True, True]
  3. [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てき

  1. tensor ‘a’ is [[1, 2], [3, 4]]
  2. 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]])

  1. 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てき位置いち

  1. ‘input’ tensor is
  2. [[True, False]
  3. [True, False]]
  4. ‘input’ ゆう两个’True’,么输两个坐标值.
  5. ‘input’てきrank为2, 所以ゆえんごと个坐标为具有ぐゆう两个维度.

where(input) ==> [[0, 0], [1, 0]] tf.unique(x, name=None) かえしかいいち个元组tuple(y,idx),y为xてきれつひょうてきただ一化数据列表, idx为xかずすえ对应y元素げんそてきindex

  1. 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かずすえあずか索引さくいんてき关系

  1. 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) 计算logitslabelsてきsoftmax交叉こうさ熵 logits, labels必须为相どうてきshapeあずかかずすえ类型 tf.nn.sparse_softmax_cross_entropy_with_logits (logits, labels, name=None) 计算logitslabelsてきsoftmax交叉こうさ熵 tf.nn.weighted_cross_entropy_with_logits (logits, targets, pos_weight, name=None) あずかsigmoid_cross_entropy_with_logits()相似そうじただし给正こう样本损失りょう权重pos_weight

   符号ふごう嵌入かんにゅう(Embeddings)

操作そうさ 描述 tf.nn.embedding_lookup (params, ids, partition_strategy=’mod’, name=None, validate_indices=True) すえ索引さくいんids查询embeddingれつひょうparamsちゅうてきtensor值 如果len(params) > 1,idしょうかいあんあきらpartition_strategy策略さくりゃく进行分割ぶんかつ 1、如果partition_strategy为”mod”, idしょ分配ぶんぱいいたてき位置いち为p = id % len(params) 如有13个ids,ふん为5个位置いち分配ぶんぱい方案ほうあん为: [[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8], [4, 9]] 2、如果partition_strategy为”div”,分配ぶんぱい方案ほうあん为: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]] tf.nn.embedding_lookup_sparse(params, sp_ids, sp_weights, partition_strategy=’mod’, name=None, combiner=’mean’) 对给じょうてきids权重查询embedding 1、sp_ids为一个N x Mてきまれ疏tensor, N为batch大小だいしょう,M为任意にんいすうすえ类型int64 2、sp_weightsてきshapeあずかsp_idsてきまれ疏tensor权重, 浮点类型,わか为None,则权じゅう为全’1’

   循环しん经网络(Recurrent Neural Networks)

操作そうさ 描述 tf.nn.rnn(cell, inputs, initial_state=None, dtype=None, sequence_length=None, scope=None) もと于RNNCell类的实例cell建立こんりゅう循环しん经网络 tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None) もと于RNNCell类的实例cell建立こんりゅう动态循环しん经网络 あずか一般いっぱんrnn不同ふどうてき,该函すうかいすえ输入动态てんかえしかい(outputs,state) tf.nn.state_saving_rnn(cell, inputs, state_saver, state_name, sequence_length=None, scope=None) 储存调试じょう态的RNN网络 tf.nn.bidirectional_rnn(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None, sequence_length=None, scope=None) そうこうRNN, かえしかいいち个3げん组tuple (outputs, output_state_fw, output_state_bw)

   — tf.nn.rnn简要かい绍— 
   cell: いち个RNNCell实例 
   inputs: いち个shape为[batch_size, input_size]てきtensor 
   initial_state: 为RNNてきstate设定はつ值,选 
   sequence_length:制定せいてい输入てきごと一个序列的长度,size为[batch_size],值范围为[0, T)てきintがたすうすえ 
   其中T为输いれすうすえ序列じょれつてき长度 
   @ 
   @针对输入batchちゅう序列じょれつ长度不同ふどうしょ设置てき动态计算つくえせい 
   @对于ざい时间t,かずbatchてきbくだりゆう 
   (output, state)(b, t) = ? (zeros(cell.output_size), states(b, sequence_length(b) - 1)) : cell(input(b, t), state(b, t - 1))
   もとめ值网络(Evaluation)

操作そうさ 描述 tf.nn.top_k(input, k=1, sorted=True, name=None) かえしかいまえkだいてき值及其对应的索引さくいん tf.nn.in_top_k(predictions, targets, k, name=None) かえしかい判断はんだんtargets索引さくいんてきpredictionsしょう应的值 いやざいざいpredictionsまえk个位置いちちゅうかえし回数かいすうすえ类型为bool类型,lenあずかpredictionsどう

   监督こう选采样网络(Candidate Sampling)

对于ゆうきょ大量たいりょうてき多分たぶん类与标签模型もけい,如果使用しようぜん连接softmaxしょうかいうらないよう大量たいりょうてき时间与そら间资げん所以ゆえんさいようこう选采样方ほう使用しよう一小部分类别与标签作为监督以加速训练。 操作そうさ 描述 Sampled Loss Functions tf.nn.nce_loss(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=False, partition_strategy=’mod’, name=’nce_loss’) かえしかいnoise-contrastiveてき训练损失结果 tf.nn.sampled_softmax_loss(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=True, partition_strategy=’mod’, name=’sampled_softmax_loss’) かえしかいsampled softmaxてき训练损失 参考さんこう- Jean et al., 2014だい3部分ぶぶん Candidate Samplers tf.nn.uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None) どおり过均匀分布ぶんぷてきさい集合しゅうごう かえしかいさんげんtuple 1、sampled_candidates こう集合しゅうごう。 2、もちてきtrue_classes个数,为浮てん值 3、もちてきsampled_candidates个数,为浮てん值 tf.nn.log_uniform_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None) どおり过logひとし分布ぶんぷてきさい集合しゅうごうかえしかいさんげんtuple tf.nn.learned_unigram_candidate_sampler (true_classes, num_true, num_sampled, unique, range_max, seed=None, name=None) すえざい训练过程中学ちゅうがく习到てき分布ぶんぷじょう况进ぎょうさいかえしかいさんげんtuple tf.nn.fixed_unigram_candidate_sampler(true_classes, num_true, num_sampled, unique, range_max, vocab_file=”, distortion=1.0, num_reserved_ids=0, num_shards=1, shard=0, unigrams=(), seed=None, name=None) もと于所提供ていきょうてき基本きほん分布ぶんぷ进行さい保存ほぞんあずか恢复变量 操作そうさ 描述 类tf.train.Saver(Saving and Restoring Variables) tf.train.Saver.__init__(var_list=None, reshape=False, sharded=False, max_to_keep=5, keep_checkpoint_every_n_hours=10000.0, name=None, restore_sequentially=False, saver_def=None, builder=None) 创建いち个存储器Saver var_listてい义需ようそん储和恢复てき变量 tf.train.Saver.save(sess, save_path, global_step=None, latest_filename=None, meta_graph_suffix=’meta’, write_meta_graph=True) 保存ほぞん变量 tf.train.Saver.restore(sess, save_path) 恢复变量 tf.train.Saver.last_checkpoints れつ最近さいきん删除てきcheckpoint ぶん件名けんめい tf.train.Saver.set_last_checkpoints(last_checkpoints) 设置checkpointぶん件名けんめいれつひょう tf.train.Saver.set_last_checkpoints_with_time(last_checkpoints_with_time) 设置checkpointぶん件名けんめいれつひょう时间戳

设备

[编辑]
with tf.device("/gpu:0"): 指定してい一个计算设备,作用さよういきちゅうてきだい码在该设备上执行。

れい

[编辑]

れい:Hello World。

import tensorflow as tf
hw = tf.constant("Hello World")
with tf.Session() as sess:
 print(sess.run(hw))

れい:两个のり相乘そうじょう

import tensorflow as tf

# Build a dataflow graph.
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)

# Construct a `Session` to execute the graph.
with tf.Session() as sess:
  # Execute the graph and store the value that `e` represents in `result`.
  result = sess.run(e)

print(result)

れい使用しようFeedingざい执行时传にゅうさんすう

import tensorflow as tf

# Build a dataflow graph.
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)

# Construct a `Session` to execute the graph.
sess = tf.Session()

# Execute the graph and store the value that `e` represents in `result`.
result = sess.run(e,feed_dict={c:[[0.0, 0.0], [3.0, 4.0]]})
print(result)
sess.close()

TensorFlowてき一大特色是其图中的节点可以是带状态的。

れい使用しよううらない <source lang="python"> input_placeholder = tf.placeholder(tf.int32) sess = tf.Session() print (sess.run(input_placeholder, feed_dict={input_placeholder: 2})) sess.close() </syntaxhighlight>

れい使用しよう变量、给变りょう赋值

使用しようtf.get_variable()创建变量。tf.get_variable() てきぜん两个さんすう必需ひつじゅてき,其余さんすう选的。tf.get_variable(name,shape)。name 一个唯一标识这个变量对象的字符串。它必须相对于全局ぜんきょく图是唯一ゆいいつてき所以ゆえんようあかりりょう使用しよう过的所有しょゆう命名めいめい,确保ぼつゆうじゅう复。shape あずか张量形状けいじょう对应てき整数せいすうすう组,按顺じょごと个维ただゆういち个整すういち个 3x8 のり阵形じょう [3, 8]。よう创建いち个标りょう,就需よう使用しよう形状けいじょう为 [] てき空列くうれつひょうゆう两种はた值放にゅう变量てき方法ほうほうはつはじめ tf.assign()。はつはじめ应该声明せいめい(tf.constant_initializer)あずか执行はつはじめ(tf.global_variables_initializer)两种节点配合はいごう使用しよう

import tensorflow as tf
count_variable = tf.get_variable("count", [])
zero_node = tf.constant(0.)
assign_node = tf.assign(count_variable, zero_node)
sess = tf.Session()
sess.run(assign_node)
print (sess.run(count_variable))
 
const_init_node = tf.constant_initializer(0.)
count_variable1 = tf.get_variable("count1", [], initializer=const_init_node)
init = tf.global_variables_initializer()
sess.run(init)
print (sess.run(count_variable1))
sess.close()

れい:tf.Variable() tf.get_variable()いくわ别 <source lang="python"> import tensorflow as tf

with tf.variable_scope("scope1"):

   w1 = tf.get_variable("w1", shape=[])
   w2 = tf.Variable(0.0, name="w2")

with tf.variable_scope("scope1", reuse=True):

   w1_p = tf.get_variable("w1", shape=[])
   w2_p = tf.Variable(1.0, name="w2")

print(w1 is w1_p, w2 is w2_p)

  1. 输出
  2. True False

</syntaxhighlight>

れい:带状态的图

import tensorflow as tf

# Build a dataflow graph.
count = tf.Variable([0],trainable=False);
init_op = tf.global_variables_initializer()
update_count = count.assign_add(tf.constant([2]))

# Construct a `Session` to execute the graph.
sess = tf.Session()
sess.run(init_op)

for step in range(10):
    result = sess.run(update_count)
    print("step %d: count = %g" % (step,result))

sess.close()

れいはしご计算

import tensorflow as tf

# Build a dataflow graph.
filename_queue = tf.train.string_input_producer(['1.txt'],num_epochs=1)
reader = tf.TextLineReader()
key,value = reader.read(filename_queue)
num = tf.decode_csv(value,record_defaults=[[0]])
x = tf.Variable([0])
loss = x * num
grads = tf.gradients([loss],x)
grad_x = grads[0]

def train_fn(sess):
  train_fn.counter += 1
  result = sess.run(grad_x)
  print("step %d: grad = %g" % (train_fn.counter,result))

train_fn.counter = 0

sv = tf.train.Supervisor()
tf.train.basic_train_loop(sv,train_fn)

かり设1.txtてき内容ないよう为:

3
2
5
8

上述じょうじゅつほどじょてき输出应该为:

step 1: grad = 3
step 2: grad = 2
step 3: grad = 5
step 4: grad = 8