def transform_screen_data(self, screen): # Convert to float, rescale, convert to tensor screen = np.ascontigousarray(screen, dtype=np.float32) / 255 screen = torch.from_numpy(screen) # Use torchvision package to compose image transforms resize = T.compose([T.ToPILImage(), T.Resize((40, 90)), T.Totensor()]) return resize(screen).unsqueeze(0).to( self.device) # add a batch dimension
convh = conv2d_out(conv2d_out(conv2d_out(h))) linear_input_size = convw * convh * 32 self.head = nn.Linear(linear_input_size, outputs) def forward(self, x): x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) # Input Extraction # Applying transforms to the image resize = T.compose( [T.ToPILImage(), T.Resize(40, interpolation=Image.CUBIC), T.ToTensor()]) def get_cart_location(screen_width): world_width = env.x_threshold * 2 scale = screen_width / world_width return int(env.state[0] * scale + screen_width / 2.0) # MIDDLE OF CART def get_screen(): # Returned screen requested by gym is 400x600x3, but is sometimes larger # such as 800x1200x3. Transpose it into torch order (CHW). screen = env.render(mode='rgb_array').transpose((2, 0, 1)) # Cart is in the lower half, so strip off the top and bottom of the screen _, screen_height, screen_width = screen.shape
import torch import torchvision import torchvision.transforms as T #------------------------------------------------------------------------------------------------------------------------------------------ #STEP1: Loading dataset with suitable transforms #general transformation to be applied to all images transform=T.compose([T.toTensor(),T.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))]) #Get the training dataset apply the transforms and apply load it in a variable with appt. batch size shuffling etc. trainset=torchvision.datasets.CIFAR10(root='./data',train=True,download=True,transform=transform) trainloader=torch.utils.data.DataLoader(trainset,batch_size = 4,shuffle=True, num_workers=2) #Get the training dataset apply the transforms and apply load it in a variable with appt. batch size shuffling etc. testset=torchvision.datasets.CIFAR10(root='./data',train=False,download=True,transofrm=transform) testloader=torch.utils.data.Dataloader(testset,shuffle=True,batch_size=4,num_workers=2) classes=('plane' , 'car', 'bird' , 'cat', 'deer','dog', 'frog', 'horse', 'ship' , 'truck') #------------------------------------------------------------------------------------------------------------------------------------------ #STEP2:Displaying Training Images