tensorflow学习之tensor操作函数

1.定义各种数组

a = np.array([[1,2,3],[4,5,6]])
# 数组转tensor:数组a,  tensor_a=tf.convert_to_tensor(a)
# tensor转数组:tensor b, array_b=b.eval()
b = tf.convert_to_tensor(a) # 将np定义数组转化为tensor

c = tf.constant([[1,2,3],[4,5,6]])

d_list = [[1,2,3],[4,5,6]]

2.tf.shape(tensor)     tensor.tf.get_shape()

# tf.shape()很显然这个是获取张量的大小的, tf.shape()返回的是一个tensor,要想知道是多少,必须通过sess.run()
# x.get_shape(),只有tensor才可以使用这种方法,返回的是一个元组,不能放到sess.run()里面,这个里面只能放operation和tensor
# c.get_shape().as_list()返回一个list
import tensorflow as tf
import numpy as np

a = np.array([[1,2,3],[4,5,6]])
b = tf.convert_to_tensor(a) # 将np定义数组转化为tensor

c = tf.constant([[1,2,3],[4,5,6]])

d_list = [[1,2,3],[4,5,6]]

# x.get_shape(),只有tensor才可以使用这种方法,返回的是一个元组,不能放到sess.run()里面,这个里面只能放operation和tensor
# c.get_shape().as_list()返回一个list
print(c.get_shape())
print(c.get_shape().as_list())

with tf.Session() as sess:
    print(sess.run(tf.shape(a)))  # tf.shape()很显然这个是获取张量的大小的
    print(sess.run(tf.shape(c)))  # tf.shape()返回的是一个tensor,要想知道是多少,必须通过sess.run()
    print(sess.run(tf.shape(d_list)))

output:
(2, 3)
[2, 3]

[2 3]
[2 3]
[2 3]

3.tf.transpose()   tf.reshape()

x = tf.transpose(x, [0, 3, 1, 2])#交换维度(b,2c,h,w)
x = tf.reshape(x, (-1, int(x_shape[1]), int(x_shape[2]), 2))#(bc,h,w,2)

4.tf.expand_dims(input, dim, name=None)

将tensor增加维度,例如(对图像维度降到二维做特定操作后,要还原成四维[batch, height, width, channels],前后各增加一维)

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

# 't2' is a tensor of shape [2, 3, 5]
shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]

one_img = tf.expand_dims(one_img, 0)
one_img = tf.expand_dims(one_img, -1) #-1表示最后一维

5. tf.tile()函数

tensorflow中的tile()函数是用来对张量(Tensor)进行扩展的,其特点是对当前张量内的数据进行一定规则的复制。最终的输出张量维度不变

tf.tile(
    input,
    multiples,
    name=None
)

with tf.Graph().as_default():
    a = tf.constant([1,2],name='a') 
    b = tf.tile(a,[3])
    sess = tf.Session()
    print(sess.run(b))
# 对[1,2]的同一维度上复制3次,multiples参数维度与input维度应一致,结果如下:

# [1 2 1 2 1 2]


with tf.Graph().as_default():
    a = tf.constant([[1,2],[3,4]],name='a')   
    b = tf.tile(a,[2,3])
    sess = tf.Session()
    print(sess.run(b))

# 输出:
[[1 2 1 2 1 2]
 [3 4 3 4 3 4]
 [1 2 1 2 1 2]
 [3 4 3 4 3 4]]

6. tf.cast()

"""tf.cast()函数的作用是执行 tensorflow 中张量数据类型转换,比如读入的图片如果是int8类型的,一般在要在训练前把图像的数据格式转换为float32。

cast定义:

cast(x, dtype, name=None)
第一个参数 x:   待转换的数据(张量)
第二个参数 dtype: 目标数据类型
第三个参数 name: 可选参数,定义操作的名称

int32转换为float32:
"""

import tensorflow as tf
 
t1 = tf.Variable([1,2,3,4,5])
t2 = tf.cast(t1,dtype=tf.float32)
 
print 't1: {}'.format(t1)
print 't2: {}'.format(t2)
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(t2)
    print t2.eval()
    # print(sess.run(t2))
输出:

t1: <tf.Variable 'Variable:0' shape=(5,) dtype=int32_ref>
t2: Tensor("Cast:0", shape=(5,), dtype=float32)
[ 1.  2.  3.  4.  5.]

7. tf.concat与tf.stack

tf.concat是沿某一维度拼接shape相同的张量,拼接生成的新张量维度不会增加。而tf.stack是在新的维度上拼接,拼接后维度加1

import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6]])
b = tf.constant([[7,8,9],[10,11,12]])
ab1 = tf.concat([a,b],axis=0)
ab2 = tf.stack([a,b], axis=0)
sess = tf.Session()
print(sess.run(ab1))
print(sess.run(ab2))
print ab1
print ab2
"""
结果:

[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]#ab1的值

[[[ 1 2 3]
[ 4 5 6]]

[[ 7 8 9]
[10 11 12]]]#ab2的值
Tensor(“concat:0”, shape=(4, 3), dtype=int32)#ab1的属性
Tensor(“stack:0”, shape=(2, 2, 3), dtype=int32)#ab2的属性
由上可知:由于axis=0,表示在第一维连接。对tf.concat来说连接后张量的第一维是在外层中括号内,将两个张量原来所有第一维内的元素(如[1 2 3],[7 8 9 ]等)连接。而tf.stack需要先将原二维张量扩展成三维张量,在扩展后张量的第一维上将原两个二维张量连接。

若axis=1,结果为:

[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]

[[[ 1 2 3]
[ 7 8 9]]

[[ 4 5 6]
[10 11 12]]]
Tensor(“concat:0”, shape=(2, 6), dtype=int32)
Tensor(“stack:0”, shape=(2, 2, 3), dtype=int32)
同上:axis=1,表示在第二维连接。对tf.concat来说连接后张量的第二维是在内层中括号内,将两个张量原来所有第二维内的元素(如1 ,2, 3,7,8,9等)连接。tf.stack先将原二维张量扩展成三维张量,在扩展后张量的第二维上将两个原张量的相对应的元素(如[1 2 3]和[ 7 8 9])连接。

若axis=2,tf.concat会报错(因为tf.concat不增加维数)。tf.stack结果如下:

[[[ 1 7]
[ 2 8]
[ 3 9]]

[[ 4 10]
[ 5 11]
[ 6 12]]]
Tensor(“stack:0”, shape=(2, 3, 2), dtype=int32)
同上:axis=2,表示在第三维连接。tf.stack先将原二维张量扩展成三维张量,在扩展后张量的第三维上将两个原张量的相对应的元素(如1和7,2和8,3和9等 )连接。
"""

8.tf.gather_nd()

tf.gather_nd(
    params,
    indices,
    name=None
)

按照indices的格式从params中抽取切片(合并为一个Tensor)
indices是一个K维整数Tensor

import tensorflow as tf

a = tf.Variable([[1, 2, 3, 4, 5],
                 [6, 7, 8, 9, 10],
                 [11, 12, 13, 14, 15]])
index_a1 = tf.Variable([[0, 2], [0, 4], [2, 2]])  # 随便选几个
index_a2 = tf.Variable([0, 1])  # 0行1列的元素——2
index_a3 = tf.Variable([[0], [1]])  # [第0行,第1行]
index_a4 = tf.Variable([0])  # 第0行


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(tf.gather_nd(a, index_a1)))
    print(sess.run(tf.gather_nd(a, index_a2)))
    print(sess.run(tf.gather_nd(a, index_a3)))
    print(sess.run(tf.gather_nd(a, index_a4)))

"""
输出:
[ 3  5 13]
2
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]]
[1 2 3 4 5]
"""

9.tf.argmax()

tf.argmax(input,axis)根据axis取值的不同返回每行或者每列最大值的索引

  • axis = 0: 
      axis=0时比较每一列的元素,将每一列最大元素所在的索引记录下来,最后输出每一列最大元素所在的索引数组。

axis = 1: 
  axis=1的时候,将每一行最大元素所在的索引记录下来,最后返回每一行最大元素所在的索引数组

test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
np.argmax(test, 0)   #输出:array([3, 3, 1]
np.argmax(test, 1)   #输出:array([2, 2, 0, 0]123


test[0] = array([1, 2, 3])
test[1] = array([2, 3, 4])
test[2] = array([5, 4, 3])
test[3] = array([8, 7, 2])
# output   :    [3, 3, 1]   

test[0] = array([1, 2, 3])  #2
test[1] = array([2, 3, 4])  #2
test[2] = array([5, 4, 3])  #0
test[3] = array([8, 7, 2])  #0

这是里面都是数组长度一致的情况,如果不一致,axis最大值为最小的数组长度-1,超过则报错。 
当不一致的时候,axis=0的比较也就变成了每个数组的和的比较。

10. tf.clip_by_value(V, min, max)

tf.clip_by_value(V, min, max), 截取V使之在min和max之间

import tensorflow as tf

import numpy as np

v = tf.constant([[1.0, 2.0, 4.0],[4.0, 5.0, 6.0]])
result = tf.clip_by_value(v, 2.5, 4.5)


with tf.Session() as sess:
    print(sess.run(result))

'''
输出

[[ 2.5  2.5  4. ]

 [ 4.   4.5  4.5]]
'''

11.twnsorflow数学运算

  • 相同大小 Tensor 之间的任何算术运算都会将运算应用到元素级
  • 不同大小 Tensor(要求dimension 0 必须相同) 之间的运算叫做广播(broadcasting)
  • Tensor 与 Scalar(0维 tensor) 间的算术运算会将那个标量值传播到各个元素
  • Note: TensorFLow 在进行数学运算时,一定要求各个 Tensor 数据类型一致

(基本数学函数)

# 算术操作符:+ - * / % 
tf.add(x, y, name=None)        # 加法(支持 broadcasting)
tf.subtract(x, y, name=None)   # 减法
tf.multiply(x, y, name=None)   # 乘法, 点积
tf.divide(x, y, name=None)     # 浮点除法, 返回浮点数(python3 除法)
tf.mod(x, y, name=None)        # 取余
 
 
# 幂指对数操作符:^ ^2 ^0.5 e^ ln 
tf.pow(x, y, name=None)        # 幂次方
tf.square(x, name=None)        # 平方
tf.sqrt(x, name=None)          # 开根号,必须传入浮点数或复数
tf.exp(x, name=None)           # 计算 e 的次方
tf.log(x, name=None)           # 以 e 为底,必须传入浮点数或复数
 
 
# 取符号、负、倒数、绝对值、近似、两数中较大/小的
tf.negative(x, name=None)      # 取负(y = -x).
tf.sign(x, name=None)          # 返回 x 的符号
tf.reciprocal(x, name=None)    # 取倒数
tf.abs(x, name=None)           # 求绝对值
tf.round(x, name=None)         # 四舍五入
tf.ceil(x, name=None)          # 向上取整
tf.floor(x, name=None)         # 向下取整
tf.rint(x, name=None)          # 取最接近的整数 
tf.maximum(x, y, name=None)    # 返回两tensor中的最大值 (x > y ? x : y)
tf.minimum(x, y, name=None)    # 返回两tensor中的最小值 (x < y ? x : y)
 
 
# 三角函数和反三角函数
tf.cos(x, name=None)    
tf.sin(x, name=None)    
tf.tan(x, name=None)    
tf.acos(x, name=None)
tf.asin(x, name=None)
tf.atan(x, name=None)   
 
 
# 其它
tf.div(x, y, name=None)  # python 2.7 除法, x/y-->int or x/float(y)-->float
tf.truediv(x, y, name=None) # python 3 除法, x/y-->float
tf.floordiv(x, y, name=None)  # python 3 除法, x//y-->int
tf.realdiv(x, y, name=None)
tf.truncatediv(x, y, name=None)
tf.floor_div(x, y, name=None)
tf.truncatemod(x, y, name=None)
tf.floormod(x, y, name=None)
tf.cross(x, y, name=None)
tf.add_n(inputs, name=None)  # inputs: A list of Tensor objects, each with same shape and type
tf.squared_difference(x, y, name=None) 

(矩阵数学函数)

# 矩阵乘法(tensors of rank >= 2)
tf.matmul(a, b, transpose_a=False, transpose_b=False,    adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None)
 
 
# 转置,可以通过指定 perm=[1, 0] 来进行轴变换
tf.transpose(a, perm=None, name='transpose')
 
 
# 在张量 a 的最后两个维度上进行转置
tf.matrix_transpose(a, name='matrix_transpose')
# Matrix with two batch dimensions, x.shape is [1, 2, 3, 4]
# tf.matrix_transpose(x) is shape [1, 2, 4, 3]
 
 
# 求矩阵的迹
tf.trace(x, name=None)
 
 
# 计算方阵行列式的值
tf.matrix_determinant(input, name=None)
 
 
# 求解可逆方阵的逆,input 必须为浮点型或复数
tf.matrix_inverse(input, adjoint=None, name=None)
 
 
# 奇异值分解
tf.svd(tensor, full_matrices=False, compute_uv=True, name=None)
 
 
# QR 分解
tf.qr(input, full_matrices=None, name=None)
 
 
# 求张量的范数(默认2)
tf.norm(tensor, ord='euclidean', axis=None, keep_dims=False, name=None)
 
 
 
# 构建一个单位矩阵, 或者 batch 个矩阵,batch_shape 以 list 的形式传入
tf.eye(num_rows, num_columns=None, batch_shape=None, dtype=tf.float32, name=None)
# Construct one identity matrix.
tf.eye(2)
==> [[1., 0.],
     [0., 1.]]
 
# Construct a batch of 3 identity matricies, each 2 x 2.
# batch_identity[i, :, :] is a 2 x 2 identity matrix, i = 0, 1, 2.
batch_identity = tf.eye(2, batch_shape=[3])
 
# Construct one 2 x 3 "identity" matrix
tf.eye(2, num_columns=3)
==> [[ 1.,  0.,  0.],
     [ 0.,  1.,  0.]]
 
 
# 构建一个对角矩阵,rank = 2*rank(diagonal)
tf.diag(diagonal, name=None)
# '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
tf.matrix_diag
tf.matrix_diag_part
tf.matrix_band_part
tf.matrix_set_diag
tf.cholesky
tf.cholesky_solve
tf.matrix_solve
tf.matrix_triangular_solve
tf.matrix_solve_ls
tf.self_adjoint_eig
tf.self_adjoint_eigvals

(Reduction:reduce various dimensions of a tensor)

# 计算输入 tensor 所有元素的和,或者计算指定的轴所有元素的和
tf.reduce_sum(input_tensor, axis=None, keep_dims=False, name=None)
# 'x' is [[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
 
 
# 计算输入 tensor 所有元素的均值/最大值/最小值/积/逻辑与/或
# 或者计算指定的轴所有元素的均值/最大值/最小值/积/逻辑与/或(just like reduce_sum)
tf.reduce_mean(input_tensor, axis=None, keep_dims=False, name=None)
tf.reduce_max(input_tensor, axis=None, keep_dims=False, name=None)
tf.reduce_min(input_tensor, axis=None, keep_dims=False, name=None)
tf.reduce_prod(input_tensor, axis=None, keep_dims=False, name=None)
tf.reduce_all(input_tensor, axis=None, keep_dims=False, name=None)  # 全部满足条件
tf.reduce_any(input_tensor, axis=None, keep_dims=False, name=None) #至少有一个满足条件
 
 
-------------------------------------------
# 分界线以上和 Numpy 中相应的用法完全一致
-------------------------------------------
 
 
 
# inputs 为一 list, 计算 list 中所有元素的累计和,
# tf.add(x, y, name=None)只能计算两个元素的和,此函数相当于扩展了其功能
tf.accumulate_n(inputs, shape=None, tensor_dtype=None, name=None)
 
 
# Computes log(sum(exp(elements across dimensions of a tensor)))
tf.reduce_logsumexp(input_tensor, axis=None, keep_dims=False, name=None)
 
 
# Computes number of nonzero elements across dimensions of a tensor
tf.count_nonzero(input_tensor, axis=None, keep_dims=False, name=None)

(Scan:perform scans (running totals) across one axis of a tensor)

# Compute the cumulative sum of the tensor x along axis
tf.cumsum(x, axis=0, exclusive=False, reverse=False, name=None)
# Eg:
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]
 
 
# Compute the cumulative product of the tensor x along axis
tf.cumprod(x, axis=0, exclusive=False, reverse=False, name=None)

(Segmentation沿着第一维(x 轴)根据 segment_ids(list)分割好相应的数据后再进行操作)

# Computes the sum/mean/max/min/prod along segments of a tensor
tf.segment_sum(data, segment_ids, name=None)
# Eg:
m = tf.constant([5,1,7,2,3,4,1,3])
s_id = [0,0,0,1,2,2,3,3]
s.run(tf.segment_sum(m, segment_ids=s_id))
>array([13,  2,  7,  4], dtype=int32)
 
tf.segment_mean(data, segment_ids, name=None)
tf.segment_max(data, segment_ids, name=None)
tf.segment_min(data, segment_ids, name=None)
tf.segment_prod(data, segment_ids, name=None)
 
 
# 其它
tf.unsorted_segment_sum
tf.sparse_segment_sum
tf.sparse_segment_mean
tf.sparse_segment_sqrt_n

(序列比较与索引提取)

# 比较两个 list 或者 string 的不同,并返回不同的值和索引
tf.setdiff1d(x, y, index_dtype=tf.int32, name=None)
 
 
# 返回 x 中的唯一值所组成的tensor 和原 tensor 中元素在现 tensor 中的索引
tf.unique(x, out_idx=None, name=None)
 
 
# x if condition else y, condition 为 bool 类型的,可用tf.equal()等来表示
# x 和 y 的形状和数据类型必须一致
tf.where(condition, x=None, y=None, name=None)
 
 
# 返回沿着坐标轴方向的最大/最小值的索引
tf.argmax(input, axis=None, name=None, output_type=tf.int64)
tf.argmin(input, axis=None, name=None, output_type=tf.int64)
 
 
# x 的值当作 y 的索引,range(len(x)) 索引当作 y 的值
# y[x[i]] = i for i in [0, 1, ..., len(x) - 1]
tf.invert_permutation(x, name=None)
 
 
# 其它
tf.edit_distance

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值