因为代码里面有比较详细的注记,这里就不啰嗦了。注意,如果是pytorch1.6以下版本,在计算除法时会有不同,具体查看该版本下除法计算的文档。直接上干货了。
from torch import nn
from torchvision import models,datasets,transforms
import torch as tc
from torch.autograd import Variable
from torch.utils.data import DataLoader
from matplotlib import pyplot as plt
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
batch_size = 8
learning_rate = 0.0002
epoc = 10
train_transforms = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((.5, .5, .5), (.5, .5, .5))
])
val_transforms = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.ToTensor(),
transforms.Normalize((.5, .5, .5), (.5, .5, .5))
])
train_dir = 'E:/pydata/cats_and_dogs_small/train'
train_datasets = datasets.ImageFolder(train_dir,transform=train_transforms)
train_dataloader = DataLoader(train_datasets,batch_size=batch_size,shuffle=True)
val_dir