train_classifier_img.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #!/usr/bin/env python3
  2. import time
  3. import random
  4. import numpy as np
  5. import gym
  6. from gym_minigrid.register import env_list
  7. from gym_minigrid.minigrid import Grid, OBJECT_TO_IDX
  8. import babyai
  9. import matplotlib.pyplot as plt
  10. import torch
  11. import torch.nn as nn
  12. import torch.optim as optim
  13. import torch.nn.functional as F
  14. from torch.autograd import Variable
  15. import torchvision
  16. import numpy as np
  17. import cv2
  18. import PIL
  19. ##############################################################################
  20. def make_var(arr):
  21. arr = np.ascontiguousarray(arr)
  22. #arr = torch.from_numpy(arr).float()
  23. arr = torch.from_numpy(arr)
  24. arr = Variable(arr)
  25. if torch.cuda.is_available():
  26. arr = arr.cuda()
  27. return arr
  28. def init_weights(m):
  29. classname = m.__class__.__name__
  30. if classname.startswith('Conv'):
  31. nn.init.orthogonal_(m.weight.data)
  32. m.bias.data.fill_(0)
  33. elif classname.find('Linear') != -1:
  34. nn.init.xavier_uniform_(m.weight)
  35. m.bias.data.fill_(0)
  36. elif classname.find('BatchNorm') != -1:
  37. m.weight.data.normal_(1.0, 0.02)
  38. m.bias.data.fill_(0)
  39. def num_params(model):
  40. pp=0
  41. for p in list(model.parameters()):
  42. nn=1
  43. for s in list(p.size()):
  44. nn = nn*s
  45. pp += nn
  46. return pp
  47. class Flatten(nn.Module):
  48. """
  49. Flatten layer, to flatten convolutional layer output
  50. """
  51. def forward(self, input):
  52. return input.view(input.size(0), -1)
  53. class Print(nn.Module):
  54. def forward(self, input):
  55. print(input.size())
  56. return input
  57. class Model(nn.Module):
  58. def __init__(self):
  59. super().__init__()
  60. self.layers = nn.Sequential(
  61. nn.Conv2d(in_channels=3, out_channels=16, kernel_size=6, stride=2),
  62. nn.LeakyReLU(),
  63. nn.Conv2d(in_channels=16, out_channels=16, kernel_size=6, stride=2),
  64. nn.LeakyReLU(),
  65. nn.Conv2d(in_channels=16, out_channels=16, kernel_size=6, stride=1),
  66. nn.LeakyReLU(),
  67. nn.Conv2d(in_channels=16, out_channels=16, kernel_size=5, stride=1),
  68. nn.LeakyReLU(),
  69. #Print(),
  70. Flatten(),
  71. nn.Linear(64, 64),
  72. nn.LeakyReLU(),
  73. nn.Linear(64, 2),
  74. )
  75. self.apply(init_weights)
  76. def forward(self, obs):
  77. obs = obs / 16
  78. out = self.layers(obs)
  79. return out
  80. def present_prob(self, obs):
  81. obs = make_var(obs).unsqueeze(0)
  82. logits = self(obs)
  83. probs = F.softmax(logits, dim=-1)
  84. probs = probs.detach().cpu().squeeze().numpy()
  85. return probs[1]
  86. env = gym.make('BabyAI-GoToRedBall-v0')
  87. def sample_batch(batch_size=128):
  88. imgs = []
  89. labels = []
  90. for i in range(batch_size):
  91. obs = env.reset()['image']
  92. ball_visible = ('red', 'ball') in Grid.decode(obs)
  93. obs = env.get_obs_render(obs, tile_size=8, mode='rgb_array')
  94. #plt.imshow(obs)
  95. #plt.show()
  96. obs = obs.transpose([2, 0, 1])
  97. imgs.append(np.copy(obs))
  98. labels.append(ball_visible)
  99. imgs = np.stack(imgs).astype(np.float32)
  100. labels = np.array(labels, dtype=np.long)
  101. return imgs, labels
  102. print('Generating test set')
  103. test_imgs, test_labels = sample_batch(256)
  104. def eval_model(model):
  105. num_true = 0
  106. for idx in range(test_imgs.shape[0]):
  107. img = test_imgs[idx]
  108. label = test_labels[idx]
  109. p = model.present_prob(img)
  110. out_label = p > 0.5
  111. #print(out_label)
  112. if np.equal(out_label, label):
  113. num_true += 1
  114. #else:
  115. # if label:
  116. # print("incorrectly predicted as absent")
  117. # else:
  118. # print("incorrectly predicted as present")
  119. acc = 100 * (num_true / test_imgs.shape[0])
  120. return acc
  121. ##############################################################################
  122. batch_size = 64
  123. model = Model()
  124. model.cuda()
  125. print('Num params:', num_params(model))
  126. optimizer = optim.Adam(
  127. model.parameters(),
  128. lr=5e-4
  129. )
  130. criterion = nn.CrossEntropyLoss()
  131. running_loss = None
  132. for batch_no in range(1, 10000):
  133. batch_imgs, labels = sample_batch(batch_size)
  134. batch_imgs = make_var(batch_imgs)
  135. labels = make_var(labels)
  136. pred = model(batch_imgs)
  137. loss = criterion(pred, labels)
  138. optimizer.zero_grad()
  139. loss.backward()
  140. optimizer.step()
  141. loss = loss.data.detach().item()
  142. running_loss = loss if running_loss is None else 0.99 * running_loss + 0.01 * loss
  143. print('batch #{}, frames={}, loss={:.5f}'.format(
  144. batch_no,
  145. batch_no * batch_size,
  146. running_loss
  147. ))
  148. if batch_no % 25 == 0:
  149. acc = eval_model(model)
  150. print('accuracy: {:.2f}%'.format(acc))