Advertisement
Guest User

CNNDog

a guest
Mar 21st, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.99 KB | None | 0 0
  1. import os
  2. from torchvision import datasets
  3. import torch
  4. import numpy as np
  5.  
  6. # check if CUDA is available
  7. train_on_gpu = torch.cuda.is_available()
  8.  
  9. if not train_on_gpu:
  10.     print('CUDA is not available.  Training on CPU ...')
  11. else:
  12.     print('CUDA is available!  Training on GPU ...')
  13.  
  14.  
  15. ### TODO: Write data loaders for training, validation, and test sets
  16. ## Specify appropriate transforms, and batch_sizes
  17. from torchvision import datasets
  18. import torchvision.transforms as transforms
  19. from torch.utils.data import DataLoader
  20. from torch.utils.data.sampler import SubsetRandomSampler
  21. from PIL import ImageFile
  22. ImageFile.LOAD_TRUNCATED_IMAGES = True
  23.  
  24. # number of subprocesses to use for data loading
  25. num_workers = 0
  26. # how many samples per batch to load
  27. batch_size = 20
  28. # percentage of training set to use as validation
  29. image_size=256
  30. rootTrain="/data/dog_images/train/"
  31. rootTest="/data/dog_images/test/"
  32. rootValid="/data/dog_images/valid/"
  33. transform = transforms.Compose([
  34.                 transforms.Resize((image_size,image_size)),
  35.                 transforms.ToTensor(),
  36.                 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
  37. ])
  38. transform2 = transforms.Compose([
  39.                 transforms.Resize((image_size,image_size)),
  40.                 transforms.RandomHorizontalFlip(p=0.99), # randomly flip and rotate
  41.                 transforms.RandomRotation(60),
  42.                 transforms.ToTensor(),
  43.                 transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
  44. ])
  45. train_data1 = datasets.ImageFolder(root=rootTrain, transform=transform)
  46. print(len(train_data1))
  47. train_data2 = datasets.ImageFolder(root=rootTrain, transform=transform)
  48. train_data = train_data1 + train_data2
  49. print(len(train_data))
  50.  
  51. test_data = datasets.ImageFolder(root=rootTest, transform=transform)
  52. valid_data = datasets.ImageFolder(root=rootValid, transform=transform)
  53.  
  54.  
  55. # prepare data loaders (combine dataset and sampler)
  56. train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers, shuffle=True)
  57. valid_loader = torch.utils.data.DataLoader(valid_data, batch_size=batch_size, num_workers=num_workers, shuffle=True)
  58. test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers, shuffle=True)
  59.  
  60. classes = []
  61. for i in range(0,133):
  62.     classes.append(str(i))
  63.  
  64. print (classes)
  65. #Visualize a Batch of Training Data
  66. import matplotlib.pyplot as plt
  67. %matplotlib inline
  68.  
  69. # helper function to un-normalize and display an image
  70. def imshow(img):
  71.     img = img / 2 + 0.5  # unnormalize
  72.     plt.imshow(np.transpose(img, (1, 2, 0)))  # convert from Tensor image
  73. # obtain one batch of training images
  74. dataiter = iter(train_loader)
  75. images, labels = dataiter.next()
  76. images = images.numpy() # convert images to numpy for display
  77.  
  78. # plot the images in the batch, along with the corresponding labels
  79. fig = plt.figure(figsize=(25, 4))
  80. # display 20 images
  81. for idx in np.arange(20):
  82.     ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])
  83.     imshow(images[idx])
  84.     ax.set_title(classes[labels[idx]])
  85.  
  86.  
  87.  
  88. #----------------------------------------- Arch ----------------------------------
  89.  
  90. import torch.nn as nn
  91. import torch.nn.functional as F
  92.  
  93. # define the CNN architecture
  94. class Net(nn.Module):
  95.     def __init__(self):
  96.         super(Net, self).__init__()
  97.         # convolutional layer
  98.         #32x32x3 image
  99.         #(n-2p+f)/s + 1
  100.         self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
  101.         self.conv3 = nn.Conv2d(16, 32, 3, padding=1)
  102.         self.conv4 = nn.Conv2d(32, 64, 3, padding=1)
  103.  
  104.         self.pool = nn.MaxPool2d(2, 2)
  105.         self.conv1_bn = nn.BatchNorm2d(16)        
  106.         self.conv2_bn = nn.BatchNorm2d(32)        
  107.         self.conv3_bn = nn.BatchNorm2d(64)        
  108.  
  109.         self.fc1 = nn.Linear(32*32*64, 500)
  110.         self.fc3 = nn.Linear(500, 133)
  111.         self.dropout = nn.Dropout(p=0.3)
  112.  
  113.     def forward(self, x):
  114.         x = self.conv1_bn((self.pool(F.relu(self.conv1(x)))))
  115.         x = self.conv2_bn(self.pool(F.relu(self.conv3(x))))
  116.         x = self.conv3_bn(self.pool(F.relu(self.conv4(x))))
  117.         x = x.view(-1, 32*32*64)
  118.         x = self.dropout(F.relu(self.fc1(x)))
  119.         x = self.fc3(x)
  120.         return x
  121.  
  122. ## complete this function
  123. def weights_init_normal(m):
  124.     '''Takes in a module and initializes all linear layers with weight
  125.       values taken from a normal distribution.'''
  126.    
  127.     classname = m.__class__.__name__
  128.     # for every Linear layer in a model
  129.     # m.weight.data shoud be taken from a normal distribution
  130.     # m.bias.data should be 0
  131.     if classname.find('Linear') != -1:
  132.         # get the number of the inputs
  133.         n = m.in_features
  134.         y = 1.0/np.sqrt(n)
  135.         m.weight.data.normal_(0,y)
  136.         m.bias.data.fill_(0)
  137.  
  138. # create a new model with the rule-based, NORMAL weights
  139. model_scratch = Net()
  140. model_scratch.apply(weights_init_normal)
  141.  
  142. print(model_scratch)
  143.  
  144. # move tensors to GPU if CUDA is available
  145. if train_on_gpu:
  146.     model_scratch.cuda()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement