Tensorflow - tf常用函数使用,持续更新中

本人较懒,故间断更新下常用的tf函数以供参考:

reduce_sum( ) 个人理解是降维求和函数,在 tensorflow 里面,计算的都是 tensor,可以通过调整 axis 的维度来控制求和维度。

参数:

  • input_tensor:要减少的张量.应该有数字类型.
  • axis:要减小的尺寸.如果为None(默认),则缩小所有尺寸.必须在范围[-rank(input_tensor), rank(input_tensor))内.
  • keep_dims:如果为true,则保留长度为1的缩小尺寸.
  • name:操作的名称(可选).
  • reduction_indices:axis的废弃的名称.

返回:

该函数返回减少的张量.

numpy兼容性

相当于np.sum;

此处axis为tensor的阶数,使用该函数将消除tensor指定的阶axis,同时将该阶下的所有的元素进行累积求和操作。

看一个官方示例:

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

此函数计算一个张量的各个维度上元素的总和.

函数中的input_tensor是按照axis中已经给定的维度来减少的;除非 keep_dims 是true,否则张量的秩将在axis的每个条目中减少1;如果keep_dims为true,则减小的维度将保留为长度1.

如果axis没有条目,则缩小所有维度,并返回具有单个元素的张量.

二、tf.ones_like | tf.zeros_like

tf.ones_like(tensor,dype=None,name=None)

tf.zeros_like(tensor,dype=None,name=None)

新建一个与给定的tensor类型大小一致的tensor,其所有元素为1和0,示例如下:

tensor=[[1, 2, 3], [4, 5, 6]] 
x = tf.ones_like(tensor) 
print(sess.run(x))

#[[1 1 1],
# [1 1 1]]

三、tf.reduce_mean()

tf.reduce_mean 函数用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,主要用作降维或者计算tensor(图像)的平均值。

reduce_mean(input_tensor,
                axis=None,
                keep_dims=False,
                name=None,
                reduction_indices=None)

第一个参数input_tensor: 输入的待降维的tensor;

第二个参数axis: 指定的轴,如果不指定,则计算所有元素的均值;

第三个参数keep_dims:是否降维度,设置为True,输出的结果保持输入tensor的形状,设置为False,输出结果会降低维度;

第四个参数name: 操作的名称;

第五个参数 reduction_indices:在以前版本中用来指定轴,已弃用;

以一个维度是2,形状是[2,3]的tensor举例:

import tensorflow as tf
 
x = [[1,2,3],
      [1,2,3]]
 
xx = tf.cast(x,tf.float32)
 
mean_all = tf.reduce_mean(xx, keep_dims=False)
mean_0 = tf.reduce_mean(xx, axis=0, keep_dims=False)
mean_1 = tf.reduce_mean(xx, axis=1, keep_dims=False)
 
 
with tf.Session() as sess:
    m_a,m_0,m_1 = sess.run([mean_all, mean_0, mean_1])
 
print m_a    # output: 2.0
print m_0    # output: [ 1.  2.  3.]
print m_1    #output:  [ 2.  2.]

如果设置保持原来的张量的维度,keep_dims=True ,结果:

print m_a    # output: [[ 2.]]
print m_0    # output: [[ 1.  2.  3.]]
print m_1    #output:  [[ 2.], [ 2.]]
 
 

类似的函数还有:

  • tf.reduce_sum :计算tensor指定轴方向上的所有元素的累加和;
  • tf.reduce_max : 计算tensor指定轴方向上的各个元素的最大值;
  • tf.reduce_all : 计算tensor指定轴方向上的各个元素的逻辑和(and运算);
  • tf.reduce_any: 计算tensor指定轴方向上的各个元素的逻辑或(or运算);

四、tf.concat与tf.stack/unstack( )

tf.concat相当于numpy中的np.concatenate函数,用于将两个张量在某一个维度(axis)合并起来,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab1 = tf.concat([a,b], axis=0) # shape(4,3)
ab2 = tf.concat([a,b], axis=1) # shape(2,6)

tf.stack其作用类似于tf.concat,都是拼接两个张量,而不同之处在于,tf.concat拼接的是两个shape完全相同的张量,并且产生的张量的阶数不会发生变化,而tf.stack则会在新的张量阶上拼接,产生的张量的阶数将会增加,增加的那一维的数量为拼接的张量的个数,如两个张量stack就为2,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=0) # shape (2,2,3)

改变参数axis为2,有:

import tensorflow as tf
a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=2) # shape (2,3,2)
 

所以axis是决定其层叠(stack)张量的维度方向的。

tf.unstacktf.stack的操作相反,是将一个高阶数的张量在某个axis上分解为低阶数的张量,例如:

a = tf.constant([[1,2,3],[3,4,5]]) # shape (2,3)
b = tf.constant([[7,8,9],[10,11,12]]) # shape (2,3)
ab = tf.stack([a,b], axis=0) # shape (2,2,3)

a1 = tf.unstack(ab, axis=0)

其a1的输出为

[<tf.Tensor 'unstack_1:0' shape=(2, 3) dtype=int32>,
 <tf.Tensor 'unstack_1:1' shape=(2, 3) dtype=int32>]

四、tf.reshape()

tf.reshape(tensor,shape,name=None)

函数的作用是将tensor变换为参数shape形式,其中的shape为一个列表形式,特殊的是列表可以实现逆序的遍历,即list(-1).-1所代表的含义是我们不用亲自去指定这一维的大小,函数会自动进行计算,但是列表中只能存在一个-1。(如果存在多个-1,就是一个存在多解的方程)

下面就说一下reshape是如何进行矩阵的变换的,其简单的流程就是:

将矩阵t变换为一维矩阵,然后再对矩阵的形式进行更改就好了。

接下来是具体的例子,创建一个一维的数组:

>>>import numpy as np
>>>a= np.array([1,2,3,4,5,6,7,8])
>>>a
array([1,2,3,4,5,6,7,8])
>>>

使用reshape()方法来更改数组的形状,使得数组成为一个二维的数组:(数组中元素的个数是2×4=8)

>>>d = a.reshape((2,4))
>>>d
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

进一步提升,可以得到一个三维的数组f:(注意数组中元素的个数时2×2×2=8)

>>>f = a.reshape((2,2,2))
>>>f
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])

注意:形状发生变化的原则时数组元素的个数是不能发生改变的,比如像下面这样的写法就会报错:

(元素的个数是2×2=4,所以会报错)

>>> e = a.shape((2,2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

-1 的应用:-1 表示不知道该填什么数字合适的情况下,可以选择,由python通过a和其他的值3推测出来,比如,这里的a 是二维的数组,数组中共有6个元素,当使用reshape()时,6/3=2,所以形成的是3行2列的二维数组,可以看出,利用reshape进行数组形状的转换时,一定要满足(x,y)中x×y=数组的个数。

>>>a = np.array([[1,2,3],[4,5,6]])
>>>np.reshape(a,(3,-1)) 
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.reshape(a,(1,-1))
array([[1, 2, 3, 4, 5, 6]])
>>> np.reshape(a,(6,-1))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
>>> np.reshape(a,(-1,1))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])