把薄书读厚,典型案例详解
pytorch-CNN经典案例拆解
案例出自:
https://github.com/yunjey/pytorch-tutorial.git
关注用案例学Pytorch:
https://github.com/houhuipeng/EasyPytorch-ByExample.git
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
#ctrl+鼠标左键,进入类/函数(可进入多层,查看注释);alt+←,退出类/函数
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
num_epochs= 5 #训练5遍
num_classes =10 #目标类别
batch_size = 100 #训练批次中,每个批次要加载的样本数量(默认值:)1
learning_rate = 0.001
train_dataset = torchvision.datasets.MNIST(root = '../../data/',
train= True,
transform = transforms.ToTensor(),
download=False)
'''
1、文件存储路径表示方法:
2、已封装数据集包括:CIFAR-10,以及ImageNet、COCO、MNIST、LSUN
所有数据集都具有几乎相似的接口(API,application programming interface)
MNIST(root =存储路径,
train =是否属于训练集,
download =是否下载,
transform =转换格式(一个函数/转换,它接收PIL图像并返回转换后的版本。例如,transforms.RandomCrop)
target_transform=是否对label转换 (接收目标并对其进行转换的函数/转换)
4、transforms:参见https://pytorch.org/docs/stable/torchvision/transforms.html
torchvision.transforms.Compose[...] 一起组合几个变换
torchvision.transforms.CenterCrop(尺寸大小) 将给定的PIL图像裁剪为中心
torchvision.transforms.ColorJitter(亮度= 0,对比度= 0,饱和度= 0,色调= 0 )更改图像亮度
torchvision.transforms.Grayscale(num_output_channels = 1 )转换灰度图像,默认为1;为3时,则输出RGB
torchvision.transforms.Pad(padding,fill = 0,padding_mode ='constant' ):
padding(int或tuple) - 边框填充。长度为1,则用于4条边;长度为2,则分别填充左/右和上/下;长度为4,分别填充左,上,右和下边框。
fill(int或tuple) - 常量填充的像素填充值。默认值为0.如果长度为3的元组,则分别用于填充R,G,B通道。仅当padding_mode为常量时才使用此值
padding_mode(str) -填充类型。应该是:恒定constant, 边缘edge,反射reflect 或对称symmetric。默认值是常量。
transforms成员函数非常多: