<jupyter_start><jupyter_text>Linear Regression using Normal Equation / Closed FormIt is a method to solve for parameters $(\theta)$ analyticallyWe have to solve the equation :- $\theta = (X^TX)^{-1}  X^Ty$ where : $X$  is a $m$ x $(n+1)$ matrix containing all the feature values of training set.$X^T$  is transpose of $X$ matrix.$y$ is a vector i.e ($m$ x $1$) matrix containing values of target variableHere, $m$ is no of training examples and $n$ is number of features.<jupyter_code>#import required packages
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import datasets
#get data in place
points = np.genfromtxt("../../data/data.csv",delimiter=",")
X = points[:,0]
Y = points[:,1]

X_test = X[0:10]
Y_test = Y[0:10]

X_train = X[10:100]
Y_train = Y[10:100]

X_train<jupyter_output><empty_output><jupyter_text>Prepare matrix XFor preparing matix X, we must convert vector X to a matrix of 2 columns.Column 1 i.e $X_{0}$ must be a column of ones.<jupyter_code>#converting vectors to a column matrix
X0 = np.ones((X_train.shape[0],1))
X1 = np.reshape(X_train,(X_train.shape[0],1))

#use hstack to combine both matrices
X_mat = np.hstack((X0,X1))
X_mat
#get matrix y
Y_mat = np.reshape(Y_train,(Y_train.shape[0],1))
Y_mat
#get theta matrix using training examples

X_t = X_mat.transpose()
prt1  = np.linalg.inv(np.dot(X_t , X_mat))
prt2 = np.dot(prt1,X_t)

theta = np.dot(prt2,Y_mat)

theta<jupyter_output><empty_output><jupyter_text>Time to get answers from our model !We observe that :$h_{\theta}(x) = \theta_{0} * (x_{0}) + \theta_{1} * (x_{1}) $  here $x_{0} = 1$ Remember we had added an extra column of ones to our X_train matrix earlier... that was done to satisfy this condition now...We can see that $h_{\theta}(x)$ is product of $\theta$ matrix and $X$ matrix Hence product of $X$ matrix and $\theta$ matrix will give a matrix with 1 column containing values o f $Y$ for the given $X$ values in $X$ matrix used.<jupyter_code>#get value of y for test data 
X0_test = np.ones((X_test.shape[0],1))
X1_test = np.reshape(X_test,(X_test.shape[0],1))

#use hstack to combine both matrices
X_test_mat = np.hstack((X0_test,X1_test))

#get answers for test data from the model
Y_regression = np.dot(X_test_mat,theta)

Y_test = np.reshape(Y_test,(Y_test.shape[0],1))

#for testing accuracy of the model
mean_squared_error = 0; 
for i in range (0,Y_test.shape[0]):
    diff = Y_test[i] - Y_regression[i]
    mean_squared_error += diff*diff
    
mean_squared_error = mean_squared_error/Y_test.shape[0]

print("mean squared error = {0}".format(mean_squared_error))
    
#plot solution
y_intercept = theta[0]
slope = theta[1]

plt.figure()
plt.scatter(X,Y)

x = np.linspace(20,80,10)
y = slope*x+y_intercept
plt.plot(x, y, '-r', label='y=2x+1')
plt.xlabel('x', color='#1C2833')
plt.ylabel('y', color='#1C2833')
plt.legend(loc='upper left')
plt.grid()

plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1409028727770178, 'fraction_numerical': 0.027359781121751026, 'mean_word_length': 5.068464730290456, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '300542', 'license': 'MIT', 'n_tokens_mistral': 1147, 'n_tokens_neox': 1101, 'n_words': 330, 'path': 'notebooks/linear_regression/Linear Regression using Normal Equation..ipynb', 'repo_name': 'pugnator-12/homemade-machine-learning', 'size': '2924'}