Pytorch Flashcards
Understand Pytorch Syntax and general NN processes in Pytorch
How does one create a tensor in pytorch?
x_tensor = torch.tensor(data) # directly from data
print(x_tensor)
np_array = np.array(data)
x_tensor = torch.from_numpy(np_array) # from numpy, this time infers a dtype
print(x_tensor)
x_ones_tensor = torch.ones_like(x_tensor) # this gets the shape of the data passed, then gives ones array
print(x_ones_tensor)
x_rand_tensor = torch.rand_like(x_tensor, dtype=torch.float) # this does the same as above, but random values
print(x_rand_tensor)
How do you get the shape of a tensor? type? device?
tensor.shape
tensor.dtype
tensor.device
How do you slice a tensor?
tensor[row,column]
How do you concatenate a tensor?
t1 = torch.cat([tensor,tensor,tensor], dim=1)
How do we multiply tensors?
tensor.mul(tensor) #element-wise
tensor*tensor # element wise
tensor.matmul(tensor) # matrix mult
tensor @ tensor # matrix mult
What are significance of functions with a “_” in pytorch?
They are in place operations
What is the typical procedure for creating a neural net in pytorch
Define the Model:
Create a subclass of torch.nn.Module, defining the network’s layers in __init__ and the forward pass in forward.
Instantiate the Model:
Create an instance of your model class.
Which imports are needed in pytorch when creating a neural net?
import torch
import torch.nn as nn
import torch.nn.functional as F
how do you set your device to gpu in pytorch
device = torch.device(‘cuda:0’ if torch.cuda.is_available() else ‘cpu’)
What is the general cycle of creating and training a neural net?
- Define the NN that has some learnable parameters (weights)
- iterate over a dataset of inputs
- process the input through the network
- compute the loss (how far the output is from being correct)
- propogate gradients back into the networks parameters
- update the weights of the network, using the SGD update rule: weight=weight - learning_rate*gradient