Linear Regression Code On Single Variable | Python | Supervised Learning

Hello guys, welcome back to my blog. In this article, I will share the code of linear regression of a single variable.If you guys want an article on some other topics then comment us below in the comment section. You can also catch me @ Instagram – Chetan Shidling.

Linear Regression Code On Single Variable | Python | Supervised Learning

Linear Regression Code

Linear Regression Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv(‘data1.txt’,header = None)
                                                              
x=np.array(data[ :])      //CS Electrical & Electronics
xs=x[:,[0]]  #independent variable
                        population is fetched
ys=x[:,[1]]  #dependent variable
                         profit is fetched
#plotting of data
def plotdata(xs,ys):
    plt.scatter(xs,ys)
    plt.axis([4, 24, -5, 25]);
    plt.xlabel(“population of cities in 10000’s”);
    plt.ylabel(“profit in $10000’s”);
   
plotdata(xs,ys)
theta=np.array([[0],[0]])
iter=1500                             //Chetan Shidling
alpha=0.01
m=len(x)
#inserting 1st column
xs=np.insert(xs,0,1,axis=1)
def computecost(xs,ys,theta):
   
    j=np.sum((np.power((np.dot
(xs,theta)-ys),2)))/(2*m)
   print(‘Cost j =’,j)
   
#implementation of gradient descent
for i in range(1,iter,1):
    theta0mul=np.dot(xs,theta)
    error=(theta0mul-ys)
    temp0=theta[0]-((alpha/m)*(np.sum
(np.multiply(error,xs[:,[0]]))))
   
    theta1mul=np.multiply(error,(xs[:,[1]]))
    sum02=(np.sum(theta1mul))
    temp1=theta[1]-((alpha/m)*(sum02))
 #update theta1
   
    theta=[temp0,temp1]
    computecost(xs,ys,theta)
   
print(‘finaltheta’,theta)
plt.show()
plt.figure()
plotdata(xs[:,[1]],ys)
plt.hold(True)
plt.plot(xs[:,[1]],np.dot(xs,theta),’-‘,color=’r’)
plt.show()
#for population=35000 we predict a profit
predict1_xs=np.matrix([1,3.5])
theta=np.matrix(theta)
predict1=np.dot(predict1_xs,theta)
print(‘for population=35000,predict a
profit’,predict1*10000)
#for population=70000
predict2_xs=np.matrix([1,7])
predict2=np.dot(predict2_xs,theta)
print(‘for population=70000,predict a
profit’,predict2*10000)
I hope this article may help you all a lot. Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *