Last active
March 29, 2022 06:16
-
-
Save rish-16/30a339d1c5a43078056d98d2c632ff15 to your computer and use it in GitHub Desktop.
CS4243 PyTorch Snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
import torch.nn as nn | |
import torch.nn.functional as F | |
""" | |
Creating tensors | |
""" | |
a = torch.rand(...) # returns a torch.Tensor | |
b = torch.LongTensor(10).random_(0, 2) # 10-dim vector from [0, 1] | |
""" | |
Network template | |
""" | |
class Network(nn.Module): | |
def __init__(self): | |
super().__init__() | |
pass | |
def forward(self, x): | |
pass | |
""" | |
batch training loop | |
""" | |
for epoch in in range(EPOCHS): | |
num_batches = 0 | |
shuffled_indices=torch.randperm(60000) | |
running_loss = 0 | |
for i in range(0, DATASETSIZE, BATCHSIZE): | |
idx = shuffled_indices[count:count+bs] | |
idx = torch.LongTensor(DATASETSIZE).random_(BATCHSIZE) | |
minibatch_data = train_data[idx] | |
minibatch_labels = trian_labels[idx] | |
inputs = minibatch_data.view(bs, INPUTSIZE) | |
inputs.requires_grad_() | |
pred = model(inputs) | |
loss = criteron(pred, minibatch_labels) | |
running_loss = loss.detach().item() | |
num_batches += 1 | |
epoch_loss = running_loss / num_batches | |
""" | |
Testing model | |
""" | |
def eval_on_test_set(model, test_data, test_label): | |
running_error=0 | |
num_batches=0 | |
for i in range(0,DATASETSIZE, BATCHSIZE): | |
inputs = test_data[i:i+BATCHSIZE].unsqueeze(dim=1) | |
minibatch_label = test_label[i:i+BATCHSIZE] | |
scores = model(inputs) | |
error = utils.get_error( scores , minibatch_label) | |
running_error += error.item() | |
num_batches+=1 | |
total_error = running_error/num_batches | |
print( 'error rate on test set =', total_error*100 ,'percent') | |
def get_accuracy(scores, labels): | |
# use within the batched training loop to get the batch accuracy | |
num_data = scores.size(0) | |
predicted_labels = scores.argmax(dim=1) | |
indicator = (predicted_labels == labels) | |
num_correct = indicator.sum() | |
accuracy = 100*num_correct.float()/num_data | |
return accuracy | |
""" | |
One-hot encoding | |
""" | |
def index_to_onehot(labels, num_classes=10): | |
""" | |
convert index label to one hot labels | |
Inputs: | |
labels: Integer Tensor of length N, e.g., [0, 1, 2, 4, 3] | |
num_classes: the number of classes, e.g., 5 | |
Output: | |
Tensor: onehot_labels of size [N, num_classes] | |
a matrix that contains one-hot label for each sample: | |
e.g., [ | |
[1, 0, 0, 0, 0], | |
[0, 1, 0, 0, 0], | |
[0, 0, 1, 0, 0], | |
[0, 0, 0, 0, 1], | |
[0, 0, 0, 1, 0] | |
] | |
""" | |
num_samples = len(labels) | |
onehot = torch.zeros(num_samples, num_classes) | |
onehot[torch.arange(num_samples), labels] = 1 | |
return onehot | |
""" | |
Soft-label CrossEntropy | |
Only when final layer does not contain Softmax | |
""" | |
score = net(x) | |
prob = torch.softmax(score, dim=-1) | |
loss = -(prob.log() * y).sum(dim=-1).mean() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mask R-CNN architecture