This repository was archived by the owner on Jul 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathregression.py
More file actions
141 lines (104 loc) · 5.62 KB
/
regression.py
File metadata and controls
141 lines (104 loc) · 5.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 7 20:40:04 2018
@author: AGBENYA Koffi Moïse
We download a dataset that is related to fuel consumption and Carbon dioxide emission of cars.
Then, we split our data into training and test sets, create a model using training set,
Evaluate your model using test set, and finally use model to predict unknown value.
The dataset contains model-specific fuel consumption ratings and estimated carbon dioxide
emissions for new light-duty vehicles for retail sale in Canada.
The dataset source is :
https://open.canada.ca/data/en/dataset/98f1a129-f628-4ce4-b24d-6f16bf24dd64
Datasets provide model-specific fuel consumption ratings and estimated carbon dioxide
emissions for new light-duty vehicles for retail sale in Canada.
To help you compare vehicles from different model years, the fuel consumption ratings for 1995
to 2014 vehicles have been adjusted to reflect the improved testing that is more representative
of everyday driving. Note that these are approximate values that were generated from the original
ratings, not from vehicle testing.
"""
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
path = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv"
df = pd.read_csv(path)
#Let's have a descriptive exploration on our data
print(df.describe())
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]
# We can plot each of these features
viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']]
viz.hist()
#Now, lets plot each of these features vs the Emission, to see how linear is their relation:
#Fuel comsumption vs co2 emissions
plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue')
plt.xlabel("FUELCONSUMPTION_COMB")
plt.ylabel("Emission")
plt.show()
#Engine size vs co2 emissions
plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')
plt.xlabel("Engine size")
plt.ylabel("Emission")
plt.show()
#plot CYLINDER vs the Emission, to see how linear is their relation:
plt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS, color='red')
plt.xlabel("Cylinders")
plt.ylabel("Emission")
plt.show()
#Creating train and test dataset
#Train/Test Split involves splitting the dataset into training and testing sets respectively,
#which are mutually exclusive. After which, you train with the training set and test with the
#testing set. This will provide a more accurate evaluation on out-of-sample accuracy because
#the testing dataset is not part of the dataset that have been used to train the data. It is
#more realistic for real world problems.
#This means that we know the outcome of each data point in this dataset, making it great to
#test with! And since this data has not been used to train the model, the model has no knowledge
#of the outcome of these data points. So, in essence, it is truly an out-of-sample testing.
msk = np.random.rand(len(df)) < 0.8
train = cdf[msk]
test = cdf[~msk]
#Linear Regression fits a linear model with coefficients B = (B1, ..., Bn) to minimize the
#'residual sum of squares' between the independent x in the dataset, and the dependent y by
#the linear approximation.
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
plt.xlabel("Engine size")
plt.ylabel("Emission")
plt.show()
#Using sklearn package to model data.
from sklearn import linear_model
regr = linear_model.LinearRegression()
train_x = np.asanyarray(train[['ENGINESIZE']])
train_y = np.asanyarray(train[['CO2EMISSIONS']])
regr.fit (train_x, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)
#Coefficient and Intercept in the simple linear regression, are the parameters of the fit line.
#Given that it is a simple linear regression, with only 2 parameters, and knowing that the
#parameters are the intercept and slope of the line, sklearn can estimate them directly from our
#data
#we can plot the fit line over the data:
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')
plt.xlabel("Engine size")
plt.ylabel("Emission")
#we compare the actual values and predicted values to calculate the accuracy of a regression model.
#Evaluation metrics provide a key role in the development of a model, as it provides insight to
#areas that require improvement.
#There are different model evaluation metrics, lets use MSE here to calculate the accuracy of our
#model based on the test set:
#- Mean absolute error: It is the mean of the absolute value of the errors. This is the easiest of
#the metrics to understand since it’s just average error.
#- Mean Squared Error (MSE): Mean Squared Error (MSE) is the mean of the squared error. It’s more
#popular than Mean absolute error because the focus is geared more towards large errors. This is
#due to the squared term exponentially increasing larger errors in comparison to smaller ones.
#- Root Mean Squared Error (RMSE).
#- R-squared is not error, but is a popular metric for accuracy of your model. It represents how
#close the data are to the fitted regression line. The higher the R-squared, the better the model
#fits your data. Best possible score is 1.0 and it can be negative (because the model can be
#arbitrarily worse).
from sklearn.metrics import r2_score
test_x = np.asanyarray(test[['ENGINESIZE']])
test_y = np.asanyarray(test[['CO2EMISSIONS']])
test_y_ = regr.predict(test_x)
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_ - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_ - test_y) ** 2))
print("R2-score: %.2f" % r2_score(test_y_ , test_y) )