TensorFlow的数学运算

目录

前言

在TensorFlow中既可以使用数学运算符号进行数学运算也可以使用TensorFlow定义好的数学运算方法。

1. 运算符与函数的对应关系

TensorFlow重载了Python运算符,使其能够直接操作张量(Tensor)。例如:

加法:a + b 等价于 tf.add(a, b)

减法:a - b 等价于 tf.subtract(a, b)

乘法:a * b 等价于 tf.multiply(a, b)

除法:a / b 等价于 tf.divide(a, b)

矩阵乘法:a @ b 等价于 tf.matmul(a, b)

python 复制代码
import tensorflow as tf

#  定义常量
a = tf.constant(2)
b = tf.constant(3)


# 使用运算符
c1 = a + b  # 结果为 5
print(c1.numpy())

# 使用TensorFlow函数
c2 = tf.add(a, b)  # 结果相同
print(c2.numpy())

结果如下:

powershell 复制代码
5
5

2.何时必须使用函数?

以下场景需直接调用TensorFlow函数:

归约操作:如tf.reduce_sum()(求和)、tf.reduce_mean()(求平均)等。

复杂运算:如矩阵乘法(tf.matmul)、卷积(tf.nn.conv2d)、梯度计算等。

指定参数:如设置计算轴(axis)、数据类型(dtype)或操作名称(name)。

聚合运算:

python 复制代码
import tensorflow as tf
import numpy as np

x = np.random.randint(0,10, size=(3,6))
x_mean = tf.reduce_mean(x)
# 默认会聚合所有的维度
print(x_mean.numpy())

# 可以指定聚合的轴
x_reduce_mean = tf.reduce_mean(x, axis=0)
print(x_reduce_mean.numpy())

结果如下;

powershell 复制代码
4
[3 4 6 1 5 5]

矩阵运算:

python 复制代码
import tensorflow as tf
import numpy as np

# 矩阵运算
x = np.random.randint(0,10, size=(3,6))
y = np.random.randint(0,10, size=(6,4))
dot = tf.matmul(x, y)
print(dot.numpy())
powershell 复制代码
[[129  73 184 121]
 [ 99  83 137 122]
 [137  63 121  97]]
相关推荐
qcx23几秒前
【系统学AI】09 Multi-Agent架构(2026版):从学术理论到工业级实践
java·人工智能·架构·multi-agent·claude agent
洛宇3 分钟前
一个口语 skill,灵感居然来自2021年的那个夏天
人工智能·程序员·github
微擎应用10 分钟前
智能售货柜公众号管理系统平台
大数据·人工智能
IT_陈寒11 分钟前
Vite打包时遇到的坑,原来问题出在这里
前端·人工智能·后端
星辰AI42 分钟前
多模态记忆:让 AI Agent 记忆各种类型的信息
人工智能·ai·语言模型
jiayong2343 分钟前
AI架构师面试题库 - 完整汇总文档
人工智能·面试·职场和发展
bigfootyazi1 小时前
python爬虫-基本库-urllib库(常用速查)
开发语言·爬虫·python
后端小肥肠1 小时前
效率狂飙9000%!Codex + HyperFrames 让一篇文章 5 分钟变视频
人工智能·aigc·agent
阿里云大数据AI技术1 小时前
最佳实践:用 EMR Serverless StarRocks AI Function 实现金融行业文本分类
人工智能
瑶总迷弟1 小时前
使用 mis-tei 在昇腾310P上部署 bge-m3模型
pytorch·python·华为·语言模型·自然语言处理·cnn·unix