环境
系统:win10
cpu:i7-6700HQ
gpu:gtx965m
python : 3.6
pytorch :0.3
数据下载
来源自Sasank Chilamkurthy 的教程; 数据:下载链接。
下载后解压放到项目根目录:
数据集为用来分类 蚂蚁和蜜蜂。有大约120个训练图像,每个类有75个验证图像。
数据导入
可以使用 torchvision.datasets.ImageFolder(root,transforms) 模块 可以将 图片转换为 tensor。
先定义transform:
ata_transforms = { 'train': transforms.Compose([ # 随机切成224x224 大小图片 统一图片格式 transforms.RandomResizedCrop(224), # 图像翻转 transforms.RandomHorizontalFlip(), # totensor 归一化(0,255) >> (0,1) normalize channel=(channel-mean)/std transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]), "val" : transforms.Compose([ # 图片大小缩放 统一图片格式 transforms.Resize(256), # 以中心裁剪 transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ])}
导入,加载数据:
data_dir = './hymenoptera_data'# trans dataimage_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']}# load datadata_loaders = {x: DataLoader(image_datasets[x], batch_size=BATCH_SIZE, shuffle=True) for x in ['train', 'val']}data_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}class_names = image_datasets['train'].classesprint(data_sizes, class_names)
{'train': 244, 'val': 153} ['ants', 'bees']
训练集 244图片 , 测试集153图片 。
可视化部分图片看看,由于visdom支持tensor输入 ,不用换成numpy,直接用tensor计算即可 :
inputs, classes = next(iter(data_loaders['val']))out = torchvision.utils.make_grid(inputs)inp = torch.transpose(out, 0, 2)mean = torch.FloatTensor([0.485, 0.456, 0.406])std = torch.FloatTensor([0.229, 0.224, 0.225])inp = std * inp + meaninp = torch.transpose(inp, 0, 2)viz.images(inp)
创建CNN
net 根据上一篇的处理cifar10的改了一下规格:
class CNN(nn.Module): def __init__(self, in_dim, n_class): super(CNN, self).__init__() self.cnn = nn.Sequential( nn.BatchNorm2d(in_dim), nn.ReLU(True), nn.Conv2d(in_dim, 16, 7), # 224 >> 218 nn.BatchNorm2d(16), nn.ReLU(inplace=True), nn.MaxPool2d(2, 2), # 218 >> 109 nn.ReLU(True), nn.Conv2d(16, 32, 5), # 105 nn.BatchNorm2d(32), nn.ReLU(True), nn.Conv2d(32, 64, 5), # 101 nn.BatchNorm2d(64), nn.ReLU(True), nn.Conv2d(64, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.ReLU(True), nn.MaxPool2d(2, 2), # 101 >> 50 nn.Conv2d(64, 128, 3, 1, 1), # nn.BatchNorm2d(128), nn.ReLU(True), nn.MaxPool2d(3), # 50 >> 16 ) self.fc = nn.Sequential( nn.Linear(128*16*16, 120), nn.BatchNorm1d(120), nn.ReLU(True), nn.Linear(120, n_class)) def forward(self, x): out = self.cnn(x) out = self.fc(out.view(-1, 128*16*16)) return out# 输入3层rgb ,输出 分类 2 model = CNN(3, 2)
新闻热点
疑难解答