目录
- [1. Early Stop](#1. Early Stop)
- [2. 怎样Early Stop](#2. 怎样Early Stop)
- [3. Dropout](#3. Dropout)
- [4. pytorch实现Dropout](#4. pytorch实现Dropout)
- [5. train和test时的Dropout](#5. train和test时的Dropout)
- [6. 增加了vidom的示例代码](#6. 增加了vidom的示例代码)
1. Early Stop
所谓的over fitting是训练集准确率在上升,但是test准确率开始下降了。
在测试集准确率达到最高点开始下降的时候停止训练,以防止over fitting
2. 怎样Early Stop
- 用验证机来选择模型参数
- 监测验证集的性能
- 在性能最高点时停止训练
3. Dropout
Dropout就是使用一个概率来减少模型参数量,使得模型复杂度降低,从而降低over fitting的几率。
模型复杂度越低over fitting的几率也就越低,因此Dropout通过使某些连接p=wx=0,相当于断掉该条连接,从而减少了当前层到下一层的连接数。比如:有10k个连接,加了Dropout可能就变成了5k。
4. pytorch实现Dropout
在层与层之间使用torch.nn.Dropout增加Dropout,注意Drop是加在两层之间而不是层内的。
5. train和test时的Dropout
train的时候是可以使用Dropout的,但是test的时候一定不要使用,否则性能会下降,如果train使用了Dropout,那么test的时候要通过net_dropped.eval()取消掉Dropout
6. 增加了vidom的示例代码
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from visdom import Visdom
batch_size=200
learning_rate=0.01
epochs=10
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
# transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.Compose([
transforms.ToTensor(),
# transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=batch_size, shuffle=True)
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.model = nn.Sequential(
nn.Linear(784, 200),
nn.LeakyReLU(inplace=True),
nn.Linear(200, 200),
nn.LeakyReLU(inplace=True),
nn.Linear(200, 10),
nn.LeakyReLU(inplace=True),
)
def forward(self, x):
x = self.model(x)
return x
device = torch.device('cuda:0')
net = MLP().to(device)
optimizer = optim.SGD(net.parameters(), lr=learning_rate)
criteon = nn.CrossEntropyLoss().to(device)
viz = Visdom()
viz.line([0.], [0.], win='train_loss', opts=dict(title='train loss'))
viz.line([[0.0, 0.0]], [0.], win='test', opts=dict(title='test loss&acc.',
legend=['loss', 'acc.']))
global_step = 0
for epoch in range(epochs):
for batch_idx, (data, target) in enumerate(train_loader):
data = data.view(-1, 28*28)
data, target = data.to(device), target.cuda()
logits = net(data)
loss = criteon(logits, target)
optimizer.zero_grad()
loss.backward()
# print(w1.grad.norm(), w2.grad.norm())
optimizer.step()
global_step += 1
viz.line([loss.item()], [global_step], win='train_loss', update='append')
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
test_loss = 0
correct = 0
for data, target in test_loader:
data = data.view(-1, 28 * 28)
data, target = data.to(device), target.cuda()
logits = net(data)
test_loss += criteon(logits, target).item()
pred = logits.argmax(dim=1)
correct += pred.eq(target).float().sum().item()
viz.line([[test_loss, correct / len(test_loader.dataset)]],
[global_step], win='test', update='append')
viz.images(data.view(-1, 1, 28, 28), win='x')
viz.text(str(pred.detach().cpu().numpy()), win='pred',
opts=dict(title='pred'))
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))