基于pytorch的图像分类网络搭建思路 #更新中 本文基于龙良曲的pytorch深度学习代码进行总结 Tips: 1.代码参考龙良曲老师的github 63节迁移学习 https://github.com/dragen1860/Deep-Learning-with-PyTorch-Tutorials 有改动,其中检测部分是自己写的 2.本文中引入visdom进行实时训练情况监测,所以在运行前请在终端启动visdom
python -m visdom.server
1.数据集部分
import torch
import os, glob
import random, csv
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
class Pokemon(Dataset):
def __init__(self, root, resize, mode):
super(Pokemon, self).__init__()
self.root = root
self.resize = resize
self.name2label = {}
for name in sorted(os.listdir(os.path.join(root))):
if not os.path.isdir(os.path.join(root, name)):
continue
self.name2label[name] = len(self.name2label.keys())
print(self.name2label)
print(self.name2label.keys())
self.images, self.labels = self.load_csv('images.csv')
if mode == 'train':
self.images = self.images[:int(0.6*len(self.images))]
self.labels = self.labels[:int(0.6*len(self.labels))]
elif mode == 'val':
self.images = self.images[int(0.6*len(self.images)):int(0.8*len(self.images))]
self.labels = self.labels[int(0.6*len(self.labels)):int(0.8*len(self.labels))]
else:
self.images = self.images[int(0.8*len(self.images)):]
self.labels = self.labels[int(0.8*len(self.labels)):]
def load_csv(self, filename):
if not os.path.exists(os.path.join(self.root,filename)):
images = []
for name in self.name2label.keys():
images += glob.glob(os.path.join(self.root, name, '*.png'))
images += glob.glob(os.path.join(self.root, name, '*.jpg'))
images += glob.glob(os.path.join(self.root, name, '*.jpeg'))
random.shuffle(images)
with open(os.path.join(self.root,filename),mode='w',newline='') as f:
writer = csv.writer(f)
for img in images:
name = img.split(os.sep)[-2]
label = self.name2label[name]
writer.writerow([img,label])
print('written into csv file',filename)
images, labels = [],[]
with open(os.path.join(self.root,filename)) as f:
reader = csv.reader(f)
for row in reader:
img, label = row
label = int(label)
images.append(img)
labels.append(label)
assert len(images) == len(labels)
return images , labels
def __len__(self):
return len(self.images)
def denormalize(self,x_hat):
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
mean = torch.tensor(mean).unsqueeze(1).unsqueeze(1)
std = torch.tensor(std).unsqueeze(1).unsqueeze(1)
x = x_hat * std + mean
return x
def __getitem__(self, idx):
img, label = self.images[idx], self.labels[idx]
tf = transforms.Compose([
lambda x:Image.open(x).convert('RGB'),
transforms.Resize((int(self.resize*1.25), int(self.resize*1.25))),
transforms.RandomRotation(15),
transforms.CenterCrop(self.resize),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
img = tf(img)
label = torch.tensor(label)
return img, label
def main():
import visdom
import time
viz = visdom.Visdom()
db = Pokemon('pokemon', 64, 'train')
x,y = next(iter(db))
print('sample:',x.shape,y.shape,y)
viz.image(db.denormalize(x),win='sample_x',opts=dict(title='sample_x'))
loader = DataLoader(db,batch_size=32,shuffle=True,num_workers=4)
for x,y in loader:
viz.images(db.denormalize(x),nrow=8,win='batch',opts=dict(title='batch'))
viz.text(str(y.numpy()),win='label',opts=dict(title='batch-y'))
time.sleep(10)
if __name__ == '__main__':
main()
2.网络训练
import torch
from torch import optim, nn
import visdom
import torchvision
from torch.utils.data import DataLoader
from pokemon import Pokemon
from torchvision.models import resnet18
from utils import Flatten
batchsz = 32
lr = 5e-4
epochs = 20
device = torch.device('cuda')
torch.manual_seed(1234)
train_db = Pokemon('pokemon', 224, mode='train')
val_db = Pokemon('pokemon', 224, mode='val')
test_db = Pokemon('pokemon', 224, mode='test')
train_loader = DataLoader(train_db, batch_size=batchsz, shuffle=True,
num_workers=4)
val_loader = DataLoader(val_db, batch_size=batchsz, num_workers=2)
test_loader = DataLoader(test_db, batch_size=batchsz, num_workers=2)
viz = visdom.Visdom()
def evalute(model, loader):
model.eval()
correct = 0
total = len(loader.dataset)
for x,y in loader:
x,y = x.to(device), y.to(device)
with torch.no_grad():
logits = model(x)
pred = logits.argmax(dim=1)
correct += torch.eq(pred, y).sum().float().item()
return correct / total
def main():
trained_model = resnet18(pretrained=True)
model = nn.Sequential(*list(trained_model.children())[:-1],
Flatten(),
nn.Linear(512, 5)
).to(device)
optimizer = optim.Adam(model.parameters(), lr=lr)
criteon = nn.CrossEntropyLoss()
best_acc, best_epoch = 0, 0
global_step = 0
viz.line([0], [-1], win='loss', opts=dict(title='loss'))
viz.line([0], [-1], win='val_acc', opts=dict(title='val_acc'))
for epoch in range(epochs):
for step, (x,y) in enumerate(train_loader):
x, y = x.to(device), y.to(device)
model.train()
print(x.size())
logits = model(x)
loss = criteon(logits, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
viz.line([loss.item()], [global_step], win='loss', update='append')
global_step += 1
if epoch % 1 == 0:
val_acc = evalute(model, val_loader)
if val_acc> best_acc:
best_epoch = epoch
best_acc = val_acc
torch.save(model.state_dict(), 'best.mdl')
viz.line([val_acc], [global_step], win='val_acc', update='append')
print('best acc:', best_acc, 'best epoch:', best_epoch)
model.load_state_dict(torch.load('best.mdl'))
print('loaded from ckpt!')
test_acc = evalute(model, test_loader)
print('test acc:', test_acc)
if __name__ == '__main__':
main()
3.验证代码
import torch
from torch import optim, nn
from PIL import Image, ImageDraw, ImageFont
from torchvision import transforms
from torchvision.models import resnet18
import os
resize = 224
device = torch.device('cuda')
weights = 'F:/Deep-Learning-with-PyTorch-Tutorials-master/lesson63-transfer learning/best.mdl'
path = 'images'
def label2name(root, label):
namedic = {}
for name in sorted(os.listdir(os.path.join(root))):
if not os.path.isdir(os.path.join(root, name)):
continue
namedic[len(namedic.keys())] = name
pokemon_name = namedic[label]
return pokemon_name
def creatmodel():
trained_model = resnet18(pretrained=True)
model = nn.Sequential(*list(trained_model.children())[:-1],
nn.Flatten(),
nn.Linear(512, 5)
).to(device)
return model
def getimagelist(source):
rlist = []
for dir, folder, file in os.walk(source):
for i in file:
t = "%s\%s" % (dir, i)
rlist.append(t)
return rlist
def drawimagetext(image, context):
img = Image.open(image)
fnt = ImageFont.truetype("arial.ttf", 40)
d = ImageDraw.Draw(img)
context = str(context)
d.text((10, 10), context, font=fnt, fill=(0, 0, 0))
return img
def main():
model = creatmodel()
model.load_state_dict(torch.load('best.mdl'))
data_transform = transforms.Compose([
lambda x: Image.open(x).convert('RGB'),
transforms.Resize((resize, resize)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
for image in getimagelist(path):
img = data_transform(image)
img = torch.unsqueeze(img, dim=0)
img = img.to(device)
model.eval()
with torch.no_grad():
logits = model(img)
pred = logits.argmax(dim=1)
image_afterdraw = drawimagetext(image, label2name('pokemon', int(pred[0])))
image_afterdraw.show()
if __name__ == '__main__':
main()
|