<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hassan Askary on Medium]]></title>
        <description><![CDATA[Stories by Hassan Askary on Medium]]></description>
        <link>https://medium.com/@hassanaskary?source=rss-34c81a0bb176------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QPnfdK7hOBa3q88V13kLGg.jpeg</url>
            <title>Stories by Hassan Askary on Medium</title>
            <link>https://medium.com/@hassanaskary?source=rss-34c81a0bb176------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:29:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hassanaskary/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Intuitive Explanation of Straight-Through Estimators with PyTorch Implementation]]></title>
            <link>https://hassanaskary.medium.com/intuitive-explanation-of-straight-through-estimators-with-pytorch-implementation-71d99d25d9d0?source=rss-34c81a0bb176------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d99d25d9d0</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[straigh-through-estimator]]></category>
            <category><![CDATA[autoencoder]]></category>
            <dc:creator><![CDATA[Hassan Askary]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 01:53:35 GMT</pubDate>
            <atom:updated>2023-02-19T01:53:35.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes we want to put a threshold function at the output of a layer. This can be for a variety of reasons. One of them is that we want to summarize the activations into binary values. This binarization of activations can be useful in autoencoders.</p><p>However, thresholding poses a problem during backpropagation. The derivative of threshold functions is zero. This lack of gradient results in our network not learning anything. To solve this problem we use straight-through estimators (STE).</p><h3>What is a Straight-Through Estimator?</h3><p>Lets suppose we want to binarize the activations of a layer using the following function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*WcpKCr5utBQor1PCjTxDCA.png" /></figure><p>This function will return 1 for every value that is greater than 0 otherwise it will return 0.</p><p>As mentioned earlier, the problem with this function is that its gradient is zero. To overcome this issue we will use a straight-through estimator in the backward pass.</p><p>A straight-through estimator is exactly what it sounds like. It estimates the gradients of a function. Specifically it ignores the derivative of the threshold function and passes on the incoming gradient as if the function was an identity function. The following diagram will help explain it better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsWTvp-qqnDfFSYXcBv0tA.png" /><figcaption>Visualization of how straight-through estimators work.</figcaption></figure><p>You can see how the threshold function is bypassed in the backward pass. That’s it, this is what a straight-through estimator does. It makes the gradient of the threshold function look like the gradient of the identity function.</p><h3>Implementation in PyTorch</h3><p>As of right now, PyTorch doesn’t include an implementation of an STE in its APIs. So, we will have to implement it ourselves. To do this we will need to create a Function class and a Module class. The Function class will contain the forward and backward functionality of the STE. The Module class is where the STE Function object will be created and used. We will use the STE Module in our neural networks.</p><p>Below is the implementation of the STE Function class:</p><pre>class STEFunction(torch.autograd.Function):<br>    @staticmethod<br>    def forward(ctx, input):<br>        return (input &gt; 0).float()<br><br>    @staticmethod<br>    def backward(ctx, grad_output):<br>        return F.hardtanh(grad_output)</pre><p>PyTorch lets us define custom autograd functions with forward and backward functionality. Here we have defined an autograd function for a straight-through estimator. In the forward pass we want to convert all the values in the input tensor from floating point to binary. In the backward pass we want to pass the incoming gradients without modifying them. This is to mimic the identity function. Although, here we are performing the F.hardtanh operation on the incoming gradients. This operation will clamp the gradient between -1 and 1. We are doing this so that the gradients do not get too big.</p><p>Now, lets implement the STE Module class:</p><pre>class StraightThroughEstimator(nn.Module):<br>    def __init__(self):<br>        super(StraightThroughEstimator, self).__init__()<br><br>    def forward(self, x):<br>            x = STEFunction.apply(x)<br>            return x</pre><p>You can see that we have used the STE Function class we defined in the forward function. To use autograd functions we have to pass the input to the apply method. Now, we can use this module in our neural networks.</p><p>A common way to use STE is inside the bottleneck layer of autoencoders. Here is an implementation of such an autoencoder:</p><pre>class Autoencoder(nn.Module):<br>    def __init__(self):<br>        super(Autoencoder, self).__init__()<br>        <br>        self.encoder = nn.Sequential(<br>            nn.Conv2d(1, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.ReLU(),<br>            <br>            nn.Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(128),<br>            nn.ReLU(),<br>            <br>            nn.Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(256),<br>            nn.ReLU(),<br>            <br>            nn.Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(512),<br>            nn.ReLU(),<br>            <br>            StraightThroughEstimator(),<br>        )<br>        self.decoder = nn.Sequential(<br>            nn.ConvTranspose2d(512, 256, kernel_size=(5, 5), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(256),<br>            nn.ReLU(),<br>            <br>            nn.ConvTranspose2d(256, 128, kernel_size=(5, 5), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(128),<br>            nn.ReLU(),<br>            <br>            nn.ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(64),<br>            nn.ReLU(),<br>            <br>            nn.ConvTranspose2d(64, 1, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.Tanh(),<br>        )<br>        <br>    def forward(self, x, encode=False, decode=False):<br>        if encode:<br>            x = self.encoder(x)<br>        elif decode:<br>            x = self.decoder(x)<br>        else:<br>            encoding = self.encoder(x)<br>            x = self.decoder(encoding)<br>        return x</pre><p>This autoencoder is made for the MNIST dataset. It will compress the 28x28 image into a 1x1 image with 512 channels. Then decode it back to 28x28 image.</p><p>I’ve placed the STE at the end of the encoder. It will convert all of the values of the tensor it receives to binary. You might have noticed I’ve used an unconventional forward function. I’ve added two new arguments encode and decode which are either True or False. If encode is set to True, the network will return the output of the encoder. Similarly if decode is set to True, the network expects a valid encoding and it will decode it back to an image.</p><p>I trained the autoencoder for 5 epochs on the MNIST dataset with MSE loss. Here are the reconstructions on the test set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*kxnRtG-p7BB7qbIuuJTuAA.png" /><figcaption>Reconstructions compared with their originals.</figcaption></figure><p>As you can see, the reconstructions are pretty good. STEs can be used in neural networks without much loss in performance.</p><h3>Full Code</h3><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>import torch.optim as optim<br>import torch.autograd as autograd<br>from torchvision import datasets, transforms<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from tqdm import tqdm<br><br>device = &#39;cuda:0&#39; if torch.cuda.is_available() else &#39;cpu&#39;<br># dataset preparation<br>transform = transforms.Compose([<br>    transforms.ToTensor(),<br>    transforms.Normalize((0.5, ), (0.5, ))<br>])<br>trainset = datasets.MNIST(&#39;dataset/&#39;, train=True, download=True, transform=transform)<br>testset = datasets.MNIST(&#39;dataset/&#39;, train=False, download=True, transform=transform)<br>trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)<br>testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)<br># defining networks<br>class STEFunction(autograd.Function):<br>    @staticmethod<br>    def forward(ctx, input):<br>        return (input &gt; 0).float()<br>    @staticmethod<br>    def backward(ctx, grad_output):<br>        return F.hardtanh(grad_output)<br>class StraightThroughEstimator(nn.Module):<br>    def __init__(self):<br>        super(StraightThroughEstimator, self).__init__()<br>    def forward(self, x):<br>        x = STEFunction.apply(x)<br>        return x<br>class Autoencoder(nn.Module):<br>    def __init__(self):<br>        super(Autoencoder, self).__init__()<br>        <br>        self.encoder = nn.Sequential(<br>            nn.Conv2d(1, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.ReLU(),<br>            <br>            nn.Conv2d(64, 128, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(128),<br>            nn.ReLU(),<br>            <br>            nn.Conv2d(128, 256, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(256),<br>            nn.ReLU(),<br>            <br>            nn.Conv2d(256, 512, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(512),<br>            nn.ReLU(),<br>            <br>            StraightThroughEstimator(),<br>        )<br>        self.decoder = nn.Sequential(<br>            nn.ConvTranspose2d(512, 256, kernel_size=(5, 5), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(256),<br>            nn.ReLU(),<br>            <br>            nn.ConvTranspose2d(256, 128, kernel_size=(5, 5), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(128),<br>            nn.ReLU(),<br>            <br>            nn.ConvTranspose2d(128, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.BatchNorm2d(64),<br>            nn.ReLU(),<br>            <br>            nn.ConvTranspose2d(64, 1, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)),<br>            nn.Tanh(),<br>        )<br>        <br>    def forward(self, x, encode=False, decode=False):<br>        if encode:<br>            x = self.encoder(x)<br>        elif decode:<br>            x = self.decoder(x)<br>        else:<br>            encoding = self.encoder(x)<br>            x = self.decoder(encoding)<br>        return x<br>net = Autoencoder().to(device)<br>optimizer = optim.Adam(net.parameters(), lr=0.001, betas=(0.5, 0.999))<br>criterion_MSE = nn.MSELoss().to(device)<br># train loop<br>epoch = 5<br>for e in range(epoch):<br>    print(f&#39;Starting epoch {e} of {epoch}&#39;)<br>    for X, y in tqdm(trainloader):<br>        optimizer.zero_grad()<br>        X = X.to(device)<br>        reconstruction = net(X)<br>        loss = criterion_MSE(reconstruction, X)<br>        loss.backward()<br>        optimizer.step()<br>    print(f&#39;Loss: {loss.item()}&#39;)<br># test loop<br>i = 1<br>fig = plt.figure(figsize=(10, 10))<br>for X, y in testloader:<br>    X_in = X.to(device)<br>    recon = net(X_in).detach().cpu().numpy()<br>    if i &gt;= 10:<br>      break<br>    fig.add_subplot(5, 2, i).set_title(&#39;Original&#39;)<br>    plt.imshow(X[0].reshape((28, 28)), cmap=&quot;gray&quot;)<br>    fig.add_subplot(5, 2, i+1).set_title(&#39;Reconstruction&#39;)<br>    plt.imshow(recon[0].reshape((28, 28)), cmap=&quot;gray&quot;)<br>    i += 2<br>fig.tight_layout()<br>plt.show()</pre><p>I hope you found this post helpful. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d99d25d9d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with PyTorch]]></title>
            <link>https://hassanaskary.medium.com/getting-started-with-pytorch-ad50588a1270?source=rss-34c81a0bb176------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad50588a1270</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mnist]]></category>
            <dc:creator><![CDATA[Hassan Askary]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 01:40:52 GMT</pubDate>
            <atom:updated>2023-02-19T01:40:52.843Z</atom:updated>
            <content:encoded><![CDATA[<p>PyTorch is a machine learning framework by Meta. It allows you to do tensor computation on the GPU, and design, train, and deploy deep learning models.</p><p>In this post we’ll cover the following topics:</p><ol><li>Installing PyTorch</li><li>Getting familiar with commonly used APIs</li><li>Building a classifier for MNIST</li></ol><p>I will assume familiarity with machine learning and deep learning.</p><h3>Installing PyTorch</h3><p>Go to the official <a href="https://pytorch.org/get-started/locally/">website</a> to download and install PyTorch. Scroll down a bit and you’ll see the “Start Locally” section. Select the option according to your OS, CUDA version, and preference of Pip or Conda.</p><p>I’m using Pop OS 20.04 right now without GPU. So I’ll select the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*ELt_WVYnhQGoGBanBbUA7A.png" /><figcaption>PyTorch get started locally page.</figcaption></figure><p>Copy and paste the command indicated by “Run this Command” into your terminal and execute. This should install PyTorch on your system.</p><h3>Getting Familiar with Commonly Used APIs</h3><p>PyTorch consists of many APIs. I won’t cover individual syntax and commands but give you an overview of what each API does. This way you will have a birds eye view of PyTorch and when you get stuck you will know where to look.</p><p>The commonly used APIs/libraries are:</p><ol><li>torch<br>– torch.nn<br>– torch.nn.functional<br>– torch.optim<br>– torch.utils.data</li><li>torchvision</li></ol><h3>torch</h3><p>The torch API provides the tensor data structure and its associated methods and mathematical operations. A tensor is similar to a numpy array. Difference between a numpy array and a torch tensor is that the latter can utilize a GPU to do computations.</p><h4>torch.nn</h4><p>The torch.nn API contains the building blocks to design and build a neural network. These building blocks are called modules and they are subclasses that inherit from torch.nn.Module base class. They are stateful meaning they automatically store their weights, gradients and other attributes. They also need to be initialized before usage.</p><p>The API contains fully-connected linear layers, convolution layers, activation functions, loss functions, normalization layers, dropout etc.</p><h4>torch.nn.functional</h4><p>The torch.nn.functional API contains useful functions like activations and loss functions etc. However, they are not stateful meaning they won’t store their attributes automatically. Instead we will have to store them manually.</p><p>These functions can be used for applying layers that don’t need to be learned like activations or pooling etc.</p><p>This API provides additional flexibility in designing your models.</p><h4>torch.optim</h4><p>The torch.optim API contains optimizers like Adam, SGD, and RMSprop etc. and methods for calculating gradients and applying them.</p><h4>torch.utils.data</h4><p>This is a utility that provides the DataLoader class which is used to load data from a folder or from a built-in dataset.</p><h3>torchvision</h3><p>The torchvision library contains datasets, models, and utilities related to computer vision. The torchvision.datasets package contains popular datasets like MNIST, ImageNet, and COCO etc. The torchvision.models package contains famous pre-trained or untrained vision models like ResNet, Inception, and Mask R-CNN etc. The torchvision.transforms package contains image transformations used to preprocess datasets like converting images to torch tensor, cropping, or resizing etc.</p><h3>Building a Classifier for MNIST</h3><p>There are many ways to build a neural network in PyTorch. In this post I’ll demonstrate building a convolutional neural network. It will have three convolution layers followed by three linear layers with Relu activations and finally a cross entropy loss.</p><p>We will be doing things in the following order:</p><ol><li>Import packages</li><li>Load and preprocess data</li><li>Build the network</li><li>Write the training loop</li><li>Write the testing loop</li></ol><h3>Import Packages</h3><p>First we will import the required packages.</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torchvision<br>import torchvision.datasets as datasets<br>import torchvision.transforms as transforms</pre><h3>Load and Preprocess Data</h3><p>We will use the built-in MNIST digits dataset. But first we have to specify how we will preprocess the images.</p><pre>preprocess = transforms.Compose([<br>    transforms.ToTensor(),<br>    transforms.Normalize((0.5, ), (0.5, ))<br>])</pre><p>Here, transforms.Compose() is a list of the transformations we want to apply to the images in order. First, we will convert the images to torch tensors then we will normalize them.</p><p>The syntax of transforms.Normalize() is as follows:</p><pre>transforms.Normalize(mean, standard deviation)</pre><p>Each index in those two tuples correspond to a channel in the image. Since MNIST images are grayscale they have only one channel. So we are setting the mean and standard deviation of that one channel to 0.5 yielding a mean of 0 and standard deviation of 1.</p><p>Lets download the dataset.</p><pre>trainset = datasets.MNIST(&#39;dataset/&#39;, train=True, download=True, transform=preprocess)<br>testset = datasets.MNIST(&#39;dataset/&#39;, train=False, download=True, transform=preprocess)</pre><p>Here, we are creating the train and test sets. They will be downloaded in “dataset/” folder. The train argument specifies whether to download train or test set. The transform argument takes in the transforms.Compose() object and preprocesses the images according to it.</p><p>Now we will create data loaders that will return a batch of data on each iteration.</p><pre>trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)<br>testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)</pre><h3>Build the Network</h3><p>Finally the fun part. First we will define some constants.</p><pre>nf = 32<br>lr = 0.0001<br>beta1 = 0.5<br>beta2 = 0.999<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;</pre><p>Here, nf is the number of kernels/filters/neurons (from now on I will call them filters). For device we are checking whether a CUDA enabled GPU exists. If it does not exist then we will use the CPU.</p><p>Now lets define the network. In PyTorch by convention we define models as a subclass of torch.nn.Module. We initialize layers in __init__() and connect them in forward() function.</p><pre>class Net(nn.Module):<br>    def __init__(self):<br>        super(Net, self).__init__()<br><br>        self.convs = nn.Sequential(<br>            nn.Conv2d(1, nf, kernel_size=3, stride=1, padding=1),<br>            nn.ReLU(),<br><br>            nn.Conv2d(nf, nf, kernel_size=3, stride=1, padding=1),<br>            nn.ReLU(),<br>            nn.MaxPool2d(kernel_size=2, stride=2), # resultant size will be 32x14x14<br><br>            nn.Conv2d(nf, nf, kernel_size=3, stride=1, padding=1),<br>            nn.ReLU(),<br>            nn.MaxPool2d(kernel_size=2, stride=2), # resultant size will be 32x7x7<br>        )<br><br>        self.linears = nn.Sequential(<br>            nn.Linear(1568, 100), # width=7, height=7, filters=32; linear layer input = 7*7*32 = 1568<br>            nn.ReLU(),<br><br>            nn.Linear(100, 50),<br>            nn.ReLU(),<br><br>            nn.Linear(50, 10),<br>        )<br><br>    def forward(self, x):<br>        x = self.convs(x)<br>        x = x.view(x.size(0), -1) # flattening, result will be (64, 1568)<br>        x = self.linears(x)<br>        return x</pre><p>Ok, a lot to unpack here. In the __init__() you can see self.convs and self.linears being defined. The nn.Sequential is like a list. It contains modules and executes them in order sequentially.</p><p>We are defining the convolution part and the fully-connected or linear part separately. All layers will be initialized randomly.</p><p>Now, lets look at the individual layers. In self.convs we first see nn.Conv2d() this is a convolution layer. The arguments correspond to:</p><pre>nn.Conv2d(number of input channels, number of filters, filter size, stride, padding)</pre><p>This convolution layer is connected to a relu layer. This continues until we reach a max pool layer. Its arguments correspond to:</p><pre>nn.MaxPool2d(filter size, stride)</pre><p>Moving on in self.linears we have the fully connected layers. Its arguments correspond to:</p><pre>nn.Linear(input feature/vector size, number of neurons in layer)</pre><p>In the first linear layer we see that the input is 1568 and the output or number of neurons is 100. In PyTorch we have to define and initialize our layers before using them. This means we have to specify there input and output sizes.</p><p>I have calculated the output size of self.convs. We can calculate the output size of convolution using the following formulas:</p><pre>outputWidth = (inputWidth - filterSize + (2 * padding)) / stride + 1<br><br>outputHeight = (inputHeight - filterSize + (2 * padding)) / stride + 1</pre><p>There are also max pool layers which change the size of our features. We can calculate the output size of max pool using:</p><pre>outputWidth = (inputWidth - filterSize) / stride + 1<br><br>outputHeight = (inputHeight - filterSize) / stride + 1</pre><p>This calculation can be automated by writing a custom module. But that is out of the scope of this guide.</p><p>Moving on to the forward() function. This is where we bring together the self.convs and self.linears and connect them. Here x is the input features/tensors.</p><p>After getting output from self.convs we flatten it by using the view() function. The view() function is similar to reshape() in numpy. Here the first argument is set to x.size(0) which is the batch size. The second argument is &quot;-1&quot; which tells PyTorch to infer the remaining size which in this case will be equal to 1568. After this the tensor will be flattened and ready to be passed to self.linears. Finally, we will return the result.</p><h3>Write the Training Loop</h3><p>Lets initialize the model. Define the loss function and optimizer.</p><pre>model = Net().to(device)<br>optimizer = optim.Adam(model.parameters(), lr=lr, betas=(beta1, beta2))<br>criterion_CE = nn.CrossEntropyLoss().to(device)</pre><p>Here the .to(device) means to transfer the model and loss function to the specified device. If a CUDA enabled GPU was found on the system then the model and loss will utilize it.</p><p>Now lets write the training loop.</p><pre>epoch = 10<br>model.train()<br>for e in range(epoch):<br>    print(f&#39;Starting epoch {e} of {epoch}&#39;)<br>    for X, y in trainloader:<br>        X = X.to(device)<br>        predictions = model(X)<br>        optimizer.zero_grad()<br>        loss = criterion_CE(predictions, y)<br>        loss.backward()<br>        optimizer.step()<br>    print(f&#39;Loss: {loss.item()}&#39;)<br><br>torch.save(model.state_dict(), &quot;model.pt&quot;)</pre><p>We will train for 10 epochs. Before training we set the model to training mode since behaviour of some layers like Batchnorm and Dropout is different in eval mode and train mode. In this case we are not using these kind of layers but it’s best practice to set the mode.</p><p>We iterate over the trainloader which return a batch of images and labels for each iteration. First we transfer the images to specified device then we pass the images to our model and get predictions. Then we zero out our gradients and calculate the loss. After this we calculate our gradient with loss.backward() and finally apply those gradients with optimizer.step(). That&#39;s it we loop over these steps for the whole dataset.</p><p>At the end we save the weights of the trained model. The training should take at most 30 minutes without GPU.</p><h3>Write the Testing Loop</h3><p>Lets test our model.</p><pre>model.eval()<br>correct = 0<br>for X, y in testloader:<br>    with torch.no_grad():<br>        X = X.to(device)<br>        output = model(X)<br>        predictions = output.max(1)[1]<br>        correct += torch.eq(predictions, y).sum()<br><br>print(f&#39;accuracy: {int(correct)}/{len(testloader.dataset)} ({int(correct)/len(testloader.dataset)} or {int(correct)/len(testloader.dataset) * 100}%)&#39;)</pre><p>The with torch.no_grad(): context tells PyTorch not to calculate gradient of tensor operations within it. Since we don&#39;t need to calculate gradient during testing this increases performance and decreases memory usage.</p><p>After getting the predictions from the model we get index of the highest score. The index indicates the digit. We compare the indexes with the ground truth with torch.eq() which returns True for a match and False otherwise. Finally we sum over the resulting tensor. All True&#39;s count as one and False&#39;s as zero. So the sum will be the number of correct predictions.</p><p>If you trained for 10 epochs then your accuracy should be about 98%. Which is pretty good.</p><h3>Full Code</h3><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import torchvision<br>import torchvision.datasets as datasets<br>import torchvision.transforms as transforms<br><br>preprocess = transforms.Compose([<br>    transforms.ToTensor(),<br>    transforms.Normalize((0.5, ), (0.5, ))<br>])<br>trainset = datasets.MNIST(&#39;dataset/&#39;, train=True, download=True, transform=preprocess)<br>testset = datasets.MNIST(&#39;dataset/&#39;, train=False, download=True, transform=preprocess)<br>trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)<br>testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)<br>nf = 32 # conv layer sizes or number of filters/kernels<br>lr = 0.0001<br>beta1 = 0.5<br>beta2 = 0.999<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>class Net(nn.Module):<br>    def __init__(self):<br>        super(Net, self).__init__()<br>        self.convs = nn.Sequential(<br>            nn.Conv2d(1, nf, kernel_size=3, stride=1, padding=1),<br>            nn.ReLU(),<br>            nn.Conv2d(nf, nf, kernel_size=3, stride=1, padding=1),<br>            nn.ReLU(),<br>            nn.MaxPool2d(kernel_size=2, stride=2), # result will be 14x14<br>            nn.Conv2d(nf, nf, kernel_size=3, stride=1, padding=1),<br>            nn.ReLU(),<br>            nn.MaxPool2d(kernel_size=2, stride=2), # result will be 7x7<br>        )<br>        self.linears = nn.Sequential(<br>            nn.Linear(1568, 100), # width=7, height=7, depth/filters/kernels=32 ; linear_input=7*7*32=1568<br>            nn.ReLU(),<br>            nn.Linear(100, 50),<br>            nn.ReLU(),<br>            nn.Linear(50, 10),<br>        )<br>    def forward(self, x):<br>        x = self.convs(x)<br>        x = x.view(x.size(0), -1) # flattening, result will be (64, 1568)<br>        x = self.linears(x)<br>        return x<br>model = Net().to(device)<br>optimizer = optim.Adam(model.parameters(), lr=lr, betas=(beta1, beta2))<br>criterion_CE = nn.CrossEntropyLoss().to(device)<br>model.train()<br>epoch = 10<br>for e in range(epoch):<br>    print(f&#39;Starting epoch {e} of {epoch}&#39;)<br>    for X, y in trainloader:<br>        X = X.to(device)<br>        predictions = model(X)<br>        optimizer.zero_grad()<br>        loss = criterion_CE(predictions, y)<br>        loss.backward()<br>        optimizer.step()<br>    print(f&#39;Loss: {loss.item()}&#39;)<br>torch.save(model.state_dict(), &quot;model.pt&quot;)<br>model.eval()<br>correct = 0<br>for X, y in testloader:<br>    with torch.no_grad():<br>        X = X.to(device)<br>        output = model(X)<br>        predictions = output.max(1)[1]<br>        correct += torch.eq(predictions, y).sum()<br><br>print(f&#39;accuracy: {int(correct)}/{len(testloader.dataset)} ({int(correct)/len(testloader.dataset)} or {int(correct)/len(testloader.dataset) * 100}%)&#39;)</pre><p>I hope you found this helpful. To learn more about PyTorch I highly recommend the official <a href="https://pytorch.org/docs/stable/index.html">documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad50588a1270" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Setup Neovim with Python Provider using Conda]]></title>
            <link>https://hassanaskary.medium.com/how-to-setup-neovim-with-python-provider-using-conda-cbb0172f162?source=rss-34c81a0bb176------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbb0172f162</guid>
            <category><![CDATA[neovim]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[conda]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[python-environment]]></category>
            <dc:creator><![CDATA[Hassan Askary]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 01:28:16 GMT</pubDate>
            <atom:updated>2023-02-19T01:28:16.701Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I will go over the steps to setup Neovim with Python provider which is the Python language tool for Neovim. It is required by many Python specific plugins. I’ll be using Conda environments to do this.</p><p>Firstly, if you don’t have Neovim installed then install it. On Ubuntu type:</p><pre>sudo apt install neovim</pre><p>Neovim requires the pynvim Python package to enable Python support. It can be downloaded from PyPI using pip. If you use Python environments you will have to install pynvim for every environment in which you want to use Neovim. Fortunately, there is a work around, we can create a Python environment and install pynvim in it. Then in our init.vim we will tell Neovim to look for the Python provider in that environment.</p><p>I’ll use Conda to create the environments. Of course, you’ll need Conda to be installed on your system. To create a Conda environment type:</p><pre>conda create -n pynvim python=3.7</pre><p>I named the environment pynvim and installed Python 3.7 in it. Now activate the environment by typing:</p><pre>conda activate pynvim</pre><p>Let&#39;s install pynvim. Type:</p><pre>pip install pynvim</pre><p>pynvim is installed in pynvim conda environment. We need to know the location of the environment. To do that type:</p><pre>which python</pre><p>Note the returned path we will need it. Now open your init.vim and add this line in it:</p><pre>let g:python3_host_prog=&#39;/path/to/conda/environment&#39;</pre><p>Put the result of which python inside the single quotes &#39;&#39;.</p><p>This is it. You’ve now configured Neovim for Python. You can now go ahead and install plugins. One cool plugin is <a href="https://github.com/numirias/semshi">Semshi</a> it does semantic syntax highlighting for Python.</p><p>I hope this was helpful for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbb0172f162" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>