-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolyreg.py
64 lines (48 loc) · 1.93 KB
/
polyreg.py
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
# -*- coding: utf-8 -*-
"""PolyReg.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/13CkobJpabwBk1hNDR3wlik8S9NEWOLI2
"""
# Commented out IPython magic to ensure Python compatibility.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import pylab as pl
# %matplotlib inline
!wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv
df = pd.read_csv("FuelConsumption.csv")
df.head()
regrdata = df[['ENGINESIZE', 'CYLINDERS', 'FUELCONSUMPTION_COMB', 'CO2EMISSIONS']]
regrdata.head(9)
plt.scatter(regrdata.ENGINESIZE, regrdata.CO2EMISSIONS, color = 'blue')
plt.xlabel = "Engine size"
plt.ylabel = 'Emissions'
plt.show()
tra = np.random.rand(len(df)) < 0.8
train = regrdata[tra]
test = regrdata[~tra]
test.head()
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
train_x = np.asanyarray(train[['ENGINESIZE']])
train_y = np.asanyarray(train[['CO2EMISSIONS']])
test_x = np.asanyarray(test[['ENGINESIZE']])
test_y = np.asanyarray(test[['CO2EMISSIONS']])
polyreg = PolynomialFeatures(degree=3)
trainxpol = polyreg.fit_transform(train_x)
trainxpol
lin = linear_model.LinearRegression()
train_y_ = lin.fit(trainxpol, train_y)
print('Coefficients:', lin.coef_)
print("Intercepts", lin.intercept_)
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
XX = np.arange(0.0, 10.0, 0.1)
yy = lin.intercept_[0]+ lin.coef_[0][1]*XX+ lin.coef_[0][2]*np.power(XX, 2) + lin.coef_[0][3]*np.power(XX,3)
plt.plot(XX, yy, )
from sklearn.metrics import r2_score
test_x_poly = polyreg.fit_transform(test_x)
test_y_ = lin.predict(test_x_poly)
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) )