简单函数不给用例
tf.nn.moments
函数原型
def moments(
x,
axes,
shift=None, # pylint: disable=unused-argument
name=None,
keep_dims=False):
例子
img = tf.Variable(tf.random_normal([2,3,4]))
#keep_dims设置为True表示axes这个参数维度为1,其他维度和原来保持一样
#当为False,表示axes这个维度直接消失,维度减一。
mean, variance = tf.nn.moments(img, [-1], keep_dims=True)
mean1, variance1 = tf.nn.moments(img, [-1])
打印mean和mean1结果:
[[[-0.01752006]
[-0.3934618 ]
[ 0.5831194 ]]
[[-0.40659836]
[ 0.26763207]
[-0.7876693 ]]]
[[-0.01752006 -0.3934618 0.5831194 ]
[-0.40659836 0.26763207 -0.7876693 ]]
可以看出mean变成(2,3,1),而mean1为(2,3)
tf.concat
函数原型
def concat(values, axis, name="concat"):
values值是以tuple形式传入,两个需要进行concat的matrix,axis指示按什么维度concat
tf.nn.embedding_lookup
原型
def embedding_lookup(
params,
ids,
partition_strategy="mod",
name=None,
validate_indices=True, # pylint: disable=unused-argument
max_norm=None):
实现功能,从params中抽取ids号的vector组成一个matrix。
ids = tf.Variable(tf.ones([3], dtype=tf.int32))
lookup_table = tf.Variable(tf.random_normal([2,3], dtype=tf.float32))
outputs = tf.nn.embedding_lookup(lookup_table, ids)
打印lookup_table和outputs:
[[ 0.82692766 -0.6102561 0.36227643]
[-0.06371575 1.1494356 -0.27827913]]
[[-0.06371575 1.1494356 -0.27827913]
[-0.06371575 1.1494356 -0.27827913]
[-0.06371575 1.1494356 -0.27827913]]
可以看到outputs中,取了3次lookup_table[1]组成matrix
tf.tile
函数原型
def tile(input, multiples, name=None):
功能实现,对matrix的复制,inputs是要复制的,multiples是规则,为一个list,表示要复制的维度和次数,且multi的维度应等于inputs。
tf.slice
t = tf.constant([[[1, 1, 1],
[2, 2, 2]],
[[3, 3, 3],
[4, 4, 4]],
[[5, 5, 5],
[6, 6, 6]]])
b = tf.slice(t, [1, 0, 0], [2, 1, 2]) # tf.slice(要被slice的tensor, 开始的索引位置, 对应维度slice多少个)
结果:
[[[3 3]]
[[5 5]]]
tf.gather_nd
# 实现根据indices查找tensor的值
# tf.gather_nd(tensor, indices, name=None)
t = tf.constant([[[1, 1, 1],
[2, 2, 2]],
[[3, 3, 3],
[4, 9, 4]],
[[5, 5, 5],
[6, 6, 7]]])
b = tf.gather_nd(t, [[1,1,1],[2,1,2]]) # tf.gather_nd(要进行查找的tensor, 查找的索引位置)
结果:
[9 7]
tf.where
功能1、 tf.where(tensor),返回tensor种True所在的索引
功能2、 tf.where(tensor, a,b),将a,b,tensor的维度要一样,tensor种True的索引位置取a,False位置取b
这是一个很灵活的函数,可以和tf.equal函数使用;也可以和上面的tf.gather_nd + tf.equal配合使用用处完全不同
1. 与tf.equal:
y1 = [[0.0, 0.0, 1.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0, 0.0]] y2 = [[0.0, 0.0, 4.0, 0.0, 4.0], [0.0, 4.0, 0.0, 4.0, 0.0]]
b = tf.where(tf.equal(y1, 1.0), y2, y1)
结果:
[[0. 0. 4. 0. 4.]
[0. 4. 0. 4. 0.]]
2. 与tf.gather_nd:
y1 = [[0.0, 0.0, 1.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0, 0.0]] y2 = [[0.0, 0.0, 4.0, 0.0, 4.0], [0.0, 4.0, 0.0, 4.0, 0.0]]
t = tf.gather_nd(y2, tf.where(tf.equal(y1, 1.0)))
结果:
[4. 4. 4. 4.]
仔细对比#