train_classifier_int.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 Flatten(nn.Module):
  39. """
  40. Flatten layer, to flatten convolutional layer output
  41. """
  42. def forward(self, input):
  43. return input.view(input.size(0), -1)
  44. class Model(nn.Module):
  45. def __init__(self):
  46. super().__init__()
  47. self.layers = nn.Sequential(
  48. nn.Conv2d(in_channels=3, out_channels=64, kernel_size=1),
  49. nn.LeakyReLU(),
  50. nn.Conv2d(in_channels=64, out_channels=64, kernel_size=1),
  51. nn.LeakyReLU(),
  52. nn.Conv2d(in_channels=64, out_channels=2, kernel_size=1),
  53. nn.LeakyReLU(),
  54. nn.Conv2d(in_channels=2, out_channels=2, kernel_size=7),
  55. nn.LeakyReLU(),
  56. Flatten(),
  57. # Two output heads, one for each class
  58. nn.Linear(2, 2)
  59. )
  60. self.apply(init_weights)
  61. def forward(self, obs):
  62. obs = obs / 16
  63. out = self.layers(obs)
  64. return out
  65. def present_prob(self, obs):
  66. obs = make_var(obs).unsqueeze(0)
  67. logits = self(obs)
  68. probs = F.softmax(logits, dim=-1)
  69. probs = probs.detach().cpu().squeeze().numpy()
  70. return probs[1]
  71. env = gym.make('BabyAI-GoToRedBall-v0')
  72. def sample_batch(batch_size=128):
  73. imgs = []
  74. labels = []
  75. for i in range(batch_size):
  76. obs = env.reset()['image']
  77. ball_visible = ('red', 'ball') in Grid.decode(obs)
  78. obs = obs.transpose([2, 0, 1])
  79. imgs.append(np.copy(obs))
  80. labels.append(ball_visible)
  81. imgs = np.stack(imgs).astype(np.float32)
  82. labels = np.array(labels, dtype=np.long)
  83. return imgs, labels
  84. print('Generating test set')
  85. test_imgs, test_labels = sample_batch(256)
  86. def eval_model(model):
  87. num_true = 0
  88. for idx in range(test_imgs.shape[0]):
  89. img = test_imgs[idx]
  90. label = test_labels[idx]
  91. p = model.present_prob(img)
  92. out_label = p > 0.5
  93. #print(out_label)
  94. if np.equal(out_label, label):
  95. num_true += 1
  96. #else:
  97. # if label:
  98. # print("incorrectly predicted as absent")
  99. # else:
  100. # print("incorrectly predicted as present")
  101. acc = 100 * (num_true / test_imgs.shape[0])
  102. return acc
  103. ##############################################################################
  104. batch_size = 128
  105. model = Model()
  106. model.cuda()
  107. optimizer = optim.Adam(
  108. model.parameters(),
  109. lr=5e-4
  110. )
  111. criterion = nn.CrossEntropyLoss()
  112. running_loss = None
  113. for batch_no in range(1, 10000):
  114. batch_imgs, labels = sample_batch(batch_size)
  115. batch_imgs = make_var(batch_imgs)
  116. labels = make_var(labels)
  117. pred = model(batch_imgs)
  118. loss = criterion(pred, labels)
  119. optimizer.zero_grad()
  120. loss.backward()
  121. optimizer.step()
  122. loss = loss.data.detach().item()
  123. running_loss = loss if running_loss is None else 0.99 * running_loss + 0.01 * loss
  124. print('batch #{}, frames={}, loss={:.5f}'.format(
  125. batch_no,
  126. batch_no * batch_size,
  127. running_loss
  128. ))
  129. if batch_no % 25 == 0:
  130. acc = eval_model(model)
  131. print('accuracy: {:.2f}%'.format(acc))