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]]
相关推荐
飞Link6 分钟前
具身智能港亮相深圳:从“大脑”到“身体”,开启人形机器人产业新纪元
人工智能·机器人
IT谢彪17 分钟前
记录Dify 安装与使用过程
人工智能
飞Link19 分钟前
AI 与能源的双向奔赴:深度解读 2026《双向赋能》行动方案
人工智能·能源
机器之心23 分钟前
这样问DeepSeek,能「偷」到数据?
人工智能·openai
桃花键神37 分钟前
Bright Data Web Scraping指南 2026: 使用 MCP + Dify 自动采集海外社交媒体数据
大数据·前端·人工智能
岁月标记1 小时前
RLHF 基于人类反馈的强化学习简介
人工智能
Ian在掘金1 小时前
从零实现一个 PDF 智能问答系统
人工智能·langchain
Flittly1 小时前
【LangGraph新手村系列】(5)时间旅行:浏览历史、分叉时间线与修改过去
python·langchain
飞Link1 小时前
智能体时代的“紧箍咒”:深度解析 Agent 治理架构与 AI 杀伤开关
人工智能·架构
飞Link1 小时前
2000 亿砸向算力:字节跳动 AI 基建跨越,后端与运维的“万亿 Token”生死战
运维·人工智能