<jupyter_start><jupyter_text>torch.nn  Layers<jupyter_code>import torch.nn as nn

# linear layer: in_feat, out_feat
linear = nn.Linear(in_features=10, out_features=10)
print(linear)

# convolution layer: in channel, out channels, kernel_size, stride
conv = nn.Conv2d(in_channels=1, out_channels=20, kernel_size=5, stride=1)
print(conv)

# RNN: num_inpnuts, num_hidden, num_layers
rnn = nn.RNN(input_size=10, hidden_size=10, num_layers=1)
print(rnn)
print(linear.weight)
print([k for k,v in conv.named_parameters()])
import torch.nn.functional as F
# Make our own model!

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 1 input channel to 20 feature maps of 5x5 kernel. Stride 1.
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=20, kernel_size=5, stride=1)

        self.conv2 = nn.Conv2d(20, 50, 5, 1)
        
        # Full connected of final 4x4 image to 500 features
        self.fc1 = nn.Linear(in_features=4*4*50, out_features=500)
        
        # 500 to 10 classes
        self.fc2 = nn.Linear(500, 10)
        
    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(-1, 4*4*50)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)
    
model = Net()<jupyter_output><empty_output><jupyter_text>formula fro computing the sizes:$$W_f =\frac{W_i - F + 2p}{S} +1$$usually, $p = 0$:$$W_f =\frac{W_i - F}{S} +1$$if $F = S$:$$W_f =\frac{W_i }{S}$$      Optimizers<jupyter_code>import torch.optim as optim

# initialize with model parameters
optimizer = optim.SGD(model.parameters(), lr=0.01)<jupyter_output><empty_output><jupyter_text>Full train and test loops<jupyter_code>import tqdm
import torch.nn.functional as F

def train(model, train_loader, optimizer, epoch):
    
    model.train()
    
    # Avg_loss
    total_loss = 0
    
    #iterate through dataset
    for data, target in tqdm.tqdm(train_loader):
        # zero grad
        optimizer.zero_grad()
        
        # forward pass
        output = model(data)
        
        # negative log-likeihood loss function
        loss = F.nll_loss(output, target)
        
        # Backward pass
        loss.backward()
        total_loss += loss.item()
        
        # update
        optimizer.step()
        
    print("Train Epoch: {}\t Loss: {:.6f}".format(epoch, total_loss / len(train_loader)))<jupyter_output><empty_output><jupyter_text>Testing loops are similar<jupyter_code>def test(model, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item() #sum up bactch loss
            
            pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()
            
    test_loss /= len(test_loader.dataset)
    
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
    test_loss, correct, len(test_loader.dataset),
    100. * correct / len(test_loader.dataset)))<jupyter_output><empty_output><jupyter_text>MNISTnow running mnist<jupyter_code>from torchvision import datasets, transforms

# see the torch Dataloader for more details
train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../data', train=True, download=True,
                  transform=transforms.Compose([
                      transforms.ToTensor(),
                      transforms.Normalize((0.1307,), (0.3081,))
                  ])),
    batch_size=32, shuffle=True)

test_loader = torch.utils.data.DataLoader(    
    datasets.MNIST('../data', train=False,
                   transform=transforms.Compose([
                       transforms.ToTensor(),
                       transforms.Normalize((0.1307,), (0.3081,))
                   ])),
    batch_size=32, shuffle=True)

for epoch in range(1, 10 + 1):
    train(model, train_loader, optimizer, epoch)
    test(model, test_loader)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12931650392950703, 'fraction_numerical': 0.028816384853536558, 'mean_word_length': 2.7102473498233217, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '546581', 'license': 'MIT', 'n_tokens_mistral': 1521, 'n_tokens_neox': 1438, 'n_words': 306, 'path': 'notebooks/pytorch_tutorial.ipynb', 'repo_name': 'akin-aroge/mitx6.86_projects', 'size': '4199'}