<?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 Naga Karthik on Medium]]></title>
        <description><![CDATA[Stories by Naga Karthik on Medium]]></description>
        <link>https://medium.com/@emvnagakarthik?source=rss-3c13159609ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eAnxH_k0Ik3_cJCE46BJ7A.jpeg</url>
            <title>Stories by Naga Karthik on Medium</title>
            <link>https://medium.com/@emvnagakarthik?source=rss-3c13159609ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:13:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emvnagakarthik/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[Linear Regression with PyTorch]]></title>
            <link>https://medium.com/@emvnagakarthik/linear-regression-with-pytorch-e122a4f9d96c?source=rss-3c13159609ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/e122a4f9d96c</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Naga Karthik]]></dc:creator>
            <pubDate>Fri, 01 Feb 2019 16:28:23 GMT</pubDate>
            <atom:updated>2019-02-01T16:28:23.174Z</atom:updated>
            <content:encoded><![CDATA[<p>This is just a simple introduction to coding in PyTorch. We’ll build a two-dimensional linear regression model and see how the model performs by observing the graphs at the output. So, let’s begin!</p><p>There are a million ways to create a linear regression model if we have the data readily available (or downloaded from somewhere). In that case, we will not be able to take advantage of PyTorch’s <em>Dataset</em> class which allows us to create datasets of our own and test them (interesting, right?). Therefore, in this article, I will be showing how to create an artificial dataset using the <em>Dataset</em> class and run our model. PyTorch also has this cool feature of letting users build their own custom modules of any kind, be it linear regression model, logistic regression model, neural network model etc. However, it goes without saying that there are in-built functions also for the same purposes. Enough of the jargon now, let’s dive into the code!</p><p>First off, we will begin by importing all the necessary packages to build our model.</p><pre>import numpy as np<br>import torch<br>from torch import nn, optim<br>from torch.utils.data import Dataset, DataLoader<br>torch.manual_seed(1)<br>import matplotlib.pyplot as plt<br>from mpl_toolkits.mplot3d import Axes3D</pre><p><em>Dataset </em>is the class that contains the artificial dataset (in the form of a subclass within the main class) that we will define and <em>DataLoader</em> is responsible for loading the dataset. For creating our custom modules, the <em>nn</em> module must be imported and for choosing the optimizer of our choice, the <em>optim</em> module must be used.</p><pre># Creating the artificial dataset<br>class Data2d(Dataset):<br>    <br>    # Constructor<br>    def __init__(self):<br>        self.x = torch.zeros(20,2)<br>        self.x[:,0] = torch.arange(-1,1,0.1)<br>        self.x[:,1] = torch.arange(-1,1,0.1)<br>        <br>        self.w = torch.tensor([[1.0], [1.0]])<br>        self.b = 1<br>        self.f = torch.mm(self.x, self.w) + self.b<br>        <br>        self.y = self.f + 0.1*torch.randn((self.x.shape[0],1))<br>        self.len = self.x.shape[0]<br>    <br>    # Getter<br>    def __getitem__(self, index):<br>        return self.x[index], self.y[index]<br>    <br>    # Getting the length<br>    def __len__(self):<br>        return self.len</pre><pre># Instantiation of the class  <br>my_data = Data2d()</pre><p>We have randomly chosen any set of values of x , which I have assumed to a 2D matrix (for no particular reason, it can be anything!). The slope and bias w and b respectively are defined. The equation of a line is written and stored in the variable f . I have added some random Gaussian noise to the equation with a standard deviation of 0.1 so that it isn’t just a straight line.</p><p>Next up in the code is a function we have defined that plots the 2D plane for better visualization purposes.</p><pre># Defining a function for plotting the plane<br>def plane2D(model,dataset,n=0):<br>      <br>    w1 = model.state_dict()[&#39;linear.weight&#39;].numpy()[0][0]<br>    w2 = model.state_dict()[&#39;linear.weight&#39;].numpy()[0][1]<br>    b = model.state_dict()[&#39;linear.bias&#39;].numpy()<br>    <br>    x1 = dataset.x[:,0].view(-1,1).numpy()<br>    x2 = dataset.x[:,1].view(-1,1).numpy()<br>    y = dataset.y.numpy()<br>    X,Y = np.meshgrid(np.arange(x1.min(),x1.max(),0.05),np.arange(x2.min(), x2.max(), 0.05))<br>    <br>    yhat = w1*X + w2*Y + b<br>    <br>    # plotting<br>    fig = plt.figure()<br>    ax = fig.gca(projection = &#39;3d&#39;)<br>    <br>    ax.plot(x1[:,0], x2[:,0], y[:,0], &#39;ro&#39;, label = &#39;y&#39;)<br>    ax.plot_surface(X,Y,yhat)<br>    ax.set_xlabel(&#39;x&#39;)<br>    ax.set_ylabel(&#39;y&#39;)<br>    ax.set_zlabel(&#39;z&#39;)<br>    ax.legend()<br>    plt.title(&#39;Estimated plane iteration: &#39;+ str(n))<br>    plt.show()</pre><p>PyTorch defines the parameters, that is, the slope and the bias randomly. We are storing those values by calling the model.state_dict() function and explicitly mentioning them by linear.weight and linear.bias. We will be passing the artificial dataset as an argument to the plane2D function, from where the data is stored in the corresponding variables. The remaining part of the code is just the standard way of plotting 3D data.</p><p>Note: The .numpy() function is used wherever there is a need of converting the data from a <em>tensor </em>(PyTorch processes data in the form of tensors)<em> </em>to a <em>numpy</em> array.</p><pre># Creating a linear regression model<br>class lin_reg(nn.Module):<br><br>    def __init__(self, in_feat, out_feat):<br>        super(lin_reg, self).__init__()<br>        self.linear = nn.Linear(in_feat, out_feat)<br>        <br>    def forward(self,x):<br>        yhat = self.linear(x)<br>        return yhat</pre><pre># Instantiation of an object<br>model = lin_reg(2,1)<br>print(&quot;The parameters: &quot;, model.state_dict())</pre><p>nn.Module is the base class for all modules in PyTorch. All the models that we define must be subclasses within this class. The super() function returns a proxy object that delegates the methods calls to a class. The in-built function nn.Linear is used which just takes the number of input and output features as arguments and simply applies the linear transformation. It can be looked at in this way, the __init__() function is where the model variables are initialized and the forward() function is where these variables are used to predict the output.</p><p>Now, all that’s left is to define the loss function, the optimizer and then train our model!</p><pre># Parameters<br>criterion = nn.MSELoss()<br>optimizer = optim.SGD(model.parameters(), lr = 0.01) </pre><pre># Training data object which loads the artificial data<br>trainloader = DataLoader(dataset = my_data, batch_size = 2)</pre><pre># Training the model<br>Loss = []  # variable for storing losses after each epoch<br>epochs = 100</pre><pre>print(&#39;Before training:&#39;)<br>plane2D(model, my_data)</pre><pre>def train_model(epochs):<br>    for epoch in range(epochs):<br>        for x,y in trainloader:<br>            yhat = model(x)<br>            loss = criterion(yhat,y)<br>            Loss.append(loss.item())<br>            optimizer.zero_grad()<br>            loss.backward()<br>            optimizer.step()</pre><pre># Calling the training function          <br>train_model(epochs)</pre><pre>print(&quot;After training: &quot;)<br>plane2D(model, my_data, epochs)</pre><p>I have decided to use the mean-squared error as the loss function. The in-built function is used here, however, a function can be created which does the same.</p><pre>def criterion(yhat,y):<br>    out = torch.mean((yhat - y)**2)<br>    return out</pre><p>The optimizer used is Stochastic Gradient Descent (SGD). The model parameters must be passed as the argument and an appropriate learning rate must be defined. The way in which PyTorch calculates the error and updates the weights is that, firstly, all the gradients are set to zero using .zero_grad()function, then the derivatives are calculated using the .backward() function. Finally, the weights are updated using the .step() function. The loss after the completion of each epoch is stored which helps in plotting (after the training is completed). It is just to see how the model performed during the training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*X3dM4rJxLpeObdCNTMMbvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*sfmQqMal29n_wszrlhmYfg.png" /><figcaption>The results of the above model. The left image shows the plane at epoch zero and the right image shows the result after the training has been completed.</figcaption></figure><p>And that’s it! I hope that this introductory tutorial in PyTorch helps. Please feel free to comment/suggest anything related to the above article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e122a4f9d96c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>