<jupyter_start><jupyter_text>Linear regression<jupyter_code>import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
data = pd.read_csv('https://raw.githubusercontent.com/mubaris/potential-enigma/master/headbrain.csv')
data.head(10)
X=data['Head Size(cm^3)'].values
Y=data['Brain Weight(grams)']

num=np.sum((X-X.mean())*(Y-Y.mean()))
den=np.sum((X-X.mean())*(X-X.mean()))
mean_x = np.mean(X)
mean_y = np.mean(Y)
n = len(X)

numer = 0
denom  = 0
for i in range(n):
  numer+=(X[i]-mean_x) *(Y[i]-mean_y)
  denom+=(X[i]-mean_x) **2 
b1 = numer/denom
b0=mean_y-(b1 * mean_x)
print(b1,b0)
max_x = np.max(X) + 100
min_x = np.min(X) - 100

# Calculating line values x and y
x = np.linspace(min_x, max_x, 1000) # Returns number spaces evenly w.r.t interval
y = b0 + b1 * x

# Ploting Line
plt.plot(x, y, color='#58b970', label='Regression Line')
# Ploting Scatter Points
plt.scatter(X, Y, c='#ef5423', label='Scatter Plot')

plt.xlabel('Head Size in cm3')
plt.ylabel('Brain Weight in grams')
plt.legend()
plt.show()
y_pred=b0+b1*X
RMSE=np.sum(np.square(y_pred-Y))
n=Y.shape[0]
RMSE=np.sqrt((RMSE/n))
print(RMSE)
ss_tot = 0
ss_res = 0
for i in range(n):
  y_pred = b0 + b1* X[i]
  ss_tot += (Y[i]- mean_y) **2
  ss_res += (Y[i]- y_pred) **2
r2 = 1 - (ss_res/ss_tot)
print(r2)
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
X = X.reshape((n,1))
reg = LinearRegression()
reg = reg.fit(X,Y)
Y_pred = reg.predict(X)
mse = mean_squared_error(Y,Y_pred)
r2_score = reg.score(X,Y)
print(np.sqrt(mse))
print(r2_score)
print("intercept" , reg.intercept_)
print("slope" , reg.coef_)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17930629041740154, 'fraction_numerical': 0.02821869488536155, 'mean_word_length': 5.257352941176471, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 1, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '630440', 'license': 'MIT', 'n_tokens_mistral': 799, 'n_tokens_neox': 754, 'n_words': 157, 'path': 'Linear_Regression.ipynb', 'repo_name': 'ColdCoffee21/Foundations-of-Data-Science', 'size': '1701'}