TensorFlow的数学运算

发布于:2025-03-27 ⋅ 阅读:(75) ⋅ 点赞:(0)

前言

在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)

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())

结果如下:

5
5

2.何时必须使用函数?

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

归约操作:如tf.reduce_sum()(求和)、tf.reduce_mean()(求平均)等。
复杂运算:如矩阵乘法(tf.matmul)、卷积(tf.nn.conv2d)、梯度计算等。
指定参数:如设置计算轴(axis)、数据类型(dtype)或操作名称(name)。

聚合运算:

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())

结果如下;

4
[3 4 6 1 5 5]

矩阵运算:

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())
[[129  73 184 121]
 [ 99  83 137 122]
 [137  63 121  97]]

网站公告

今日签到

点亮在社区的每一天
去签到