# -*- coding: utf-8 -*-
"""P3-1-Least Square Regression.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1gU6rRYa8vNSqSFvH9dDuRKc80I1Oejvg
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = (12.0, 9.0)

# Preprocessing Input data
data = pd.read_csv('/content/Data (2).csv')
X = data.iloc[:, 0]
Y = data.iloc[:, 1]
plt.scatter(X, Y)
plt.show()

# Building the model
#Calculating the means
X_mean = np.mean(X)
Y_mean = np.mean(Y)

cov = 0
var = 0
for i in range(len(X)):
    cov += (X[i] - X_mean)*(Y[i] - Y_mean)# Calculate the covariance of X and Y
    var += (X[i] - X_mean)**2 # Calculate the variance of X
regcoeff = cov / var
intercept = Y_mean - regcoeff*X_mean

print (regcoeff, intercept)

# Making predictions
Y_pred = regcoeff*X + intercept

plt.scatter(X, Y) # actual
plt.plot([min(X), max(X)], [min(Y_pred), max(Y_pred)], color='red') # predicted
plt.show()

# my cooode


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Set plot size
plt.rcParams['figure.figsize'] = (10, 6)

# Load data
data = pd.read_csv(r'/content/Data (2).csv')

# Extract features and target
X = data.iloc[:, 0].values
Y = data.iloc[:, 1].values

# Scatter plot of original data
plt.scatter(X, Y, color='blue', label='Actual Data')
plt.title('Data Visualization')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()

# --- Linear Regression from Scratch ---

# Calculate means
X_mean = np.mean(X)
Y_mean = np.mean(Y)

# Calculate covariance and variance
cov = np.sum((X - X_mean) * (Y - Y_mean))
var = np.sum((X - X_mean) ** 2)

# Regression coefficients
reg_coeff = cov / var
intercept = Y_mean - reg_coeff * X_mean

print(f"Slope (regression coefficient): {reg_coeff:.4f}")
print(f"Intercept: {intercept:.4f}")

# Predictions
Y_pred = reg_coeff * X + intercept

# --- Model Evaluation ---
# R² Score
ss_total = np.sum((Y - Y_mean) ** 2)
ss_residual = np.sum((Y - Y_pred) ** 2)
r2_score = 1 - (ss_residual / ss_total)
print(f"R² Score: {r2_score:.4f}")

# --- Visualization ---
plt.scatter(X, Y, color='blue', label='Actual Data')
plt.plot(X, Y_pred, color='red', label='Regression Line')
plt.title('Simple Linear Regression')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid(True)
plt.show()