目录
Softmax
二分类问题
给定一系列特征,输出为0或1,表示是否满足某个条件。具体做法是输出一个概率,表示给定特征满足这个条件的概率,或者不满足这个条件的概率。
多分类问题
给定一系列特征,预测是多个类别中的哪一类,比如手写数组识别、物体识别等。
如果在多分类问题中仍采用二分类问题的解决方法,即输出可能属于每个类别的概率,会出现的问题有
- 输出的概率可能为负数
- 所有类别概率之和不为1,即不是一个分布
提出Softmax Classifier解决上述问题,最后一个线性层输出的结果是z,包括预测属于k个类别的概率,公式如下
- 通过计算指数保证了最终输出结果必为正数
- 通过归一化保证了最终输出所有类别概率之和为1
举例如下
多分类损失函数
二分类损失函数cross-entropy(交叉熵)
本质还是损失函数,描述预测结果和真实结果之间的差异程度
y:真实值,y_head:预测值
-
y = 1
-
y_head = 1
预测值和真实值之间吻合,loss会很小
-
y_head = 0
预测值和真实值之间差异较大,loss会很大,注意看-log(y_head)
-
-
y = 0
-
y_head = 1
预测值和真实值之间差异较大,loss会很大,注意看-log(1-y_head)
-
y_head = 0
预测值和真实值之间吻合,loss会很小
-
多分类损失函数
没太明白,看弹幕有什么独热编码,记住公式吧?
pytorch提供的交叉熵损失函数直接包括计算log(y_head)、softmax和损失函数计算
注意:最后一层不做激活,直接使用交叉熵损失函数,传入softmax
实现手写数字识别
import torch
from torch import nn
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim
# --------------------------------------- 数据准备 ----------------------------------------
batch_size = 64
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./dataset/mnist', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size)
test_dataset = datasets.MNIST(root='./dataset/mnist', train=False, download=True, transform=transform)
test_loader = DataLoader(test_dataset, shuffle=False, batch_size=batch_size)
# --------------------------------------- 定义网络模型 ----------------------------------------
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.linear1 = nn.Linear(784, 512)
self.linear2 = nn.Linear(512, 256)
self.linear3 = nn.Linear(256, 128)
self.linear4 = nn.Linear(128, 64)
self.linear5 = nn.Linear(64, 10)
def forward(self, x):
x = x.view(-1, 784)
x = F.relu(self.linear1(x))
x = F.relu(self.linear2(x))
x = F.relu(self.linear3(x))
x = F.relu(self.linear4(x))
x = self.linear5(x) # 注意最后一层不加激活函数
return x
# -------------------------- 实例化网络模型 定义损失函数和优化器 --------------------------------
device = torch.device("cuda") # 定义gpu设备
model = Net()
model = model.to(device)
criterion = nn.CrossEntropyLoss() # 交叉熵损失函数
criterion = criterion.to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
# --------------------------------------- 定义训练过程 ----------------------------------------
def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 0):
inputs, targets = data
inputs = inputs.to(device)
targets = targets.to(device)
optimizer.zero_grad()
outputs = model(inputs) # forward
loss = criterion(outputs, targets) # get loss
loss.backward() # backward
optimizer.step() # update
running_loss += loss.item()
if batch_idx % 300 == 299: # 每300次输出
print('[%d, %5d] loss: %3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
running_loss = 0.0
# --------------------------------------- 定义测试过程 ----------------------------------------
def test():
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, dim=1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy on test set: %d %%' % (100 * correct / total))
if __name__ == '__main__':
for epoch in range(10):
train(epoch)
test()
标签:loss,head,torch,nn,self,分类,问题,train
From: https://www.cnblogs.com/dctwan/p/17067688.html