TensorFLow 数学运算的示例代码


Posted in Python onApril 21, 2020

一、Tensor 之间的运算规则

  • 相同大小 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)分割好相应的数据后再进行操作

TensorFLow 数学运算的示例代码

# 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

到此这篇关于TensorFLow 数学运算的示例代码的文章就介绍到这了,更多相关TensorFLow 数学运算内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python转换摩斯密码示例
Feb 16 Python
使用httplib模块来制作Python下HTTP客户端的方法
Jun 19 Python
python实现逆序输出一个数字的示例讲解
Jun 25 Python
Python使用pyautogui模块实现自动化鼠标和键盘操作示例
Sep 04 Python
Python判断字符串是否xx开始或结尾的示例
Aug 08 Python
Python 使用 PyMysql、DBUtils 创建连接池提升性能
Aug 14 Python
通过celery异步处理一个查询任务的完整代码
Nov 19 Python
Python input函数使用实例解析
Nov 22 Python
Django项目基础配置和基本使用过程解析
Nov 25 Python
python开发飞机大战游戏
Jul 15 Python
Python matplotlib绘制条形统计图 处理多个实验多组观测值
Apr 21 Python
详解PyTorch模型保存与加载
Apr 28 Python
jupyter修改文件名方式(TensorFlow)
Apr 21 #Python
Python基于requests实现模拟上传文件
Apr 21 #Python
Ubuntu中配置TensorFlow使用环境的方法
Apr 21 #Python
基于jupyter代码无法在pycharm中运行的解决方法
Apr 21 #Python
如何基于python对接钉钉并获取access_token
Apr 21 #Python
python用TensorFlow做图像识别的实现
Apr 21 #Python
jupyter notebook 添加kernel permission denied的操作
Apr 21 #Python
You might like
分享一个超好用的php header下载函数
2014/01/31 PHP
jQuery+Ajax+PHP“喜欢”评级功能实现代码
2015/10/08 PHP
PHP模板引擎Smarty内建函数详解
2016/04/11 PHP
thinkphp自定义权限管理之名称判断方法
2017/04/01 PHP
利用PHP判断是手机移动端还是PC端访问的函数示例
2017/12/14 PHP
thinkPHP框架实现的简单计算器示例
2018/12/07 PHP
Smarty模板配置实例简析
2019/07/20 PHP
PHP多进程简单实例小结
2019/11/09 PHP
锋利的jQuery 要点归纳(二) jQuery中的DOM操作(下)
2010/03/23 Javascript
js 点击按钮弹出另一页,选择值后,返回到当前页
2010/05/26 Javascript
通过JQuery将DIV的滚动条滚动到指定的位置方便自动定位
2014/05/05 Javascript
基于NodeJS的前后端分离的思考与实践(四)安全问题解决方案
2014/09/26 NodeJs
详谈javascript中DOM的基本属性
2015/02/26 Javascript
浅谈jquery的map()和each()方法
2016/06/12 Javascript
jQuery图片前后对比插件beforeAfter用法示例【附demo源码下载】
2016/09/20 Javascript
Javascript使用uploadify来实现多文件上传
2016/11/16 Javascript
form表单数据封装成json格式并提交给服务器的实现方法
2017/12/14 Javascript
JavaScript实现多叉树的递归遍历和非递归遍历算法操作示例
2018/02/08 Javascript
JavaScript静态作用域和动态作用域实例详解
2019/06/17 Javascript
nuxt.js添加环境变量,区分项目打包环境操作
2020/11/06 Javascript
python scp 批量同步文件的实现方法
2019/01/03 Python
python 利用已有Ner模型进行数据清洗合并代码
2019/12/24 Python
Matplotlib自定义坐标轴刻度的实现示例
2020/06/18 Python
html5 canvas绘制网络字体的常用方法
2019/08/26 HTML / CSS
Coach澳大利亚官方网站:美国著名时尚奢侈品牌
2017/05/24 全球购物
英国花园药房: The Garden Pharmacy
2017/12/28 全球购物
英国在线药房:Chemist.co.uk
2019/03/26 全球购物
介绍一下Python中webbrowser的用法
2013/05/07 面试题
学生自我鉴定范文
2013/10/04 职场文书
会计系中文个人求职信
2013/12/24 职场文书
《泉水》教学反思
2014/04/11 职场文书
优秀少先队大队辅导员事迹材料
2014/05/04 职场文书
软件售后服务方案
2014/05/29 职场文书
销售类求职信
2014/06/13 职场文书
岗位竞聘报告范文
2014/11/06 职场文书
教师节班会主持词
2015/07/06 职场文书