├── .gitignore ├── LICENSE ├── README.md ├── main.py ├── models ├── __init__.py ├── lenet.py └── resnet.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.pyc 3 | .DS_Store 4 | *.xml 5 | *.iml 6 | images/ 7 | checkpoint/ 8 | 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyTorch_UCMerced_LandUse 2 | ## Dataset 3 | 4 | [UC Merced Land Use Dataset](http://weegee.vision.ucmerced.edu/datasets/landuse.html) 5 | 6 | ## Result 7 | **lr = 0.001, batch_size = 8** 8 | 9 | Epoch|4|100|200 10 | ---|---|---|--- 11 | ResNet18|45.48%|86.19%|91.90% 12 | ResNet34|44.05%|79.52%|79.52% 13 | 14 | ## File structure 15 | ``` 16 | ├── Images 17 | │   ├── agricultural 18 | │   ├── airplane 19 | │   ├── baseballdiamond 20 | │   ├── beach 21 | │   ├── buildings 22 | │   ├── chaparral 23 | │   ├── denseresidential 24 | │   ├── forest 25 | │   ├── freeway 26 | │   ├── golfcourse 27 | │   ├── harbor 28 | │   ├── intersection 29 | │   ├── mediumresidential 30 | │   ├── mobilehomepark 31 | │   ├── overpass 32 | │   ├── parkinglot 33 | │   ├── river 34 | │   ├── runway 35 | │   ├── sparseresidential 36 | │   ├── storagetanks 37 | │   └── tenniscourt 38 | ├── README.md 39 | ├── checkpoint 40 | │   ├── LeNet 41 | │   │   └── ckpt.pth 42 | │   └── ResNet 43 | │   └── ckpt.pth 44 | ├── main.py 45 | ├── models 46 | │   ├── __init__.py 47 | │   ├── lenet.py 48 | │   └── resnet.py 49 | └── utils.py 50 | 51 | ``` 52 | 53 | ## Reference 54 | 1. Yi Yang and Shawn Newsam, "[Bag-Of-Visual-Words and Spatial Extensions for Land-Use Classification](http://faculty.ucmerced.edu/snewsam/papers/Yang_ACMGIS10_BagOfVisualWords.pdf)," ACM SIGSPATIAL International Conference on Advances in Geographic Information Systems (ACM GIS), 2010. -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.backends.cudnn as cudnn 3 | import torchvision.datasets as datasets 4 | from torchvision.transforms import transforms 5 | from torch.utils.data import DataLoader 6 | from torch.utils.data import random_split 7 | import torch.optim as optim 8 | from torch.optim import Adam 9 | 10 | import os 11 | import argparse 12 | 13 | from models import * 14 | from utils import get_progress_bar, update_progress_bar, ApplyTransform 15 | 16 | # 0. Define some parameters 17 | parser = argparse.ArgumentParser(description='UCMerced Land Use') 18 | parser.add_argument('--lr', default=0.001, type=float, help='learning rate') 19 | parser.add_argument('--resume', '-r', default=False, action='store_true', help='resume from checkpoint') 20 | args = parser.parse_args() 21 | 22 | # os.environ["CUDA_VISIBLE_DEVICES"] = "0, 1" 23 | device = 'cuda' if torch.cuda.is_available() else 'cpu' 24 | 25 | # 1. Load and normalizing dataset 26 | # 1. Data augmentation 27 | transforms_train = transforms.Compose([ 28 | transforms.RandomCrop(32, padding=4), 29 | transforms.RandomHorizontalFlip(), 30 | transforms.ToTensor(), 31 | transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)) 32 | ]) 33 | 34 | transforms_test = transforms.Compose([ 35 | transforms.RandomCrop(32, padding=4), 36 | transforms.ToTensor(), 37 | transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)) 38 | ]) 39 | 40 | total_dataset = datasets.ImageFolder('Images', transform=None) 41 | train_size = int(0.8 * len(total_dataset)) 42 | test_size = len(total_dataset) - train_size 43 | 44 | train_dataset, test_dataset = random_split(total_dataset, [train_size, test_size]) 45 | 46 | train_dataset = ApplyTransform(train_dataset, transform=transforms_train) 47 | test_dataset = ApplyTransform(test_dataset, transform=transforms_test) 48 | 49 | train_dataset_loader = DataLoader(dataset=train_dataset, batch_size=16) 50 | test_dataset_loader = DataLoader(dataset=test_dataset, batch_size=16) 51 | 52 | # 2. Define a Convolutional Network 53 | 54 | 55 | 56 | # net, model_name = LeNet(), 'LeNet' 57 | # net, model_name = ResNet18(), 'ResNet18' 58 | net, model_name = ResNet34(), 'ResNet34' 59 | 60 | print(model_name + ' is ready!') 61 | 62 | net = net.to(device) 63 | # Use GPU or not 64 | if device == 'cuda': 65 | net = torch.nn.DataParallel(net) 66 | print("Let's use", torch.cuda.device_count(), "GPUs") 67 | cudnn.benchmark = True 68 | 69 | start_epoch = 0 70 | best_acc = 0 71 | 72 | if args.resume == True: 73 | print('==> Resuming from checkpoint..') 74 | assert os.path.isdir('checkpoint/' + model_name), 'Error : no checkpoint directory found!' 75 | checkpoint = torch.load('./checkpoint/' + model_name + '/ckpt.pth') 76 | net.load_state_dict(checkpoint['net']) 77 | best_acc = checkpoint['acc'] 78 | start_epoch = checkpoint['epoch'] + 1 79 | 80 | # 3. Define a loss function 81 | criterion = nn.CrossEntropyLoss() 82 | # optimizer = Adam(net.parameters()) 83 | optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4) 84 | 85 | 86 | # 4. Train the network on the training data 87 | 88 | def train(epoch): 89 | running_loss = 0.0 90 | net.train() 91 | correct = 0 92 | total = 0 93 | progress_bar_obj = get_progress_bar(len(train_dataset_loader)) 94 | print('Epoch', epoch, 'Train') 95 | for i, (inputs, labels) in enumerate(train_dataset_loader): 96 | inputs, labels = inputs.to(device), labels.to(device) # this line doesn't work when use cpu 97 | # zero the parameter gradients 98 | optimizer.zero_grad() 99 | 100 | outputs = net(inputs) 101 | loss = criterion(outputs, labels) 102 | loss.backward() 103 | optimizer.step() 104 | 105 | running_loss += loss.item() 106 | _, predicted = outputs.max(1) 107 | total += labels.size(0) 108 | correct += predicted.eq(labels).sum().item() 109 | update_progress_bar(progress_bar_obj, index=i, loss=(running_loss / (i + 1)), acc=100. * (correct / total), 110 | c=correct, t=total) 111 | 112 | 113 | # 5. Test Network 114 | def test(epoch): 115 | global best_acc 116 | net.eval() 117 | 118 | correct = 0 119 | total = 0 120 | test_loss = 0 121 | 122 | with torch.no_grad(): 123 | for i, (images, labels) in enumerate(test_dataset_loader): 124 | images, labels = images.to(device), labels.to(device) 125 | outputs = net(images) 126 | loss = criterion(outputs, labels) 127 | 128 | test_loss += loss.item() 129 | 130 | _, predicted = torch.max(outputs, 1) 131 | total += labels.size(0) 132 | correct += predicted.eq(labels).sum().item() 133 | 134 | acc = 100 * correct / total 135 | print() 136 | print("Accuracy of whole test dataset: %.2f %%" % acc) 137 | 138 | if acc > best_acc: 139 | state = { 140 | 'net': net.state_dict(), 141 | 'acc': acc, 142 | 'epoch': epoch, 143 | } 144 | if not os.path.isdir('checkpoint/' + model_name): 145 | os.mkdir('checkpoint/' + model_name) 146 | torch.save(state, './checkpoint/' + model_name + '/ckpt.pth') 147 | best_acc = acc 148 | print('Acc > best_acc, Saving net, acc') 149 | 150 | 151 | for epoch in range(start_epoch, start_epoch + 150): 152 | train(epoch) 153 | test(epoch) 154 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | from .lenet import * 2 | from .resnet import * -------------------------------------------------------------------------------- /models/lenet.py: -------------------------------------------------------------------------------- 1 | '''LeNet in PyTorch''' 2 | 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | 7 | class LeNet(nn.Module): 8 | def __init__(self): 9 | super(LeNet, self).__init__() 10 | self.conv1 = nn.Conv2d(3, 6, 5) 11 | self.pool = nn.MaxPool2d(2, 2) 12 | self.conv2 = nn.Conv2d(6, 16, 5) 13 | self.fc1 = nn.Linear(16 * 5 * 5, 120) 14 | self.fc2 = nn.Linear(120, 84) 15 | self.fc3 = nn.Linear(84, 21) 16 | 17 | def forward(self, x): 18 | x = self.pool(F.relu(self.conv1(x))) 19 | x = self.pool(F.relu(self.conv2(x))) 20 | x = x.view(-1, 16 * 5 * 5) 21 | x = F.relu(self.fc1(x)) 22 | x = F.relu(self.fc2(x)) 23 | x = self.fc3(x) 24 | return x 25 | 26 | 27 | ''' 28 | if the input image was resized to 64 * 64 29 | the input of fc1 should be 16 * 13 * 13 30 | 31 | 64 - 4 = 60 32 | 60 / 2 = 30 33 | 30 - 4 = 26 34 | 26 / 2 = 13 35 | ''' 36 | 37 | -------------------------------------------------------------------------------- /models/resnet.py: -------------------------------------------------------------------------------- 1 | ''' 2 | ResNet 3 | ''' 4 | 5 | import torch 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | 9 | 10 | class BasicBlock(nn.Module): 11 | expansion = 1 12 | 13 | def __init__(self, in_planes, planes, stride=1): 14 | super(BasicBlock, self).__init__() 15 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 16 | self.bn1 = nn.BatchNorm2d(planes) 17 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) 18 | self.bn2 = nn.BatchNorm2d(planes) 19 | 20 | self.shortcut = nn.Sequential() 21 | if stride != 1 or in_planes != self.expansion * planes: 22 | self.shortcut = nn.Sequential( 23 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), 24 | nn.BatchNorm2d(self.expansion * planes) 25 | ) 26 | 27 | def forward(self, x): 28 | out = F.relu(self.bn1(self.conv1(x))) 29 | out = self.bn2(self.conv2(out)) 30 | out += self.shortcut(x) 31 | out = F.relu(out) 32 | return out 33 | 34 | 35 | class Bottleneck(nn.Module): 36 | expansion = 4 37 | 38 | def __init__(self, in_planes, planes, stride=1): 39 | super(Bottleneck, self).__init__() 40 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) 41 | self.bn1 = nn.BatchNorm2d(planes) 42 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 43 | self.bn2 = nn.BatchNorm2d(planes) 44 | self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False) 45 | self.bn3 = nn.BatchNorm2d(self.expansion * planes) 46 | 47 | self.shortcut = nn.Sequential() 48 | if stride != 1 or in_planes != self.expansion * planes: 49 | self.shortcut = nn.Sequential( 50 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), 51 | nn.BatchNorm2d(self.expansion * planes) 52 | ) 53 | 54 | def forward(self, x): 55 | out = F.relu(self.bn1(self.conv1(x))) 56 | out = F.relu(self.bn2(self.conv2(out))) 57 | out = self.bn3(self.conv3(out)) 58 | out += self.shortcut(x) 59 | out = F.relu(out) 60 | return out 61 | 62 | 63 | class ResNet(nn.Module): 64 | def __init__(self, block, num_blocks, num_classes=21): 65 | super(ResNet, self).__init__() 66 | self.in_planes = 64 67 | 68 | self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) 69 | self.bn1 = nn.BatchNorm2d(64) 70 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) 71 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) 72 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) 73 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) 74 | self.linear = nn.Linear(512 * block.expansion, num_classes) 75 | 76 | def _make_layer(self, block, planes, num_blocks, stride): 77 | strides = [stride] + [1] * (num_blocks - 1) 78 | layers = [] 79 | for stride in strides: 80 | layers.append(block(self.in_planes, planes, stride)) 81 | self.in_planes = planes * block.expansion 82 | return nn.Sequential(*layers) 83 | 84 | def forward(self, x): 85 | out = F.relu(self.bn1(self.conv1(x))) 86 | out = self.layer1(out) 87 | out = self.layer2(out) 88 | out = self.layer3(out) 89 | out = self.layer4(out) 90 | out = F.avg_pool2d(out, 4) 91 | out = out.view(out.size(0), -1) 92 | out = self.linear(out) 93 | return out 94 | 95 | 96 | def ResNet18(): 97 | return ResNet(BasicBlock, [2, 2, 2, 2]) 98 | 99 | 100 | def ResNet34(): 101 | return ResNet(BasicBlock, [3, 4, 6, 3]) 102 | 103 | 104 | def ResNet50(): 105 | return ResNet(Bottleneck, [3, 4, 6, 3]) 106 | 107 | 108 | def ResNet101(): 109 | return ResNet(Bottleneck, [3, 4, 23, 3]) 110 | 111 | 112 | def ResNet152(): 113 | return ResNet(Bottleneck, [3, 8, 36, 3]) 114 | 115 | 116 | def test(): 117 | net = ResNet18() 118 | y = net(torch.randn(1, 3, 32, 32)) 119 | print(y.size()) 120 | 121 | # test() 122 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/env python 2 | #-*- coding:utf-8 _*- 3 | """ 4 | @author:yaoli 5 | @file: utils.py 6 | @time: 2019/12/19 7 | """ 8 | import progressbar 9 | from torch.utils.data import Dataset 10 | 11 | 12 | def get_progress_bar(total): 13 | format_custom_text = progressbar.FormatCustomText( 14 | 'Loss: %(loss).3f | Acc: %(acc).3f%% (%(c)d/%(t)d)', 15 | dict( 16 | loss=0, 17 | acc=0, 18 | c=0, 19 | t=0, 20 | ), 21 | ) 22 | prog_bar = progressbar.ProgressBar(0, total, widgets=[ 23 | progressbar.Counter(), ' of {} '.format(total), 24 | progressbar.Bar(), 25 | ' ', progressbar.ETA(), 26 | ' ', format_custom_text 27 | ]) 28 | return prog_bar, format_custom_text 29 | 30 | 31 | def update_progress_bar(progress_bar_obj, index=None, loss=None, acc=None, c=None, t=None, ): 32 | prog_bar, format_custom_text = progress_bar_obj 33 | format_custom_text.update_mapping(loss=loss, acc=acc, c=c, t=t) 34 | prog_bar.update(index) 35 | 36 | 37 | def format_time(seconds): 38 | days = int(seconds / 3600 / 24) 39 | seconds = seconds - days * 3600 * 24 40 | hours = int(seconds / 3600) 41 | seconds = seconds - hours * 3600 42 | minutes = int(seconds / 60) 43 | seconds = seconds - minutes * 60 44 | secondsf = int(seconds) 45 | seconds = seconds - secondsf 46 | millis = int(seconds * 1000) 47 | 48 | f = '' 49 | i = 1 50 | if days > 0: 51 | f += str(days) + 'D' 52 | i += 1 53 | if hours > 0 and i <= 2: 54 | f += str(hours) + 'h' 55 | i += 1 56 | if minutes > 0 and i <= 2: 57 | f += str(minutes) + 'm' 58 | i += 1 59 | if secondsf > 0 and i <= 2: 60 | f += str(secondsf) + 's' 61 | i += 1 62 | if millis > 0 and i <= 2: 63 | f += str(millis) + 'ms' 64 | i += 1 65 | if f == '': 66 | f = '0ms' 67 | return f 68 | 69 | class ApplyTransform(Dataset): 70 | """ 71 | Apply transformations to a Dataset 72 | 73 | Arguments: 74 | dataset (Dataset): A Dataset that returns (sample, target) 75 | transform (callable, optional): A function/transform to be applied on the sample 76 | target_transform (callable, optional): A function/transform to be applied on the target 77 | 78 | """ 79 | def __init__(self, dataset, transform=None, target_transform=None): 80 | self.dataset = dataset 81 | self.transform = transform 82 | self.target_transform = target_transform 83 | # yes, you don't need these 2 lines below :( 84 | if transform is None and target_transform is None: 85 | print("Am I a joke to you? :)") 86 | 87 | def __getitem__(self, idx): 88 | sample, target = self.dataset[idx] 89 | if self.transform is not None: 90 | sample = self.transform(sample) 91 | if self.target_transform is not None: 92 | target = self.target_transform(target) 93 | return sample, target 94 | 95 | def __len__(self): 96 | return len(self.dataset) 97 | 98 | ''' 99 | class ApplyTransform is referenced from https://stackoverflow.com/questions/56582246/correct-data-loading-splitting-and-augmentation-in-pytorch 100 | ''' --------------------------------------------------------------------------------