Machine learning code related to linear regression using python?

All QuestionsCategory: Artificial Intelligence, Machine Learning, & Deep LearningMachine learning code related to linear regression using python?
Chetan Shidling Staff asked 5 years ago

I need code.

1 Answers
Chetan Shidling Staff answered 5 years ago

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[ :])
xs = x[:,[0]] ys = x[:,[1]] def plotdata(xs, ys):
plt.scatter(xs, ys)
plt.axis([4, 24, -5, 25]);
plt.xlabel(“Population of City in 10,000s”);
plt.ylabel(“Profit in $10,000s”);

plotdata(xs, ys)
theta = np.array([[0], [0]])
iter = 5000
alpha = 0.01
m = len(ys)
xs = np.insert(xs, 0, 1, axis=1)
#implementation of cost
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))

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()
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)
predict2_xs = np.matrix([1, 7])
predict2 = np.dot(predict2_xs, theta)
print(‘For population = 70000, predict a profit’, predict2*10000)