tensorflow函数笔记

-------------索引-------------

  1. cast
  2. get_variable
  3. embedding_lookup
  4. l2_loss
  5. xw_plus_b
  6. sigmoid_cross_entropy_with_logits
  7. trainable_variables
  8. reshape
  9. transpose
  10. squeeze
  11. dropout
  12. tf.sequence_mask

1. cast

cast(x,dtype,name=None)

将x的数据格式转化成dtype数据类型.例如,原来x的数据格式是bool,那么将其转化成float以后,就能够将其转化成0和1的序列。反之也可以

import sys
import tensorflow as tf
print(sys.version)

a = tf.Variable([1.0,1.3,2.1,3.41,4.51])
b = tf.cast(a>3,dtype=tf.bool)
c = tf.cast(a>3,dtype=tf.int8)
e = tf.cast(a<2,dtype=tf.float32)
d = tf.cast(a,dtype=tf.int8)

sess = tf.Session()
sess.run(tf.initialize_all_variables())
print(sess.run(b))
print(sess.run(c))
print(sess.run(e))
print(sess.run(d))

结果:

[False False False True True]
[0 0 0 1 1]
[1. 1. 0. 0. 0.]
[1 1 2 3 4]

2. get_variable

TensorFlow一般有两种方法创建变量:

  1. 通过tf.Variable()

weights = tf.Variable(tf.random_normal([784, 200]), name='weights')

  1. 通过tf.get_variable()

weights = tf.get_variable(name='weights', shape=[784, 200], initializer=tf.random_normal_initializer())

3.embedding_lookup()

tf.nn.embedding_lookup()就是根据input_ids中的id,寻找embeddings中的第id行。比如input_ids=[1,3,5],则找出embeddings中第1,3,5行,组成一个tensor返回。

import tensorflow as tf
import numpy as np

input_ids = tf.placeholder(tf.int32, shape=[None], name="input_ids")
embedding = tf.Variable(np.identity(5, dtype=np.int32))
input_embedding = tf.nn.embedding_lookup(embedding, input_ids)

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print("embedding=\n", embedding.eval())
print("input_embedding=\n", sess.run(input_embedding, feed_dict={input_ids: [1, 2, 3, 0, 3, 2, 1]}))

结果:

embedding=
 [[1 0 0 0 0]
 [0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]
input_embedding=
 [[0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [1 0 0 0 0]
 [0 0 0 1 0]
 [0 0 1 0 0]
 [0 1 0 0 0]]
[Finished in 3.8s]

4. l2_loss

损失运算 用于测量两个张量之间或张量与0之间的误差。 这些可以用于测量回归任务中的网络的精确度,或用于正则化的目的(权重衰减)。 
tf.nn.l2_loss可以作为一个正则项

tf.nn.l2_loss(t, name=None)

tf.nn.l2_loss形如1/2Σw2,一般用于优化的目标函数中的正则项,防止参数太多复杂容易过拟合。
这个函数的作用是利用 L2 范数来计算张量的误差值,但是没有开方并且只取 L2 范数的值的一半,具体如下:

output = sum(t ** 2) / 2

输入参数:
t: 一个Tensor。一般情况下,数据维度是二维的。但是,数据维度可以取任意维度。
name: 为这个操作取个名字。
输出参数:
一个 Tensor,数据类型和t相同,是一个标量。

import tensorflow as tf
a=tf.constant([1,2,3],dtype=tf.float32)
b=tf.constant([[1,1],[2,2],[3,3]],dtype=tf.float32)
with tf.Session() as sess:
    print('a:')
    print(sess.run(tf.nn.l2_loss(a)))
    print('b:')
    print(sess.run(tf.nn.l2_loss(b)))
    sess.close()

结果:

a:
7.0
b:
14.0

5. xw_plus_b

tf.nn.xw_plus_b(x,weights,biases,name=None)

用来计算matmul(x, weights) + biases。维度通常为:batch,out_units

6.sigmoid_cross_entropy_with_logits

sigmoid_cross_entropy_with_logits(_sentinel=None,labels=None,logits=None,name=None)

logits和labels必须具有相同的类型和shape。
参数:
_sentinel:用于防止positional参数。内部的,不要使用。
labels:一个Tensor,与logits具有相同的类型和shape。
logits:一个Tensor,类型为float32或float64。
name:操作的名称(可选)。
返回:
与具有分量logistic损失的logits有着相同shape的Tensor。
可能引发的异常:
ValueError:如果logits和labels没有相同的shape。

7. trainable_variables

返回使用 trainable=True 创建的所有变量.

传递 trainable=True 时,Variable() 构造函数会自动将新变量添加到图形集合 GraphKeys.TRAINABLE_VARIABLES 中.这个便利函数返回该集合的内容.

函数参数:

scope:(可选)一个字符串.如果提供,对结果列表进行过滤,以便只包含 name 属性与使用 re.match 匹配 scope 的项.如果提供了作用域,则不会返回没有 name 属性的项目.这种 re.match 选择意味着 scope 没有特殊的令牌通过前缀进行过滤.
函数返回值:

tf.trainable_variables函数返回 Variable 对象的列表.

8.reshape

# 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]]

# tensor 't' is [[[1, 1], [2, 2]],
#                [[3, 3], [4, 4]]]
# tensor 't' has shape [2, 2, 2]
reshape(t, [2, 4]) ==> [[1, 1, 2, 2],
                        [3, 3, 4, 4]]

# tensor 't' is [[[1, 1, 1],
#                 [2, 2, 2]],
#                [[3, 3, 3],
#                 [4, 4, 4]],
#                [[5, 5, 5],
#                 [6, 6, 6]]]
# tensor 't' has shape [3, 2, 3]
# pass '[-1]' to flatten 't'
reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]

# -1 can also be used to infer the shape

# -1 is inferred to be 9:
reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]
# -1 is inferred to be 2:
reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]
# -1 is inferred to be 3:
reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],
                              [2, 2, 2],
                              [3, 3, 3]],
                             [[4, 4, 4],
                              [5, 5, 5],
                              [6, 6, 6]]]

# tensor 't' is [7]
# shape `[]` reshapes to a scalar
reshape(t, []) ==> 7

9.transpose

置换 a,根据 perm 重新排列尺寸.
返回的张量的维度 i 将对应于输入维度 perm[i].如果 perm 没有给出,它被设置为(n-1 ... 0),其中 n 是输入张量的秩.因此,默认情况下,此操作在二维输入张量上执行常规矩阵转置.如果共轭为 True,并且 a.dtype 是 complex64 或 complex128,那么 a 的值是共轭转置和.

例如:

x = tf.constant([[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]]

# If x is complex, setting conjugate=True gives the conjugate transpose
x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],
                 [4 + 4j, 5 + 5j, 6 + 6j]])
tf.transpose(x, conjugate=True)  # [[1 - 1j, 4 - 4j],
                                 #  [2 - 2j, 5 - 5j],
                                 #  [3 - 3j, 6 - 6j]]

# 'perm' is more useful for n-dimensional tensors, for n > 2
x = tf.constant([[[ 1,  2,  3],
                  [ 4,  5,  6]],
                 [[ 7,  8,  9],
                  [10, 11, 12]]])

# Take the transpose of the matrices in dimension-0
# (this common operation has a shorthand `matrix_transpose`)
tf.transpose(x, perm=[0, 2, 1])  # [[[1,  4],
                                 #   [2,  5],
                                 #   [3,  6]],
                                 #  [[7, 10],
                                 #   [8, 11],
                                 #   [9, 12]]]

函数参数:

a:一个 Tensor.
perm:a 的维数的排列.
name:操作的名称(可选).
conjugate:可选 bool,将其设置为 True 在数学上等同于 tf.conj(tf.transpose(input)).
返回:

tf.transpose 函数返回一个转置 Tensor.

10.squeeze

从张量形状中移除大小为1的维度.

给定一个张量 input,该操作返回一个与已经移除的所有大小为1的维度具有相同类型的张量.如果您不想删除所有大小为1的维度,则可以通过指定 axis 来删除特定的大小为1的维度.

如本例所示:

# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
tf.shape(tf.squeeze(t))  # [2, 3]

或者,要删除特定的大小为1的维度:

# 't' is a tensor of shape [1, 2, 1, 3, 1, 1]
tf.shape(tf.squeeze(t, [2, 4]))  # [1, 2, 3, 1]

函数参数:

input:A Tensor.该input挤.
axis:一个可选列表ints.默认为[].如果指定,只能挤压列出的尺寸.维度索引从0开始.压缩非1的维度是错误的.必须在范围内[-rank(input), rank(input)).
name:操作的名称(可选).
squeeze_dims:现在是轴的已弃用的关键字参数.
函数返回值:

一Tensor.与.类型相同input.包含与之相同的数据input,但删除了一个或多个尺寸为1的尺寸.

可能引发的异常:

ValueError:当两个squeeze_dims和axis指定.

11.dropout

tf.nn.dropout(x,keep_prob,noise_shape=None,seed=None,name=None)

该函数用于计算dropout.

使用概率keep_prob,输出按照1/keep_prob的比例放大输入元素,否则输出0.缩放是为了使预期的总和不变.

默认情况下,每个元素都是独立保留或删除的.如果已指定noise_shape,则必须将其广播为x的形状,并且只有具有noise_shape[i] == shape(x)[i]的维度才作出独立决定.

例如,如果shape(x) = [k, l, m, n]并且noise_shape = [k, 1, 1, n],则每个批处理和通道组件将独立保存,并且每个行和列将保留或不保留在一起.

参数:

x:一个浮点型Tensor.
keep_prob:一个标量Tensor,它与x具有相同类型.保留每个元素的概率.
noise_shape:类型为int32的1维Tensor,表示随机产生的保持/丢弃标志的形状.
seed:一个Python整数.用于创建随机种子.
name:此操作的名称(可选).
返回:

该函数返回与x具有相同形状的Tensor.

可能引发的异常:

ValueError:如果keep_prob不在(0, 1]或如果x不是浮点型Tensor.

12. sequence_mask

sequence_mask(lengths,maxlen=None,dtype=tf.bool,name=None)

返回一个表示每个单元的前N个位置的mask张量.
如果lengths的形状为[d_1, d_2, ..., d_n],由此产生的张量mask有dtype类型和形状[d_1, d_2, ..., d_n, maxlen],并且:
mask[i_1, i_2, ..., i_n, j] = (j < lengths[i_1, i_2, ..., i_n])
示例如下:

tf.sequence_mask([1, 3, 2], 5)  # [[True, False, False, False, False],
                                #  [True, True, True, False, False],
                                #  [True, True, False, False, False]]

tf.sequence_mask([[1, 3],[2,0]])  # [[[True, False, False],
                                  #   [True, True, True]],
                                  #  [[True, True, False],
                                  #   [False, False, False]]]

函数参数
lengths:整数张量,其所有值小于等于maxlen.
maxlen:标量整数张量,返回张量的最后维度的大小;默认值是lengths中的最大值.
dtype:结果张量的输出类型.
name:操作的名字.
函数返回值
形状为lengths.shape + (maxlen,)的mask张量,投射到指定的dtype.

函数中可能存在的异常
ValueError:如果maxlen不是标量.

posted @ 2019-11-07 21:39  "kisetsu  阅读(263)  评论(0编辑  收藏  举报