<?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 Satyam Kumar Singh on Medium]]></title>
        <description><![CDATA[Stories by Satyam Kumar Singh on Medium]]></description>
        <link>https://medium.com/@satyamkumarsingh_74579?source=rss-73928a3df74f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tt3mlJQWk9IeYMQIzJG3MA.jpeg</url>
            <title>Stories by Satyam Kumar Singh on Medium</title>
            <link>https://medium.com/@satyamkumarsingh_74579?source=rss-73928a3df74f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:55:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satyamkumarsingh_74579/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[ResNet Architecture: Deep Learning with PyTorch]]></title>
            <link>https://pub.towardsai.net/resnet-architecture-deep-learning-with-pytorch-19ecb7ca359e?source=rss-73928a3df74f------2</link>
            <guid isPermaLink="false">https://medium.com/p/19ecb7ca359e</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Satyam Kumar Singh]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 20:34:05 GMT</pubDate>
            <atom:updated>2020-07-20T14:48:59.687Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/machine-learning/deep-learning">Deep Learning</a></h4><p>From winning ImageNet Large Scale Visual Recognition Challenge (ILSVRC) in 2015 till now ResNet Architecture has been remarkable in the field of Data Science. Apart from ILSVRC, ResNet also won Detection and localization challenge and MSCOCO detection and segmentation challenge. Quite a feat!</p><p>So, What’s so unique about ResNet compared to the previous convolutional network?</p><h3>ResNet: the working behind it</h3><p>As input=output, So effectively the more the layers the better the network. Well, not actually. But in the real world, because of the vanishing gradient and curse of dimensionality problems, it isn’t possible. In fact, the training error increases after certain epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKG18fNQxcov2QeaAzkClA.jpeg" /></figure><p>The working is ResNet is pretty simple, it adds the original input back to the output feature map obtained by passing the input through one or more convolutional layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*5UAu2uxrMIi4EAaII6IY8g.png" /></figure><h4>Lets us understand the picture on the left. What’s happening is Relu(Input+Output), where input is either the 1st data or the data of previous block and output is Relu(W2(W1+b) + I), where W1 and W2 are the weight of both layers and b is the bias of the previous layer.</h4><h4>Now as we know the basic behind the ResNet architecture, so let’s create one.</h4><pre>class <strong>SimpleResidualBlock</strong>(nn.Module):<br>    def <strong>__init__</strong>(self):<br>        super().__init__()<br>        self.conv1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=1)<br>        self.relu1 = nn.ReLU()<br>        self.conv2 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=1)<br>        self.relu2 = nn.ReLU()<br>        <br>    def <strong>forward</strong>(self, x):<br>        out = self.conv1(x)<br>        out = self.relu1(out)<br>        out = self.conv2(out)<br>        return self.relu2(out) + x <em># ReLU can be applied before or after adding the input</em></pre><p>Note something above, if the dimensions of our output don’t match our residual then we cannot perform Relu addition, hence, we shall not only apply pooling on the input, but the residual would also be transformed through a stridden 1 x 1 conv that would project the filters to be the same as the output and the stride of 2 would half the dimensions just as the max-pooling does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Hb4l_paTxs7mFuLENeR3HQ.png" /><figcaption>Difference between VGG-19, 34_ layer plain and 34 layer residual network</figcaption></figure><p>In the above picture, we saw ResNet34 architecture. The first layer with 7x7 convolution and stride 2 to down sample the input pooling it by the factor of 2. Then it’s followed by 3 identity blocks before down sampling again by 2. In the last average pooling layer, it creates 1000 feature maps, and average it for each feature map. The result is a 1000 dimensional vector which is then fed into the Softmax layer directly making him fully convolutional. There are a total of 6 different types of ResNet architectures namely, ResNet9, ResNet18, ResNet34, ResNet50, Resnet101, ResNet150 differing in the number of layers. After explaining all, I should now present the full ResNet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*nQKteTXtvkoifOiwynexzQ.png" /></figure><h3>Classifying CIFAR10 images using ResNet and Regularization techniques in PyTorch</h3><p>Here are some images from the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*B0LLVdmcxQoI78jgfuF3wA.png" /></figure><h3>System Setup</h3><pre><em># Uncomment and run the commands below if imports fail</em><br><em># !conda install numpy pandas pytorch torchvision cpuonly -c pytorch -y</em><br><em># !pip install matplotlib --upgrade --quiet<br></em>import os<br>import torch<br>import torchvision<br>import tarfile<br>import torch.nn as nn<br>import numpy as np<br>import torch.nn.functional as F<br>from torchvision.datasets.utils import download_url<br>from torchvision.datasets import ImageFolder<br>from torch.utils.data import DataLoader<br>import torchvision.transforms as tt<br>from torch.utils.data import random_split<br>from torchvision.utils import make_grid<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre>project_name=&#39;05b-cifar10-resnet&#39;</pre><h3>Preparing the Data</h3><p>Let’s begin by downloading the dataset and creating PyTorch datasets to load the data, just as we did in the previous tutorial.</p><pre><em># Dowload the dataset</em><br>dataset_url = &quot;http://files.fast.ai/data/cifar10.tgz&quot;<br>download_url(https://medium.com/dataset_url,%20&#39;.&#39;)<br><br><em># Extract from archive</em><br>with tarfile.open(&#39;./cifar10.tgz&#39;, &#39;r:gz&#39;) as tar:<br>    tar.extractall(path=&#39;./data&#39;)<br>    <br><em># Look into the data directory</em><br>data_dir = &#39;./data/cifar10&#39;<br>print(os.listdir(data_dir))<br>classes = os.listdir(data_dir + &quot;/train&quot;)<br>print(classes)</pre><pre><em># Data transforms (normalization &amp; data augmentation)</em><br>stats = ((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))<br>train_tfms = tt.Compose([tt.RandomCrop(32, padding=4, padding_mode=&#39;reflect&#39;), <br>                         tt.RandomHorizontalFlip(), <br>                         tt.ToTensor(), <br>                         tt.Normalize(*stats,inplace=True)])<br>valid_tfms = tt.Compose([tt.ToTensor(), tt.Normalize(*stats)])<br><em># PyTorch datasets</em><br>train_ds = ImageFolder(data_dir+&#39;/train&#39;, train_tfms)<br>valid_ds = ImageFolder(data_dir+&#39;/test&#39;, valid_tfms)<br>batch_size = 400<br><em># PyTorch data loaders</em><br>train_dl = DataLoader(train_ds, batch_size, shuffle=True, num_workers=3, pin_memory=True)<br>valid_dl = DataLoader(valid_ds, batch_size*2, num_workers=3, pin_memory=True)<br>def <strong>show_batch</strong>(dl):<br>    for images, labels in dl:<br>        fig, ax = plt.subplots(figsize=(12, 12))<br>        ax.set_xticks([]); ax.set_yticks([])<br>        ax.imshow(make_grid(images[:64], nrow=8).permute(1, 2, 0))<br>        break<br>show_batch(train_dl)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*HvzS__ZYyMxrK3H-e95isA.png" /><figcaption>The colors seem out of place because of the normalization.</figcaption></figure><h3>Using a GPU</h3><pre>def <strong>get_default_device</strong>():<br>    &quot;&quot;&quot;Pick GPU if available, else CPU&quot;&quot;&quot;<br>    if torch.cuda.is_available():<br>        return torch.device(&#39;cuda&#39;)<br>    else:<br>        return torch.device(&#39;cpu&#39;)<br>    <br>def <strong>to_device</strong>(data, device):<br>    &quot;&quot;&quot;Move tensor(s) to chosen device&quot;&quot;&quot;<br>    if isinstance(data, (list,tuple)):<br>        return [to_device(x, device) for x in data]<br>    return data.to(device, non_blocking=True)<br><br>class <strong>DeviceDataLoader</strong>():<br>    &quot;&quot;&quot;Wrap a dataloader to move data to a device&quot;&quot;&quot;<br>    def <strong>__init__</strong>(self, dl, device):<br>        self.dl = dl<br>        self.device = device<br>        <br>    def <strong>__iter__</strong>(self):<br>        &quot;&quot;&quot;Yield a batch of data after moving it to device&quot;&quot;&quot;<br>        for b in self.dl: <br>            yield to_device(b, self.device)<br><br>    def <strong>__len__</strong>(self):<br>        &quot;&quot;&quot;Number of batches&quot;&quot;&quot;<br>        return len(self.dl)<br>train_dl = DeviceDataLoader(train_dl, device)<br>valid_dl = DeviceDataLoader(valid_dl, device)</pre><pre>def <strong>accuracy</strong>(outputs, labels):<br>    _, preds = torch.max(outputs, dim=1)<br>    return torch.tensor(torch.sum(preds == labels).item() / len(preds))<br><br>class <strong>ImageClassificationBase</strong>(nn.Module):<br>    def <strong>training_step</strong>(self, batch):<br>        images, labels = batch <br>        out = self(images)                  <em># Generate predictions</em><br>        loss = F.cross_entropy(out, labels) <em># Calculate loss</em><br>        return loss<br>    <br>    def <strong>validation_step</strong>(self, batch):<br>        images, labels = batch <br>        out = self(images)                    <em># Generate predictions</em><br>        loss = F.cross_entropy(out, labels)   <em># Calculate loss</em><br>        acc = accuracy(out, labels)           <em># Calculate accuracy</em><br>        return {&#39;val_loss&#39;: loss.detach(), &#39;val_acc&#39;: acc}<br>        <br>    def <strong>validation_epoch_end</strong>(self, outputs):<br>        batch_losses = [x[&#39;val_loss&#39;] for x in outputs]<br>        epoch_loss = torch.stack(batch_losses).mean()   <em># Combine losses</em><br>        batch_accs = [x[&#39;val_acc&#39;] for x in outputs]<br>        epoch_acc = torch.stack(batch_accs).mean()      <em># Combine accuracies</em><br>        return {&#39;val_loss&#39;: epoch_loss.item(), &#39;val_acc&#39;: epoch_acc.item()}<br>    <br>    def <strong>epoch_end</strong>(self, epoch, result):<br>        print(&quot;Epoch [{}], last_lr: {:.5f}, train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}&quot;.format(<br>            epoch, result[&#39;lrs&#39;][-1], result[&#39;train_loss&#39;], result[&#39;val_loss&#39;], result[&#39;val_acc&#39;]))</pre><pre>def <strong>conv_block</strong>(in_channels, out_channels, pool=False):<br>    layers = [nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), <br>              nn.BatchNorm2d(out_channels), <br>              nn.ReLU(inplace=True)]<br>    if pool: layers.append(nn.MaxPool2d(2))<br>    return nn.Sequential(*layers)<br><br>class <strong>ResNet9</strong>(ImageClassificationBase):<br>    def <strong>__init__</strong>(self, in_channels, num_classes):<br>        super().__init__()<br>        <br>        self.conv1 = conv_block(in_channels, 64)<br>        self.conv2 = conv_block(64, 128, pool=True)<br>        self.res1 = nn.Sequential(conv_block(128, 128), conv_block(128, 128))<br>        <br>        self.conv3 = conv_block(128, 256, pool=True)<br>        self.conv4 = conv_block(256, 512, pool=True)<br>        self.res2 = nn.Sequential(conv_block(512, 512), conv_block(512, 512))<br>        <br>        self.classifier = nn.Sequential(nn.MaxPool2d(4), <br>                                        nn.Flatten(), <br>                                        nn.Linear(512, num_classes))<br>        <br>    def <strong>forward</strong>(self, xb):<br>        out = self.conv1(xb)<br>        out = self.conv2(out)<br>        out = self.res1(out) + out<br>        out = self.conv3(out)<br>        out = self.conv4(out)<br>        out = self.res2(out) + out<br>        out = self.classifier(out)<br>        return out<br>model = to_device(ResNet9(3, 10), device)<br>model</pre><h3>Training the model</h3><pre><strong>@torch.no_grad()</strong><br>def <strong>evaluate</strong>(model, val_loader):<br>    model.eval()<br>    outputs = [model.validation_step(batch) for batch in val_loader]<br>    return model.validation_epoch_end(outputs)<br><br>def <strong>get_lr</strong>(optimizer):<br>    for param_group in optimizer.param_groups:<br>        return param_group[&#39;lr&#39;]<br><br>def <strong>fit_one_cycle</strong>(epochs, max_lr, model, train_loader, val_loader, <br>                  weight_decay=0, grad_clip=None, opt_func=torch.optim.SGD):<br>    torch.cuda.empty_cache()<br>    history = []<br>    <br>    <em># Set up cutom optimizer with weight decay</em><br>    optimizer = opt_func(model.parameters(), max_lr, weight_decay=weight_decay)<br>    <em># Set up one-cycle learning rate scheduler</em><br>    sched = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr, epochs=epochs, <br>                                                steps_per_epoch=len(train_loader))<br>    <br>    for epoch in range(epochs):<br>        <em># Training Phase </em><br>        model.train()<br>        train_losses = []<br>        lrs = []<br>        for batch in train_loader:<br>            loss = model.training_step(batch)<br>            train_losses.append(loss)<br>            loss.backward()<br>            <br>            <em># Gradient clipping</em><br>            if grad_clip: <br>                nn.utils.clip_grad_value_(model.parameters(), grad_clip)<br>            <br>            optimizer.step()<br>            optimizer.zero_grad()<br>            <br>            <em># Record &amp; update learning rate</em><br>            lrs.append(get_lr(optimizer))<br>            sched.step()<br>        <br>        <em># Validation phase</em><br>        result = evaluate(model, val_loader)<br>        result[&#39;train_loss&#39;] = torch.stack(train_losses).mean().item()<br>        result[&#39;lrs&#39;] = lrs<br>        model.epoch_end(epoch, result)<br>        history.append(result)<br>    return history</pre><pre>history = [evaluate(model, valid_dl)]<br>history<br>epochs = 8<br>max_lr = 0.01<br>grad_clip = 0.1<br>weight_decay = 1e-4<br>opt_func = torch.optim.Adam<br>%%time<br>history += fit_one_cycle(epochs, max_lr, model, train_dl, valid_dl, <br>                             grad_clip=grad_clip, <br>                             weight_decay=weight_decay, <br>                             opt_func=opt_func)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKU8w7BmENgDGeoF0s61Sw.png" /></figure><pre>def <strong>plot_accuracies</strong>(history):<br>    accuracies = [x[&#39;val_acc&#39;] for x in history]<br>    plt.plot(accuracies, &#39;-x&#39;)<br>    plt.xlabel(&#39;epoch&#39;)<br>    plt.ylabel(&#39;accuracy&#39;)<br>    plt.title(&#39;Accuracy vs. No. of epochs&#39;);<br>plot_accuracies(history)</pre><pre>def <strong>plot_losses</strong>(history):<br>    train_losses = [x.get(&#39;train_loss&#39;) for x in history]<br>    val_losses = [x[&#39;val_loss&#39;] for x in history]<br>    plt.plot(train_losses, &#39;-bx&#39;)<br>    plt.plot(val_losses, &#39;-rx&#39;)<br>    plt.xlabel(&#39;epoch&#39;)<br>    plt.ylabel(&#39;loss&#39;)<br>    plt.legend([&#39;Training&#39;, &#39;Validation&#39;])<br>    plt.title(&#39;Loss vs. No. of epochs&#39;);<br>plot_losses(history)</pre><pre>def <strong>plot_lrs</strong>(history):<br>    lrs = np.concatenate([x.get(&#39;lrs&#39;, []) for x in history])<br>    plt.plot(lrs)<br>    plt.xlabel(&#39;Batch no.&#39;)<br>    plt.ylabel(&#39;Learning rate&#39;)<br>    plt.title(&#39;Learning Rate vs. Batch no.&#39;);<br>plot_lrs(history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*af9tZ6z78uT-gECw_zbZ-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*4S6SJ7wFj8hY8noRAHPSGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*6P65xDoNUVVm5v15y1e4zw.png" /></figure><p><strong>Congratulations, for reaching this far. I know there is a lot of learning there but trust me this topic is worth reading.</strong></p><p>Now, for further reading here are some awesome links that you should check.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fsatyamkumar073%2Fprotein-advanced&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fsatyamkumar073%2Fprotein-advanced&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fsatyamkumar073%2Fprofile_images%2Fc6b60b425b6f437d9ba88435357b34a2%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2bc1d35c1aecefb9735563d110ea724/href">https://medium.com/media/e2bc1d35c1aecefb9735563d110ea724/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuBkiaGTKHCc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuBkiaGTKHCc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuBkiaGTKHCc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/511e983c1094e04aa8b4c267847ffbc3/href">https://medium.com/media/511e983c1094e04aa8b4c267847ffbc3/href</a></iframe><p>Hope you loved this, future posts will be on GANs in deep learning.</p><p>Have a great time ahead!</p><p>You can always reach me on twitter and GitHub via @satyamkumar073.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19ecb7ca359e" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/resnet-architecture-deep-learning-with-pytorch-19ecb7ca359e">ResNet Architecture: Deep Learning with PyTorch</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Covid-19 leading the way for the return of inflation]]></title>
            <link>https://medium.com/@satyamkumarsingh_74579/covid-19-leading-the-way-for-the-return-of-inflation-fc9ebfc3926f?source=rss-73928a3df74f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc9ebfc3926f</guid>
            <category><![CDATA[economy]]></category>
            <category><![CDATA[world-news]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Satyam Kumar Singh]]></dc:creator>
            <pubDate>Tue, 19 May 2020 15:10:52 GMT</pubDate>
            <atom:updated>2020-07-29T23:44:54.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*aC5WdWrGie7qIuFHOO6kbg.jpeg" /></figure><p>For the first time, respondents attached a 21 percent probability that one-year ahead inflation expectations would be above 10 percent — “An IIM-A survey”.</p><p>Inflation in the rich world resembles a fairy-tale beast. Older members of society frighten younger ones with stories of the creature’s foul deeds, but few serious people expect to see one and some doubt it ever existed. Although high inflation seemed a fixture of the economic landscape in the 1970s, changes to policy and the structure of the global economy since have ushered in four decades of ever meeker growth in prices. As covid-19 shutters businesses and leaves supermarket shelves bare, some economists fret that the pandemic could lead to inflation making an unwelcome return.</p><p>The one-year ahead business inflation expectation shot up to 4.57 percent in March 2020 from 3.85 percent reported in February 2020.</p><p>Economists estimate that for every month of lock down an economy shrinks 2.5%. That makes a two-month lock down equal to the 5% fall in output from the financial crisis and more severe if it stretched out to three months or longer. Double-digit budget deficits would be unavoidable under this scenario.</p><p>This will leave administrations with some very tough choices. Politics in countries have already taken a populist turn as a result of the austerity and the fallout from the financial crisis. It will be very difficult politically to make further cuts in public services or welfare payments to restore the health of the government’s balance sheet.</p><p>The only other easy options are direct financing by the central banks or raising taxes but the large companies and wealthy individuals that governments would like to pay them are very mobile these days and difficult to pin down. Increasing taxes on the middle classes is electoral suicide.</p><p>There could be one final and better option. Now might be the time to do what left-of-center politicians and economists have been advocating for some time, and that is carry on spending. The government would keep the economy on a ‘war footing’ even as the corona virus epidemic retreats and redirect the spending on wage and business support to productive investment. The goal would be to restructure the economy, and not to worry if the debt-to-GDP ratio goes north of 150%.</p><p>Done right it could set the course of the economy for a generation and bring in the revenues to pay back the debt. The other choices are more austerity or high inflation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc9ebfc3926f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>