当前位置:   article > 正文

视觉入门必备实战--pytorch--阿里天池大赛--街景字符--手把手指导_pytorch怎么打比赛

pytorch怎么打比赛

目录

前言:

用到的库:

1、数据准备

2、数据加载

3、创建Dataset类

pytorch --数据加载之 Dataset 与DataLoader详解

4、数据增强、创建DataLoader

5、搭建模型:

6、模型的训练

7、模型预测结果

8、成绩提交

前言:

目前阿里天池大赛正式赛已经结束了,还有一个长期赛同学们可以参加,增加自己的cv基础知识

天池大数据竞赛_天池大赛-阿里云天池

这里就是天池大赛的官方网址啦,想打比赛的小伙伴们可以点击上方的链接注册,里面有很多数据分析,视觉检测以及算法等等的比赛,同时还有很多入门比赛,大家都可以尝试学习

话不多说,正式开始:

备注:默认同学们已经配置好pytorch环境了哈,当然,遇到临时用到的库,再安装也行

基本的流程如下:


用到的库:

  1. import os, sys, glob, shutil, json
  2. os.environ["CUDA_VISIBLE_DEVICES"] = '0'
  3. import cv2
  4. from PIL import Image
  5. import numpy as np
  6. from tqdm import tqdm, tqdm_notebook
  7. # %pylab inline
  8. import torch
  9. torch.manual_seed(0)
  10. torch.backends.cudnn.deterministic = False
  11. torch.backends.cudnn.benchmark = True

1、数据准备

进入天池大赛官网,报名就可以获取 数据啦,在官网的csv文件中有数据集,验证集还有测试机的下载网址:

2、数据加载

直接上代码:

训练集的数据加载:

  1. train_path = sorted(glob.glob('D:/1wangyong\pytorchtrains\街景字符\Data\mchar_train/*.png'))
  2. train_json = json.load(open('D:/1wangyong\pytorchtrains\街景字符\Data\mchar_train.json'))
  3. train_label = [train_json[x]['label'] for x in train_json]

测试集的数据加载和训练集一样:

  1. val_path = sorted(glob.glob('D:/1wangyong\pytorchtrains\街景字符\Data\mchar_val/*.png'))
  2. val_json = json.load(open('D:/1wangyong\pytorchtrains\街景字符\Data\mchar_val.json'))
  3. val_label = [val_json[x]['label'] for x in val_json]
  4. print(len(val_path), len(val_label))

很多文章都写路径最好别带中文哈,因为运行没出现什么问题,就没改,大家不放心的话,路径使用全英文的也可以

3、创建Dataset类

在pytorch中,数据加载完成之后,就要建立一个Dataset类,这个可以在我的博客:

pytorch --数据加载之 Dataset 与DataLoader详解

中查看详细的描述:

  1. class SVHNDataset(Dataset):
  2. def __init__(self, img_path, img_label, transform=None):
  3. self.img_path = img_path
  4. self.img_label = img_label
  5. if transform is not None:
  6. self.transform = transform
  7. else:
  8. self.transform = None
  9. def __getitem__(self, index):
  10. img = Image.open(self.img_path[index]).convert('RGB')
  11. if self.transform is not None:
  12. img = self.transform(img)
  13. lbl = np.array(self.img_label[index], dtype=np.int_)
  14. lbl = list(lbl) + (5 - len(lbl)) * [10]
  15. return img, torch.from_numpy(np.array(lbl[:5]))
  16. def __len__(self):
  17. return len(self.img_path)


 4、数据增强、创建DataLoader

这个也是训练集与验证集分开:

测试集:

  1. val_loader = torch.utils.data.DataLoader(
  2. SVHNDataset(val_path, val_label,
  3. transforms.Compose([
  4. transforms.Resize((80, 160)),
  5. transforms.RandomCrop((64, 128)),
  6. # transforms.ColorJitter(0.3, 0.3, 0.2),
  7. # transforms.RandomRotation(5),
  8. transforms.ToTensor(),
  9. transforms.Normalize([0.485, 0.456, 0.406], [
  10. 0.229, 0.224, 0.225])
  11. ])),
  12. batch_size=64,
  13. shuffle=False,
  14. num_workers=0,
  15. )

训练集:

  1. train_loader = torch.utils.data.DataLoader(
  2. SVHNDataset(train_path, train_label,
  3. transforms.Compose([
  4. transforms.Resize((80, 160)),
  5. transforms.RandomCrop((64, 128)),
  6. transforms.ColorJitter(0.3, 0.3, 0.2),
  7. transforms.RandomRotation(10),
  8. transforms.ToTensor(),
  9. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
  10. ])),
  11. batch_size=64,
  12. shuffle=True,
  13. num_workers=0,
  14. )

5、搭建模型:

官网模型:

  1. class SVHN_Model1(nn.Module):
  2. def __init__(self):
  3. super(SVHN_Model1, self).__init__()
  4. model_conv = models.resnet18(pretrained=True)
  5. model_conv.avgpool = nn.AdaptiveAvgPool2d(1)
  6. model_conv = nn.Sequential(*list(model_conv.children())[:-1]) # 去除最后一个fc layer
  7. self.cnn = model_conv
  8. self.fc1 = nn.Linear(512, 11)
  9. self.fc2 = nn.Linear(512, 11)
  10. self.fc3 = nn.Linear(512, 11)
  11. self.fc4 = nn.Linear(512, 11)
  12. self.fc5 = nn.Linear(512, 11)
  13. def forward(self, img):
  14. feat = self.cnn(img)
  15. #print(feat.shape)
  16. feat = feat.view(feat.shape[0], -1)
  17. c1 = self.fc1(feat)
  18. c2 = self.fc2(feat)
  19. c3 = self.fc3(feat)
  20. c4 = self.fc4(feat)
  21. c5 = self.fc5(feat)
  22. return c1, c2, c3, c4, c5

官网给出的模型比较基础,如果只用官网,那肯定没有太大意义:

所以针对网络做出以下改进:

我们可以对使用的backbone网络进行一系列的改进:

1、由resnet18换为更大的resnet152

2、为每一个分类模块加上一层全连接隐藏层

3、为隐含层添加dropout

4、给全连接隐藏层中途添加一个relu函数,增强非线性
由resnet18换为resnet152,更深的模型就拥有更好的表达能力,添加一层隐含层同样起到了增加模型拟合能力的作用,与此同时为隐含层添加dropout来进行一个balance,一定程度上防止过拟合。(只是一些改进技巧,并不最优)

改进后的模型定义代码如下:

  1. class SVHN_Model2(nn.Module):
  2. def __init__(self):
  3. super(SVHN_Model2, self).__init__()
  4. # resnet18
  5. model_conv = models.resnet152(pretrained=True)
  6. model_conv.avgpool = nn.AdaptiveAvgPool2d(1)
  7. model_conv = nn.Sequential(*list(model_conv.children())[:-1]) # 去除最后一个fc layer
  8. self.cnn = model_conv
  9. self.hd_fc1 = nn.Linear(512, 256)
  10. self.hd_fc2 = nn.Linear(512, 256)
  11. self.hd_fc3 = nn.Linear(512, 256)
  12. self.hd_fc4 = nn.Linear(512, 256)
  13. self.hd_fc5 = nn.Linear(512, 256)
  14. self.dropout_1 = nn.Dropout(0.25)
  15. self.dropout_2 = nn.Dropout(0.25)
  16. self.dropout_3 = nn.Dropout(0.25)
  17. self.dropout_4 = nn.Dropout(0.25)
  18. self.dropout_5 = nn.Dropout(0.25)
  19. self.fc1 = nn.Linear(256, 11)
  20. self.fc2 = nn.Linear(256, 11)
  21. self.fc3 = nn.Linear(256, 11)
  22. self.fc4 = nn.Linear(256, 11)
  23. self.fc5 = nn.Linear(256, 11)
  24. def forward(self, img):
  25. feat = self.cnn(img)
  26. feat = feat.view(feat.shape[0], -1)
  27. feat1 = torch.relu(self.hd_fc1(feat))
  28. feat2 = torch.relu(self.hd_fc2(feat))
  29. feat3 = torch.relu(self.hd_fc3(feat))
  30. feat4 = torch.relu(self.hd_fc4(feat))
  31. feat5 = torch.relu(self.hd_fc5(feat))
  32. feat1 = self.dropout_1(feat1)
  33. feat2 = self.dropout_2(feat2)
  34. feat3 = self.dropout_3(feat3)
  35. feat4 = self.dropout_4(feat4)
  36. feat5 = self.dropout_5(feat5)
  37. c1 = self.fc1(feat1)
  38. c2 = self.fc2(feat2)
  39. c3 = self.fc3(feat3)
  40. c4 = self.fc4(feat4)
  41. c5 = self.fc5(feat5)
  42. return c1, c2, c3, c4, c5

6、模型的训练

基础的数据加载、数据增强、以及模型搭建都已经完成,就可以正式训练了:

有的同学可能好奇,那之前的Datase类和DataLoader过程是干嘛用的?

还是,同学们可以看看我之前的博客:pytorch --数据加载之 Dataset 与DataLoader详解

这里面有详细的介绍

训练代码:

  1. model = SVHN_Model2()
  2. criterion = nn.CrossEntropyLoss()
  3. optimizer = torch.optim.Adam(model.parameters(), 0.001)
  4. best_loss = 1000.0
  5. use_cuda = True
  6. if use_cuda:
  7. model = model.cuda()
  8. for epoch in range(100):
  9. start = time.time()
  10. print('start', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start)))
  11. train_loss = train(train_loader, model, criterion, optimizer, epoch)
  12. val_loss = validate(val_loader, model, criterion)
  13. val_label = [''.join(map(str, x)) for x in val_loader.dataset.img_label]
  14. val_predict_label = predict(val_loader, model, 1)
  15. val_predict_label = np.vstack([
  16. val_predict_label[:, :11].argmax(1),
  17. val_predict_label[:, 11:22].argmax(1),
  18. val_predict_label[:, 22:33].argmax(1),
  19. val_predict_label[:, 33:44].argmax(1),
  20. val_predict_label[:, 44:55].argmax(1),
  21. ]).T
  22. val_label_pred = []
  23. for x in val_predict_label:
  24. val_label_pred.append(''.join(map(str, x[x != 10])))
  25. val_char_acc = np.mean(np.array(val_label_pred) == np.array(val_label))
  26. end = time.time()
  27. print('end', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(end)))
  28. time_cost = end - start
  29. print(
  30. 'Epoch: {0}, Train loss: {1} \t Val loss: {2}, time_cost: {3}'.format(
  31. epoch,
  32. train_loss,
  33. val_loss,
  34. time_cost))
  35. print('Val Acc', val_char_acc)
  36. # 记录下验证集精度
  37. if val_loss < best_loss:
  38. best_loss = val_loss
  39. # print('Find better model in Epoch {0}, saving model.'.format(epoch))
  40. torch.save(model.state_dict(), './model.pt')

我在训练代码中加了一些,开始时间以及结束时间的记录,看一下网络迭代一次额所需时间。不需要的同学可以直接注释掉就OK

如果选用的优化器是Adam的话,大概20轮之内就训练完成了,SGD的话,需要训练久一点:

上述代码使用的Adam

7、模型预测结果

在上述的过程中,我们已经完成了模型的训练了,并且保存了训练最好的模型,我们只需要把模型拿出来做测试就好了:

代码如下:

  1. model = SVHN_Model1().cuda()
  2. test_path = sorted(glob.glob('D:/1wangyong\pytorchtrains\街景字符\Data\mchar_test_a/*.png'))
  3. # test_json = json.load(open('../input/test.json'))
  4. test_label = [[1]] * len(test_path)
  5. # print(len(test_path), len(test_label))
  6. test_loader = torch.utils.data.DataLoader(
  7. SVHNDataset(test_path, test_label,
  8. transforms.Compose([
  9. transforms.Resize((68, 136)),
  10. transforms.RandomCrop((64, 128)),
  11. # transforms.ColorJitter(0.3, 0.3, 0.2),
  12. # transforms.RandomRotation(5),
  13. transforms.ToTensor(),
  14. transforms.Normalize([0.485, 0.456, 0.406], [
  15. 0.229, 0.224, 0.225])
  16. ])),
  17. batch_size=40,
  18. shuffle=False,
  19. num_workers=0,
  20. )
  21. # 加载保存的最优模型
  22. model.load_state_dict(torch.load('D:/Projects/wordec/model.pt'))
  23. test_predict_label = predict(test_loader, model, 1)
  24. print(test_predict_label.shape)
  25. print('test_predict_label', test_predict_label)
  26. test_label = [''.join(map(str, x)) for x in test_loader.dataset.img_label]
  27. # print('test_label', test_label)
  28. test_predict_label = np.vstack([
  29. test_predict_label[:, :11].argmax(1),
  30. test_predict_label[:, 11:22].argmax(1),
  31. test_predict_label[:, 22:33].argmax(1),
  32. test_predict_label[:, 33:44].argmax(1),
  33. test_predict_label[:, 44:55].argmax(1),
  34. ]).T
  35. test_label_pred = []
  36. for x in test_predict_label:
  37. test_label_pred.append(''.join(map(str, x[x != 10])))
  38. # print("test_label_pred", len(test_label_pred))
  39. df_submit = pd.read_csv('D:/Projects/wordec/input/test_A_sample_submit.csv')
  40. df_submit['file_code'] = test_label_pred
  41. df_submit.to_csv('submit_1018.csv', index=None)
  42. print("finished")

完成上述过程,同学们就已经完成了,一个基础的训练啦。是不是有点小激动呢?

8、成绩提交

进入刚刚的天池大赛官网,找到相关的比赛,提交结果就可以啦!!

备注:(结果就是第七步保存的文件)

快去查看自己的排名吧!!! 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/413929
推荐阅读
相关标签
  

闽ICP备14008679号