Linear regression is a common machine learning technique that predicts a real-valued output using a weighted linear combination of one or more input values. For instance, the sale price of a house can often be estimated using a linear combination of features such as area, number of bedrooms, number of floors, date of construction etc. Mathematically, it can be expressed using the following equation: house_price = w1 * area + w2 * n_bedrooms + w3 * n_floors + ... + w_n * age_in_years + b The “learning” part of linear regression is to figure out a set of weights that leads to good predictions. This is done by looking at lots of examples one by one (or in batches) and adjusting the weights slightly each time to make better predictions, using an optimization technique called . w1, w2, w3, ... w_n, b Gradient Descent Let’s create some sample data with one feature (e.g. floor area) and one dependent variable (e.g. house price). We’ll assume that is a linear function of , with some noise added to account for features we haven’t considered here. Here’s how we generate the data points, or samples: x y y x m, c = , noise = np.random.randn( ) / x = np.random.rand( ) y = x * m + c + noise 2 3 250 4 250 And here’s what it looks like visually: Now we can define and instantiate a linear regression model in PyTorch: super(LinearRegressionModel, self).__init__() self.linear = nn.Linear(input_dim, output_dim) out = self.linear(x) outmodel = LinearRegressionModel( , ) criterion = nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr= ) : class LinearRegressionModel (nn.Module) : def __init__ (self, input_dim, output_dim) : def forward (self, x) return 1 1 0.01 For the full code, including imports etc. see . Here’s how the model weights look like right now: this link As you can see, it’s quite far from the desired result. Now we can define a utility function to run a training epoch: inputs = Variable(torch.from_numpy(x.reshape( , ).astype( ))) labels = Variable(torch.from_numpy(y.reshape( , ).astype( ))) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() loss : def run_epoch (epoch) # Convert from numpy array to torch tensors -1 1 'float32' -1 1 'float32' # Clear the gradients w.r.t. parameters # Forward to get the outputs # Calcuate loss # Getting gradients from parameters # Updating parameters return Next, we can train the model and update the state of a animated graph at the end of each epoch: %matplotlib notebook fig, (ax1) = plt.subplots( , figsize=( , )) ax1.scatter(x, y, s= )w1, b1 = get_param_values() x1 = np.array([ , ]) y1 = x1 * w1 + b1 fit, = ax1.plot(x1, y1, , label= .format(w1, b1)) ax1.plot(x1, x1 * m + c, , label= ) ax1.legend() ax1.set_xlabel( ) ax1.set_ylabel( ) ax1.set_title( ) ax1.set_ylim( , ) fit, loss = run_epoch(i) [w, b] = model.parameters() w1, b1 = w.data[ ][ ], b.data[ ] y1 = x1 * w1 + b1 fit.set_ydata(y1)epochs = np.arange( , ) ani = FuncAnimation(fig, animate, epochs, init_func=init, interval= , blit= , repeat= ) plt.show() 1 12 6 8 0. 1. 'r' 'Predicted' 'g' 'Best Fit' 'x' 'y' 'Linear Regression' : def init () 0 6 return : def animate (i) 0 0 0 1 250 100 True False This will result in following animated graph: That’s it! It takes about 200 epochs for the model to come quite close to the best fit line. The complete code for this post can be found in this Jupyter notebook: https://gist.github.com/aakashns/82db9df1e6c20eb13523903507dbd537