Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Machine Learning by (19k points)

I am trying to implement this algorithm to find the intercept and slope for a single variable:


Here is my Python code to update the Intercept and slope. But it is not converging. RSS is Increasing with Iteration rather than decreasing and after some iteration, it's becoming infinite. I am not finding any error in implementing the algorithm. How Can I solve this problem? I have attached the csv file too. Here is the code.

import pandas as pd

import numpy as np

#Defining gradient_decend

#This Function takes X value, Y value and vector of w0(intercept),w1(slope)

#INPUT FEATURES=X(sq.feet of house size)

#TARGET VALUE=Y (Price of House)



#    w1]

def gradient_decend(X,Y,W):



    #Here i will get a list

    #list is like this


    #     sum(predicted_value-(intercept+slope*x)*x)]

    gd=[sum(y-(intercept+slope*x) for x,y in zip(X,Y)),

        sum(((y-(intercept+slope*x))*x) for x,y in zip(X,Y))]

    return np.array(gd).reshape(2,1)

#Defining Resudual sum of squares

def RSS(X,Y,W):

    return sum((y-(W[0][0]+W[1][0]*x))**2 for x,y in zip(X,Y))


#Reading Training Data


#Defining fixed parameters

#Learning Rate







#Creating 2,1 vector of w0,w1 parameters


#Running gradient Decend

for i in range(iteration):

     W=W+((2*n)*    (gradient_decend(training_data["sqft_living"],training_data["price"],W)))

     print RSS(training_data["sqft_living"],training_data["price"],W)

Here is the CSV file.

1 Answer

0 votes
by (33.1k points)

Simple Linear Regression in Python:


import numpy as np

import pandas as pd

import math

from sys import stdout

def get_numpy_data(data, features, output):

    #Adding a constant column with value 1 in the dataframe.

    data['constant'] = 1    

    #Adding the name of the constant column in the feature list.

    features = ['constant'] + features

    #Creating Feature matrix(Selecting columns and converting to matrix).


    #Target column is converted to the numpy array


    return(features_matrix, output_array)

def predict_outcome(feature_matrix, weights):


    predictions =, weights)

    return predictions

def errors(output,predictions):


    return errors

def feature_derivative(errors, feature):,,errors))

    return derivative


def regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance):

    converged = False

    #Initital weights are converted to numpy array

    weights = np.array(initial_weights)

    while not converged:

        # compute the predictions based on feature_matrix and weights:


        # compute the errors as predictions - output:


        gradient_sum_squares = 0 # initialize the gradient

        # while not converged, update each weight individually:

        for i in range(len(weights)):

            # Recall that feature_matrix[:, i] is the feature column associated with weights[i]

            feature=feature_matrix[:, i]

            # compute the derivative for weight[i]:




            # add the squared derivative to the gradient magnitude


            # update the weight based on step size and derivative:

            weights[i]=weights[i] -,deriv)

        gradient_magnitude = math.sqrt(gradient_sum_squares)

        stdout.write("\r%d" % int(gradient_magnitude))


        if gradient_magnitude < tolerance:

            converged = True


Hope this answer helps.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94.1k users

Browse Categories