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]]
相关推荐
蓝桉80227 分钟前
如何进行神经网络的模型训练(视频代码中的知识点记录)
人工智能·深度学习·神经网络
星期天要睡觉1 小时前
深度学习——数据增强(Data Augmentation)
人工智能·深度学习
南山二毛2 小时前
机器人控制器开发(导航算法——导航栈关联坐标系)
人工智能·架构·机器人
大数据张老师2 小时前
【案例】AI语音识别系统的标注分区策略
人工智能·系统架构·语音识别·架构设计·后端架构
xz2024102****2 小时前
吴恩达机器学习合集
人工智能·机器学习
anneCoder2 小时前
AI大模型应用研发工程师面试知识准备目录
人工智能·深度学习·机器学习
骑驴看星星a2 小时前
没有深度学习
人工智能·深度学习
youcans_2 小时前
【医学影像 AI】YoloCurvSeg:仅需标注一个带噪骨架即可实现血管状曲线结构分割
人工智能·yolo·计算机视觉·分割·医学影像
Eric.5653 小时前
python advance -----object-oriented
python
空白到白3 小时前
机器学习-决策树
人工智能·决策树·机器学习