Pytorch(二) —— 激活函数、损失函数及其梯度

1.激活函数

1.1 Sigmoid / Logistic

δ ( x ) = 1 1 + e − x δ ′ ( x ) = δ ( 1 − δ ) \delta(x)=\frac{1}{1+e^{-x}}\\\delta'(x)=\delta(1-\delta) δ(x)=1+ex1δ(x)=δ(1δ)

import matplotlib.pyplot as plt
import torch.nn.functional as F
x = torch.linspace(-10,10,1000)
y = F.sigmoid(x)
plt.plot(x,y)
plt.show()

在这里插入图片描述

1.2 Tanh

t a n h ( x ) = e x − e − x e x + e − x ∂ t a n h ( x ) ∂ x = 1 − t a n h 2 ( x ) tanh(x)=\frac{e^x-e^{-x}}{e^x+e^{-x}}\\\frac{\partial tanh(x)}{\partial x}=1-tanh^2(x) tanh(x)=ex+exexexxtanh(x)=1tanh2(x)

import matplotlib.pyplot as plt
import torch.nn.functional as F
x = torch.linspace(-10,10,1000)
y = F.tanh(x)
plt.plot(x,y)
plt.show()

在这里插入图片描述

1.3 ReLU

f ( x ) = m a x ( 0 , x ) f(x)=max(0,x) f(x)=max(0,x)

import matplotlib.pyplot as plt
import torch.nn.functional as F
x = torch.linspace(-10,10,1000)
y = F.relu(x)
plt.plot(x,y)
plt.show()

在这里插入图片描述

1.4 Softmax

p i = e a i ∑ k = 1 N e a k ∂ p i ∂ a j = { p i ( 1 − p j ) i = j − p i p j i ≠ j p_i=\frac{e^{a_i}}{\sum_{k=1}^N{e^{a_k}}}\\ \frac{\partial p_i}{\partial a_j}=\left\{ \begin{array}{lc} p_i(1-p_j) & i=j \\ -p_ip_j&i\neq j\\ \end{array} \right. pi=k=1Neakeaiajpi={pi(1pj)pipji=ji=j

import torch.nn.functional as F
logits = torch.rand(10)
prob = F.softmax(logits,dim=0)
print(prob)
tensor([0.1024, 0.0617, 0.1133, 0.1544, 0.1184, 0.0735, 0.0590, 0.1036, 0.0861,
        0.1275])

2.损失函数

2.1 MSE

import torch.nn.functional as F
x = torch.rand(100,64)
w = torch.rand(64,1)
y = torch.rand(100,1)
mse = F.mse_loss(y,x@w)
print(mse)
tensor(238.5115)

2.2 CorssEntorpy

import torch.nn.functional as F
x = torch.rand(100,64)
w = torch.rand(64,10)
y = torch.randint(0,9,[100])
entropy = F.cross_entropy(x@w,y)
print(entropy)
tensor(3.6413)

3. 求导和反向传播

3.1 求导

  • Tensor.requires_grad_()
  • torch.autograd.grad()
import torch.nn.functional as F
import torch
x = torch.rand(100,64)
w = torch.rand(64,1)
y = torch.rand(100,1)
w.requires_grad_()
mse = F.mse_loss(x@w,y)
grads = torch.autograd.grad(mse,[w])
print(grads[0].shape)
torch.Size([64, 1])

3.2 反向传播

  • Tensor.backward()
import torch.nn.functional as F
import torch
x = torch.rand(100,64)
w = torch.rand(64,10)
w.requires_grad_()
y = torch.randint(0,9,[100,])
entropy = F.cross_entropy(x@w,y)
entropy.backward()
w.grad.shape
torch.Size([64, 10])

by CyrusMay 2022 06 28

人生 只是 须臾的刹那
人间 只是 天地的夹缝
——————五月天(因为你 所以我)——————

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch是一个流行的深度学习框架,可以用于实现各种损失函数,包括GHM损失函数。GHM(Gradient Harmonized Mixture)损失函数是一种用于解决样本不平衡问题的损失函数。 下面是使用PyTorch实现分类GHM损失函数的示例代码: ```python import torch import torch.nn as nn class GHMLoss(nn.Module): def __init__(self, bins=10, momentum=0): super(GHMLoss, self).__init__() self.bins = bins self.momentum = momentum self.edges = torch.arange(bins+1).float() / bins self.edges[-1] += 1e-6 if momentum > 0: self.acc_sum = torch.zeros(bins) def forward(self, pred, target): g = torch.abs(pred.detach() - target) weights = torch.zeros_like(g) tot = g.numel() n = 0 for i in range(self.bins): inds = (g >= self.edges[i]) & (g < self.edges[i+1]) num_in_bin = inds.sum().item() if num_in_bin > 0: if self.momentum > 0: self.acc_sum[i] = self.momentum * self.acc_sum[i] + (1 - self.momentum) * num_in_bin weights[inds] = tot / self.acc_sum[i] else: weights[inds] = tot / num_in_bin n += 1 weights /= n loss = nn.BCELoss(weight=weights)(pred, target) return loss # 使用示例 criterion = GHMLoss() pred = torch.randn(10, 1) target = torch.randint(0, 2, (10, 1)).float() loss = criterion(pred, target) print(loss) ``` 在上述代码中,我们定义了一个名为`GHMLoss`的自定义损失函数类,它继承自`nn.Module`。在类的初始化方法中,我们设置了GHM损失函数的参数,包括`bins`(直方图的箱数)和`momentum`(动量参数)。在前向传播方法中,我们计算了样本的梯度差异度量`g`,然后根据梯度差异将样本分成不同的区间,并计算每个区间的权重。最后,我们使用带权重的分类交叉熵损失函数`nn.BCELoss`计算最终的损失。 你可以根据自己的需求调整`bins`和`momentum`参数,并将上述代码集成到你的分类模型中进行训练。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值