八、多分类问题-softmax classifier
课程链接:Pytorch 深度学习实践——多分类问题
1、Loss Function - Cross Entropy
①Cross Entropy in Numpy
import numpy as np
z = np.array([0.2, 0.1, -0.1])
y = np.array([1, 0, 0])
y_pred = np.exp(z) / np.exp(z).sum()
loss = (-y * np.log(y_pred)).sum()
print(loss)
② N L L L O S S ( Y ^ , Y ) = − Y l o g Y ^ NLLLOSS(\hat{Y},Y)=-Ylog\hat{Y} NLLLOSS(Y^,Y)=−YlogY^
③Cross Entropy in Pytorch
import numpy as np
import torch
y = torch.LongTensor([2, 0, 1])
y_pred1 = torch.Tensor([[0.1, 0.2, 0.9],
[1.1, 0.1, 0.2],
[0.2, 2.1, 0.1]])
y_pred2 = torch.Tensor([[0.8, 0.2, 0.3],
[0.2, 0.3, 0.5],
[0.2, 0.2, 0.5]])
criterion = torch.nn.CrossEntropyLoss()
l1 = criterion(y_pred1, y)
l2 = criterion(y_pred2, y)
print(l1.item(), l2.item()) #0.4966353178024292 1.2388995885849
2、 MNIST DataSet
①ToTensor:Convert PIL Image to Tensor
transform = transforms.Compose([transforms.ToTensor(), #convert PIL Image to Tensor
transforms.Normalize((0.1307,), (0.3081,))]) #归一化参数:均值mean、标准差std
②Prepare Dataset
# Prepare Dataset
batch_size = 64
train_data = datasets.MNIST('mnist_data', train=True, download=True, transform=transform)
train_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)
test_data = datasets.MNIST('mnist_data', train=False, download=True, transform=transform)
test_loader = DataLoader(test_data, shuffle=False, batch_size=batch_size)
③Design Model
# Design Model
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.l1 = torch.nn.Linear(784, 512)
self.l2 = torch.nn.Linear(512, 256)
self.l3 = torch.nn.Linear(256, 128)
self.l4 = torch.nn.Linear(128, 64)
self.l5 = torch.nn.Linear(64, 10)
self.activate = torch.nn.ReLU()
def forward(self, x): # input维度为N*1*28*28
x = x.view(-1, 784) # 将维度转换为N*784
x = self.activate(self.l1(x))
x = self.activate(self.l2(x))
x = self.activate(self.l3(x))
x = self.activate(self.l4(x))
x = self.l5(x)
return x
model = Model()
④Loss Function And Optimizer
# Loss Function And Optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
⑤Traing Cycle
# Training Cycle
def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 1):
# Prepare
x, y = data
# Forward
y_pred = model(x)
loss = criterion(y_pred, y)
running_loss += loss.item()
# Backward
optimizer.zero_grad()
loss.backward()
# Update
optimizer.step()
if(batch_idx % 300 == 0): #每300轮看一下结果
print('[%d, %5d] loss = %.3f' % (epoch + 1, batch_idx, running_loss / 300))
running_loss = 0.0
⑥Test
# Test
def test():
correct = 0
total = 0
with torch.no_grad(): # Test 阶段不适用梯度
for data in test_loader:
images, labels = data
outputs = model(images)
_, pred = torch.max(outputs.data, dim=1) #返回两个值:最大值以及最大值所在的下标
total += labels.size(0)
correct += (pred == labels).sum().item()
print('Accuracy on Test set: %.4f %%' % (100.0 * correct / total))
⑦结果展示
output:
[1, 300] loss = 2.217
[1, 600] loss = 0.910
[1, 900] loss = 0.440
Accuracy on Test set: 89.6800 %
[2, 300] loss = 0.328
[2, 600] loss = 0.274
[2, 900] loss = 0.242
Accuracy on Test set: 93.7400 %
[3, 300] loss = 0.193
[3, 600] loss = 0.179
[3, 900] loss = 0.163
Accuracy on Test set: 95.2600 %
Loss曲线
3、作业——otto-group-product-classification
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
import torch.optim as optim
#将字符型标签转换为数值标签,方便后面的Cross Entropy Loss的计算
def lables2id(lables):
target_id = []
target_lables = ['Class_1', 'Class_2', 'Class_3', 'Class_4', 'Class_5', 'Class_6', 'Class_7', 'Class_8', 'Class_9']
for lable in lables:
target_id.append(target_lables.index(lable))
return target_id
# Define DataSet
class TrainDataset(Dataset):
def __init__(self, filepath):
data = pd.read_csv(filepath)
# data.info()
lables = data['target']
self.x_data = torch.from_numpy(np.array(data)[:, 1:-1].astype(np.float32))
self.y_data = lables2id(lables)
self.len = data.shape[0]
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
def __len__(self):
return self.len
train_data = TrainDataset('train.csv')
train_loader = DataLoader(dataset=train_data, batch_size=64, shuffle=True, num_workers=0)
# Design Model
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.l1 = torch.nn.Linear(93, 64)
self.l2 = torch.nn.Linear(64, 32)
self.l3 = torch.nn.Linear(32, 16)
self.l4 = torch.nn.Linear(16, 9)
self.activate = torch.nn.ReLU()
def forward(self, x):
x = self.activate(self.l1(x))
x = self.activate(self.l2(x))
x = self.activate(self.l3(x))
x = self.l4(x)
return x
model = Model()
# Loss Function And Optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
# Training Cycle
train_loss = []
def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 1):
# Prepare
x, y = data
# Forward
y_pred = model(x)
loss = criterion(y_pred, y)
running_loss += loss.item()
# Backward
optimizer.zero_grad()
loss.backward()
# Update
optimizer.step()
train_loss.append(loss.item())
if (batch_idx % 300 == 0): # 每300轮看一下结果
print('[%d, %5d] loss = %.3f' % (epoch + 1, batch_idx, running_loss / 300))
running_loss = 0.0
if __name__ == '__main__':
for epoch in range(33):
train(epoch)
plt.plot(range(len(train_loss)), train_loss)
plt.xlabel('step')
plt.ylabel('loss')
plt.show()
# Test
def test():
test_data = pd.read_csv('test.csv')
x_test = torch.from_numpy(np.array(test_data)[:, 1:].astype(np.float32))
y_pred = model(x_test)
_, pred = torch.max(y_pred, dim=1)
out = pd.get_dummies(pred) # get_dummies 是利用pandas实现one hot encode的方式
lables = ['Class_1', 'Class_2', 'Class_3', 'Class_4', 'Class_5', 'Class_6', 'Class_7', 'Class_8', 'Class_9']
out.columns = lables
out.insert(0, 'id', test_data['id'])
result = pd.DataFrame(out)
result.to_csv('otto-group-product_predictions.csv', index=False)
test()