回归的损失函数,-【动手学深度学习】09 回归+损失函数+图片分类数据集 - , '
视频p3地址:
notebooks/chapter_linear-networks/image-classification-dataset.ipynb
p3练习一、二
查看迭代器和batch_size对性能的影响:
for batch_size in [1, 64, 256, 1024]:
timer = d2l.Timer()
train_iter = data.DataLoader(mnist_train, batch_size=batch_size,
shuffle=True, num_workers=4)
for X, y in train_iter:
continue
print(f"batch_size={batch_size} -->{timer.stop():.2f} sec")
for nw in [0, 2, 4, 8]:
timer = d2l.Timer()
train_iter = data.DataLoader(mnist_train, batch_size=256,
shuffle=True, num_workers=nw)
for X, y in train_iter:
continue
print(f"num_workers={nw} -->{timer.stop():.2f} sec")
运行结果:
p3练习三
import torchvision.datasets as dsets
print(dir(dsets))
#print:
['CIFAR10', 'CIFAR100', 'CLEVRClassification', 'CREStereo', 'Caltech101', 'Caltech256', 'CarlaStereo', 'CelebA', 'Cityscapes', 'CocoCaptions', 'CocoDetection', 'Country211', 'DTD', 'DatasetFolder', 'EMNIST', 'ETH3DStereo', 'EuroSAT', 'FER2013', 'FGVCAircraft', 'FakeData', 'FallingThingsStereo', 'FashionMNIST', 'Flickr30k', 'Flickr8k', 'Flowers102', 'FlyingChairs', 'FlyingThings3D', 'Food101', 'GTSRB', 'HD1K', 'HMDB51', 'INaturalist', 'ImageFolder', 'ImageNet', 'Imagenette', 'InStereo2k', 'KMNIST', 'Kinetics', 'Kitti', 'Kitti2012Stereo', 'Kitti2015Stereo', 'KittiFlow', 'LFWPairs', 'LFWPeople', 'LSUN', 'LSUNClass', 'MNIST', 'Middlebury2014Stereo', 'MovingMNIST', 'Omniglot', 'OxfordIIITPet', 'PCAM', 'PhotoTour', 'Places365', 'QMNIST', 'RenderedSST2', 'SBDataset', 'SBU', 'SEMEION', 'STL10', 'SUN397', 'SVHN', 'SceneFlowStereo', 'Sintel', 'SintelStereo', 'StanfordCars', 'UCF101', 'USPS', 'VOCDetection', 'VOCSegmentation', 'VisionDataset', 'WIDERFace', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__getattr__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_optical_flow', '_stereo_matching', 'caltech', 'celeba', 'cifar', 'cityscapes', 'clevr', 'coco', 'country211', 'dtd', 'eurosat', 'fakedata', 'fer2013', 'fgvc_aircraft', 'flickr', 'flowers102', 'folder', 'food101', 'gtsrb', 'hmdb51', 'imagenet', 'imagenette', 'inaturalist', 'kinetics', 'kitti', 'lfw', 'lsun', 'mnist', 'moving_mnist', 'omniglot', 'oxford_iiit_pet', 'pcam', 'phototour', 'places365', 'rendered_sst2', 'sbd', 'sbu', 'semeion', 'stanford_cars', 'stl10', 'sun397', 'svhn', 'ucf101', 'usps', 'utils', 'video_utils', 'vision', 'voc', 'widerface']
视频p4地址:notebooks/chapter_linear-networks/softmax-regression-scratch.ipynb
p4练习1、2
exp(50)数值会溢出;在log中,如果概率出现为0的情况会出现负无穷
p4练习3
针对溢出,可以考虑减去最大值;针对负无穷,可以考虑+ 1e-9
p4练习5
计算量会提高,减缓训练速度
视频p5地址:notebooks/chapter_linear-networks/softmax-regression-concise.ipynb
p5练习1
import torch
from torch import nn
from d2l import torch as d2l
import matplotlib.pyplot as plt
batch_size = 256
def get_net():
net = nn.Sequential(nn.Flatten(), nn.Linear(28*28, 10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std = 0.01)
net.apply(init_weights)
return net
def run_experiment(batch_size, lr, num_epochs, label):
#加载数据
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
net = get_net()
loss = nn.CrossEntropyLoss(reduction = 'none')
trainer = torch.optim.SGD(net.parameters(), lr = lr)
# 准备记录指标
train_losses, train_accs, test_accs = [], [], []
for epoch in range(num_epochs):
net.train()
metric = d2l.Accumulator(3)
for X,y in train_iter:
y_hat = net(X)
l = loss(y_hat, y)
trainer.zero_grad()
l.mean().backward()
trainer.step()
metric.add(float(l.sum()), d2l.accuracy(y_hat, y), y.numel())
train_losses.append(metric[0]/metric[2])
train_accs.append(metric[1]/metric[2])
test_acc = d2l.evaluate_accuracy(net, test_iter)
test_accs.append(test_acc)
return{
'label':label,
'train_loss':train_losses,
'train_acc':train_accs,
'test_acc':test_accs
}
experiments = [
{'batch_size': 64, 'lr': 0.1, 'num_epochs': 10, 'label': 'bs=64, lr=0.1'},
{'batch_size': 256, 'lr': 0.1, 'num_epochs': 10, 'label': 'bs=256, lr=0.1'},
{'batch_size': 256, 'lr': 0.01, 'num_epochs': 10, 'label': 'bs=256, lr=0.01'},
{'batch_size': 512, 'lr': 0.1, 'num_epochs': 10, 'label': 'bs=512, lr=0.1'}
] 拼多多帮助力入口
results = []
for exp in experiments:
print(f"Running:{exp['label']}")
result = run_experiment(**exp)
results.append(result)
def plot_metrics(results, metric_name):
plt.figure(figsize = (8,4))
for r in results:
plt.plot(r[metric_name], label=r['label'])
plt.xlabel('epoch')
plt.ylabel(metric_name)
plt.title(f'{metric_name} across experoments')
plt.legend()
plt.grid(True)
plt.show()
plot_metrics(results, 'train_loss')
plot_metrics(results, 'train_acc')
plot_metrics(results, 'test_acc')
p5练习2
因为出现了过拟合,可以考虑early stopping、降低学习率等。