train_classifier_emb2.py 4.9 KB

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