介绍
torch.exp() 函数,是实现指数运算的核心函数,也是 softmax、sigmoid 等激活函数的基础
语法
对输入张量中的 每一个元素 计算 自然指数 e^x
e是自然常数,≈2.71828x是张量中的元素值
torch.exp(input, *, out=None)
简单来说,它是一个逐元素运算——输入一个张量,输出一个形状完全相同的张量,每个元素都是原元素的自然指数结果。
例子
先看最直观的代码示例,你可以直接运行验证:
import torch
# 示例1:标量输入
x_scalar = torch.tensor(1.0)
exp_scalar = torch.exp(x_scalar)
print("标量结果:", exp_scalar) # tensor(2.7183)(≈e^1)
# 示例2:一维张量输入
x_vec = torch.tensor([0.0, 1.0, 2.0])
exp_vec = torch.exp(x_vec)
print("一维张量结果:", exp_vec) # tensor([1.0000, 2.7183, 7.3891])(e^0=1, e^1≈2.7183, e^2≈7.3891)
# 示例3:二维张量输入
x_mat = torch.tensor([[0.5, 1.5], [-1.0, 0.0]])
exp_mat = torch.exp(x_mat)
print("二维张量结果:\n", exp_mat)
# 输出:
# tensor([[1.6487, 4.4817], # e^0.5≈1.6487, e^1.5≈4.4817
# [0.3679, 1.0000]]) # e^-1≈0.3679, e^0=1
与 NumPy 的对比
如果你熟悉 NumPy,torch.exp() 和 numpy.exp() 行为完全一致,只是操作的是 PyTorch 张量而非 NumPy 数组:
import numpy as np
x = torch.tensor([1.0, 2.0])
np_x = x.numpy()
# PyTorch exp
torch_exp = torch.exp(x)
# NumPy exp
np_exp = np.exp(np_x)
print("torch.exp:", torch_exp) # tensor([2.7183, 7.3891])
print("np.exp:", np_exp) # [2.7182817 7.389056 ]
与 softmax 函数的关联(核心应用场景)
softmax 函数的核心就是 torch.exp() + 归一化,我们可以手动实现 softmax 来理解它的作用:
def manual_softmax(x, dim=0):
# 步骤1:计算每个元素的指数(torch.exp核心)
exp_x = torch.exp(x)
# 步骤2:按指定维度求和(归一化分母)
sum_exp_x = torch.sum(exp_x, dim=dim, keepdim=True)
# 步骤3:归一化得到概率
return exp_x / sum_exp_x
# 验证:手动实现 vs PyTorch 官方 softmax
logits = torch.tensor([1.0, 2.0, 3.0])
my_softmax = manual_softmax(logits)
torch_softmax = torch.nn.functional.softmax(logits, dim=0)
print("手动softmax:", my_softmax) # tensor([0.0900, 0.2447, 0.6652])
print("PyTorch softmax:", torch_softmax) # tensor([0.0900, 0.2447, 0.6652])
print("是否相等:", torch.equal(my_softmax, torch_softmax)) # True
数值稳定性优化(解决溢出)
为了避免 torch.exp() 溢出,softmax 实际实现时会先减去输入的最大值(这也是 PyTorch 官方 softmax 的内部逻辑):
def stable_softmax(x, dim=0):
# 步骤1:减去最大值,避免指数溢出
x_max = torch.max(x, dim=dim, keepdim=True)[0]
x_stable = x - x_max
# 步骤2:计算指数
exp_x = torch.exp(x_stable)
# 步骤3:归一化
sum_exp_x = torch.sum(exp_x, dim=dim, keepdim=True)
return exp_x / sum_exp_x
# 验证溢出场景的稳定性
x_overflow = torch.tensor([1000.0, 1001.0, 1002.0])
# 直接exp会溢出,stable_softmax则正常
stable_sm = stable_softmax(x_overflow)
print("稳定softmax结果:", stable_sm) # tensor([0.0900, 0.2447, 0.6652])(正确)
注意
数值范围与溢出风险
自然指数的增长速度极快,大的正数输入会导致结果溢出为无穷大(inf),这是使用时最需要注意的问题:
# 溢出示例
x_large = torch.tensor([100.0, 1000.0])
exp_large = torch.exp(x_large)
print("大值指数结果:", exp_large) # tensor([inf, inf])(超出浮点数表示范围)
# 负数输入则会趋近于0
x_neg = torch.tensor([-10.0, -100.0])
exp_neg = torch.exp(x_neg)
print("负数指数结果:", exp_neg) # tensor([4.5400e-05, 3.2088e-44])(接近0)
总结
torch.exp()是逐元素计算自然指数e^x的函数,输出张量与输入形状完全一致。- 核心应用是实现 softmax、sigmoid 等激活函数,但需注意 大正数输入会导致数值溢出。
- 解决溢出的关键技巧是:计算指数前先减去输入的最大值(这是 softmax 等函数的数值稳定化核心)。