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]]
相关推荐
回眸&啤酒鸭3 天前
【回眸】Minicart 电商购物车核心功能落地指南
人工智能
一隅论数智3 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
AI的探索之旅3 天前
97 个 OpenCV 实例(三十):双目立体,从标定到点云
人工智能·opencv·计算机视觉
AlbertZein3 天前
Step-5-Preview 上手实测:3D 游戏、金融分析、网页设计一次跑完
人工智能·aigc
LaughingZhu3 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
美狐美颜SDK开放平台3 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk