Python计算softmax和pytorch计算结果比较

博客主要围绕softmax计算展开,给出了softmax计算公式,并展示了pytorch和Python的计算结果。在Python计算中出现溢出问题,原因是exp(1000)太大。通过在softmax计算公式中分子分母同时除以exp(max(xi))解决了溢出问题,使计算结果恢复正常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、softmax计算公式

 

softmax(x_{i}) = exp(x_{i})/\sum(exp(x_{j}))

2、pytorch计算结果


import torch
import torch.nn as nn
import numpy as np


n1 = np.array([[1, 2, 3], [1000, 0, -1000]], dtype=np.float32)
m = nn.Softmax(dim=1)
out = m(torch.from_numpy(n1))
print(out)

执行后输出结果:

tensor([[0.0900, 0.2447, 0.6652],
        [1.0000, 0.0000, 0.0000]])

3、Python计算结果

简单实现:

import torch
import torch.nn as nn
import numpy as np
import math

n1 = np.array([[1, 2, 3], [1000, 0, -1000]], dtype=np.float32)
def softmax(inp):
    for b in inp:
        tmp = [math.exp(i) for i in b]
        s = sum(tmp)
        print([i/s for i in tmp])

softmax(n1)

结果:

[0.09003057317038046, 0.24472847105479767, 0.6652409557748219]
Traceback (most recent call last):
  File "softmax.py", line 20, in <module>
    softmax(n1)
  File "softmax.py", line 16, in softmax
    tmp = [math.exp(i) for i in b]
  File "softmax.py", line 16, in <listcomp>
    tmp = [math.exp(i) for i in b]
OverflowError: math range error

从结果可以看出,第一行和pytorch中结果一致,计算第二行时,提示溢出了,因为exp(1000)太大了。

softmax计算公式中,分子分母同时除以exp(max(xi)),结果不变,可以解决溢出问题。

代码略微修改:


import torch
import torch.nn as nn
import numpy as np
import math


n1 = np.array([[1, 2, 3], [1000, 0, -1000]], dtype=np.float32)
def softmax(inp):
    for b in inp:
        maxi = max(b)
        tmp = [math.exp(i-maxi) for i in b]
        s = sum(tmp)
        print([i/s for i in tmp])

softmax(n1)

结果正常:

[0.09003057317038046, 0.24472847105479764, 0.6652409557748218]
[1.0, 0.0, 0.0]

 

 

 

PyTorch中实现softmax回归可以分为以下几个步骤: 1. 导入所需的库: ```python import torch import torch.nn as nn import torch.optim as optim ``` 2. 准备数据: 假设我们有一个大小为(N,D)的训练集,其中N是样本数量,D是特征数量,以及一个大小为(N,)的标签集。可以使用`torch.tensor`将数据转换为PyTorch张量。 ```python X_train = torch.tensor(X_train, dtype=torch.float32) y_train = torch.tensor(y_train, dtype=torch.long) ``` 3. 定义模型: 在PyTorch中,可以通过继承`nn.Module`类来定义模型。在softmax回归中,我们使用线性变换softmax函数。 ```python class SoftmaxRegression(nn.Module): def __init__(self, input_dim, num_classes): super(SoftmaxRegression, self).__init__() self.linear = nn.Linear(input_dim, num_classes) def forward(self, x): return self.linear(x) ``` 4. 实例化模型损失函数: ```python input_dim = X_train.shape[1] # 输入特征数 num_classes = len(torch.unique(y_train)) # 类别数 model = SoftmaxRegression(input_dim, num_classes) criterion = nn.CrossEntropyLoss() ``` 5. 定义优化器: ```python optimizer = optim.SGD(model.parameters(), lr=learning_rate) ``` 6. 训练模型: ```python num_epochs = 100 for epoch in range(num_epochs): # 前向传播 outputs = model(X_train) # 计算损失 loss = criterion(outputs, y_train) # 反向传播优化 optimizer.zero_grad() loss.backward() optimizer.step() # 打印训练信息 if (epoch+1) % 10 == 0: print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}') ``` 这样就完成了使用PyTorch实现softmax回归的过程。你可以根据自己的数据需求进行适当的调整扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值