# -*- coding: utf-8 -*-
"""Linear_Regerssion.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/github/Abdokarawia/Linear-Regerssion/blob/main/Linear_Regerssion.ipynb
"""

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

EDS = pd.read_csv('/content/FuelConsumptionCo2.csv')
EDS.head()   # Showing a sample of the dataset

EDS.describe()

sns.pairplot(EDS , aspect=1 , height=4)
plt.show()

DS = EDS [['ENGINESIZE', 'CYLINDERS', 'FUELCONSUMPTION_COMB',  'FUELCONSUMPTION_CITY', 'CO2EMISSIONS' , 'FUELCONSUMPTION_COMB_MPG' ]] 
DS.head(9)

sns.pairplot(data =DS , kind='scatter', height=4,   x_vars=['ENGINESIZE', 'CYLINDERS', 'FUELCONSUMPTION_COMB' , "FUELCONSUMPTION_COMB_MPG"], y_vars="CO2EMISSIONS" )
plt.show()

sns.boxplot(DS.CO2EMISSIONS ,color="lightblue")
plt.show()

sns.heatmap(DS.corr(), cmap="YlGnBu")
plt.show()

# First Way
mask  = np.random.rand(len(DS)) < 0.75
train = DS[mask]
test  = DS [~mask]

# Second Way
# from sklearn.model_selection import train_test_split
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

sns.pairplot(data =train , kind='scatter', height=4, aspect=1.2 , x_vars=['ENGINESIZE', 'CYLINDERS', 'FUELCONSUMPTION_COMB'], y_vars="CO2EMISSIONS" )
sns.pairplot(data =test , kind='scatter', height=4, aspect=1.2 , x_vars=['ENGINESIZE', 'CYLINDERS', 'FUELCONSUMPTION_COMB'], y_vars="CO2EMISSIONS" )
plt.show()

from sklearn.linear_model import  LinearRegression
LR = LinearRegression()
x_train = np.asarray(train[["ENGINESIZE"]])
y_train = np.asarray(train[["CO2EMISSIONS"]])
x_test  = np.asarray(test[["ENGINESIZE"]])
y_test  = np.asarray(test[["CO2EMISSIONS"]])
LR.fit(x_train , y_train)
intercept = LR.intercept_
coef = LR.coef_

plt.scatter(x_train, y_train , c="blue")
plt.plot(x_train, LR.predict(x_train)  , c="red")
predict_test = LR.predict(x_test)

from sklearn.metrics import r2_score
MAE = np.mean(np.abs(predict_test - y_test))
MSE = np.mean(np.abs(predict_test - y_test) **2 )
R2 = r2_score(y_test , predict_test)
print("Mean absolute error: %.2f" % MAE)
print("Residual sum of squares (MSE): %.2f" % MSE)
print("R2-score: %.4f" % R2 )









