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

#Predict Co2Emission using enginesize.

"""Read the csv file"""
df = pd.read_csv("FuelConsumptionCo2.csv", sep=",")
print(df.head()) #print first 5 rows
print(f'Number of columns : {len(df.columns)}')
print(df.columns) #print columns

"""Properties of dataset"""
print(df.describe()) #only of columns with numerical values.

"""Data types"""
print(df.dtypes) #to see datatypes of the columns: int,float, objects etc

"""Test/Train"""
#x=train, y=test
mask = np.random.rand(len(df)) < 0.8 #len(df)== numbers of rows. we are generating true,false for them.
print(mask) #msk true if numbers generated by np is < 0.8 else >=0.8 False
train = df[mask] # 80% , it pick the row for which mask is true.
test = df[~mask] #~ for remaining 20%, for mask false

# we can see our data is now random(rows) and exclusive.
print(train.head())
print(test.head())

"""Plot Enginesize(X) vs co2Emission(Y)"""
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='green')
plt.xlabel("Engine Size")
plt.ylabel("CO2Emission")
plt.show() # make sure tkinter or pyQt is installed if you not on notebook.

"""Model data using sklearn"""
from sklearn import linear_model
linear = linear_model.LinearRegression()

train_x=np.asanyarray(train[['ENGINESIZE']]) #2D array [[]]
train_y=np.asanyarray(train[['CO2EMISSIONS']])

"""Fit line (intercept & slope/coefficients)"""
linear.fit(train_x,train_y)
print(f'intercept : {linear.intercept_[0]}, coefficients: {linear.coef_[0][0]}')

"""Fit line draw"""
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='green')
#plt.plot(train_x,linear.coef_[0][0]*train_x+linear.intercept_[0], color="red",linestyle = 'dashed')#  x=train_x, y=mx +c
plt.plot(train_x,linear.coef_[0][0]*train_x+linear.intercept_[0], '-r')#  x=train_x, y=mx +c
plt.xlabel("Engine Size")
plt.ylabel("CO2Emission")
plt.show() # make sure tkinter or pyQt is installed if you not on notebook.

"""Evaluation"""
test_x=np.asanyarray(test[['ENGINESIZE']]) #2D array [[]]
test_y=np.asanyarray(test[['CO2EMISSIONS']])

test_pred_y=linear.predict(test_x)
from sklearn.metrics import r2_score
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_pred_y - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((test_pred_y - test_y) ** 2))
print("R2-score: %.2f" % r2_score(test_y , test_pred_y) )