softmax:处理多分类 ①概率和为1 ②各个概率都>=0 softmax例子: softmax对应的损失函数: code:
import numpy as np
y = np.array([1, 0, 0])
z = np.array([0.2, 0.1, -0.1])
y_pred = np.exp(z) / np.exp(z).sum()
loss = (- y * np.log(y_pred)).sum()
print(loss)
效果图:
torch里面有:交叉熵损失,包含了softmax,loss
import torch
y = torch.LongTensor([0])
z = torch.Tensor([[0.2, 0.1, -0.1]])
criterion = torch.nn.CrossEntropyLoss()
loss = criterion(z, y)
print(loss)
效果图: 样例: code:
import torch
criterion = torch.nn.CrossEntropyLoss()
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, 2.1, 0.5]])
l1 = criterion(Y_pred1, Y)
l2 = criterion(Y_pred2, Y)
print("Batch Loss1 = ", l1.data, "\nBatch Loss2 =", l2.data)
图像处理: code:
import torch
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
# 拿到一个图像,先ToTensor变为张量,做一个normalize把它变为0-1分布,然后再用神经网络
transforms = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307, ), (0.3081, )) # 第一个(0.1307, )是均值,第二个是标准差
])
train_dataset = datasets.MNIST(root='../dataset/mnist',
train=True,
download=True,
transform=transforms)
train_loader = DataLoader(train_dataset,
shuffle=True,
batch_size=batch_size)
test_dataset = datasets.MNIST(root='../dataset/mnist',
train=False,
download=True,
transform=transforms)
test_loader = DataLoader(test_dataset,
shuffle=False,
batch_size=batch_size)
模型图: # 交叉熵损失,经过softmax
code:
criterion = torch.nn.CrossEntropyLoss()
train部分: train把一轮循环封装为函数 test部分: 总的code:
import torch
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
# 拿到一个图像,先ToTensor变为张量,做一个normalize把它变为0-1分布,然后再用神经网络
transforms = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307, ), (0.3081, )) # 第一个(0.1307, )是均值,第二个是标准差
])
train_dataset = datasets.MNIST(root='../dataset/mnist',
train=True,
download=True,
transform=transforms)
train_loader = DataLoader(train_dataset,
shuffle=True,
batch_size=batch_size)
test_dataset = datasets.MNIST(root='../dataset/mnist',
train=False,
download=True,
transform=transforms)
test_loader = DataLoader(test_dataset,
shuffle=False,
batch_size=batch_size)
class Net(torch.nn.Module):
def __init__(self):
super(Net, 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)
def forward(self, x):
x = x.view(-1, 784) # 把图片变为矩阵
x = F.relu(self.l1(x))
x = F.relu(self.l2(x))
x = F.relu(self.l3(x))
x = F.relu(self.l4(x))
return self.l5(x)
model = Net()
# 交叉熵损失,经过softmax
criterion = torch.nn.CrossEntropyLoss()
# 模型有点大,所以用带有冲量(momentum)的
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
# train把一轮循环封装为函数
def train(epoch):
running_loss = 0.0
for batch_idx, data in enumerate(train_loader, 0):
# X:inputs,Y:target
inputs, target = data
optimizer.zero_grad()
# 前向+反向+更新
outputs = model(inputs)
loss = criterion(outputs, target)
loss.backward()
optimizer.step()
running_loss += loss.item()
if batch_idx % 300 == 299:
print('[%d, %5d] loss: %.3f' % (epoch +1, batch_idx +1, running_loss / 300))
running_loss = 0.0
# test 不用算梯度 with torch.no_grad():
def test():
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
outputs = model(images)
_, predicted = torch.max(outputs.data, dim=1) # 算每一行最大值的下标是多少,其实也代表了每一行的分类 / max返回 每一行最大值是多少,每一行最大值的下标是多少
total += labels.size(0)
correct += (predicted == labels).sum().item() # ==预测的和原来的作比较,真为1,假为0,再总的加起来,求和后再把这个标量提出来
print('Accuracy on test set: %d %%' % (100 * correct / total))
if __name__ == '__main__':
for epoch in range(10):
# 一轮训练一轮测试
train(epoch)
test()
效果图:
|