Professional Documents
Culture Documents
Pattern - Recognition - 2 - Code
Pattern - Recognition - 2 - Code
"""
Created on Mon Mar 29 20:23:29 2021
@author: Khaldon
"""
#import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#read data
path = 'D:\\lectures\\Pattern Recognition\\lectures\\Linear Regression\\ex1data1.txt'
data = pd.read_csv(path, header= None, names=['Population', 'Profit'])
#=========================================================================
print('**************************************' )
print('X data = \n' ,X.head(10) )
print('y data = \n' ,y.head(10) )
print('**************************************' )
print('X \n',X)
print('X.shape = ' , X.shape)
print('theta \n',theta)
print('theta.shape = ' , theta.shape)
print('y \n',y)
print('y.shape = ' , y.shape)
print('**************************************' )
#=========================================================================
# cost function
def computeCost(X, y, theta):
1
z = np.power(((X * theta.T) - y), 2)
# print('z \n',z)
# print('m ' ,len(X))
return np.sum(z) / (2 * len(X))
print('**************************************' )
# GD function
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))
parameters = int(theta.ravel().shape[ 1])
cost = np.zeros(iters)
for i in range(iters):
error = (X * theta.T) - y
for j in range(parameters):
term = np.multiply(error, X[:,j])
temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))
theta = temp
cost[i] = computeCost(X, y, theta)
print('g = ' , g)
print('cost = ' , cost[0:50] )
print('computeCost = ' , computeCost(X, y, g))
print('**************************************' )
#=========================================================================
f = g[0, 0] + (g[0, 1] * x)
print('f \n',f)
2
ax.scatter(data.Population, data.Profit, label= 'Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Predicted Profit vs. Population Size' )