哪里学的?指路👇 小破站:深度学习-图像分类(霹雳吧啦Wz) 其他人整理的笔记CSDN:fun1024 大佬们都很牛🐮 另外,这是学完之后的复盘笔记
首先安装pytorch,官网合适版本cmd命令安装.
配置pycharm的python环境与默认的要一致,不然包包不互通.
Pytorch Tensor的通道顺序:[batch,channel,height,width]
Result
跑了两张dog和car都识别错的,找了张plane识别对了. (图片是自己另外找的,随便找,放到文件里路径写得对都没事)
Model
import torch.nn as nn
import torch.nn.functional as F
calss LeNet(nn.Module):
def__init__(self):
super(LeNet,self).__init__()
self.conv1 = nn.Conv2d(3, 16, 5)
self.pool1 = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16, 32, 5)
self.pool2 = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(32*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.pool1(x)
x = F.relu(self.conv2(x))
x = self.pool2(x)
x = x.view(-1, 32*5*5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
计算经卷积后输出尺寸
o
u
t
p
u
t
=
W
?
F
+
2
P
S
+
1
output=\frac{W-F+2P}{S}+1
output=SW?F+2P?+1 其中,输入图片size=WxW 卷积核size=FxF 步距stride=S padding像素数P
Train
import torch
import torchvision
import torch.nn as nn
from model import LeNet
import torch.optim as optim
import torchvision.transforms as transforms
def main():
transform = transform.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5),(0.5, 0.5, 0.5))])
train_set = torchvision.datasets.CIFAR10(root='./data',tarin=True,download=True,transform=transform)
train_loader = torch.utils.data.DataLoader(train_set,batch_size=36,shuffle=True,num_workers=0)
val_set = torchvision.datasets.CIFAR10(root='./data',train=False,download=True,transform=transform)
val_loader = torch.utils.data.DataLoader(val_set,batch_size=5000,shuffle=False,num_workers=0)
val_data_iter = iter(val_loader)
val_image,val_label = val_data_iter.next()
calsses = ('plane','car','bird','cat','deer','dog','frog','horse','ship','truck')
net = LeNet()
loss_function = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(),lr=0.001)
for epoch in range(5):
running_loss = 0.0
for step, data in enumerate(train_loader, start=0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = loss_function(outputs, lables)
loss.backward()
optimizer.step()
running_loss +=loss.item()
if step % 500 ==499:
with torch.no_grad():
outputs = net(val_image)
predict_y = torch.max(outputs, dim=1)[1]
accuracy = torch.eq(predict_y, val_label).sum().item() / val_label.size(0)
print('[%d,%5d] train_loss:%3f test_accuracy:%.3f'%(epoch+1,step+1,running_loss / 500,accuracy))
running_loss = 0.0
print('Finshed Training')
save_path = './Lenet.pth'
torch.save(net.state_dict(),save_path)
if __name__ == '__main__':
main()
Predict
import torch
import torchvision.transforms as transforms
from PIL import Image
from model import LeNet
def main():
transform = transforms.Compose(
[transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
net = LeNet()
net.load_state_dict(torch.load('Lenet.pth'))
im = Image.open('3.jpg')
im = transform(im)
im = torch.unsqueeze(im, dim=0)
with torch.no_grad():
outputs = net(im)
predict = torch.max(outputs, dim=1)[1].numpy()
print(classes[int(predict)])
if __name__ == '__main__':
main()
三个部分均保存为.py文件一个文件夹下运行即可
|