import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np %matplotlib inline
!wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv
--2019-04-15 12:06:39-- https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 126.96.36.199 Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)|188.8.131.52|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 72629 (71K) [text/csv] Saving to: ‘FuelConsumption.csv’ FuelConsumption.csv 100%[=====================>] 70.93K --.-KB/s in 0.04s 2019-04-15 12:06:40 (1.62 MB/s) - ‘FuelConsumption.csv’ saved [72629/72629]
Did you know? When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: Sign up now for free
We have downloaded a fuel consumption dataset,
FuelConsumption.csv, which contains model-specific fuel consumption ratings and estimated carbon dioxide emissions for new light-duty vehicles for retail sale in Canada. Dataset source
df = pd.read_csv("FuelConsumption.csv") # take a look at the dataset df.head()
|3||2014||ACURA||MDX 4WD||SUV - SMALL||3.5||6||AS6||Z||12.7||9.1||11.1||25||255|
|4||2014||ACURA||RDX AWD||SUV - SMALL||3.5||6||AS6||Z||12.1||8.7||10.6||27||244|
Lets select some features that we want to use for regression.
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']] cdf.head(9)
Lets plot Emission values with respect to Engine size:
plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue') plt.xlabel("Engine size") plt.ylabel("Emission") plt.show()
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.
msk = np.random.rand(len(df)) < 0.8 train = cdf[msk] test = cdf[~msk]
Sometimes, the trend of data is not really linear, and looks curvy. In this case we can use Polynomial regression methods. In fact, many different regressions exist that can be used to fit whatever the dataset looks like, such as quadratic, cubic, and so on, and it can go on and on to infinite degrees.
In essence, we can call all of these, polynomial regression, where the relationship between the independent variable x and the dependent variable y is modeled as an nth degree polynomial in x. Lets say you want to have a polynomial regression (let's make 2 degree polynomial):
Now, the question is: how we can fit our data on this equation while we have only x values, such as Engine Size? Well, we can create a few additional features: 1, , and .
PloynomialFeatures() function in Scikit-learn library, drives a new feature sets from the original feature set. That is, a matrix will be generated consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. For example, lets say the original feature set has only one feature, ENGINESIZE. Now, if we select the degree of the polynomial to be 2, then it generates 3 features, degree=0, degree=1 and degree=2:
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']]) poly = PolynomialFeatures(degree=2) train_x_poly = poly.fit_transform(train_x) train_x_poly
array([[ 1. , 2. , 4. ], [ 1. , 2.4 , 5.76], [ 1. , 1.5 , 2.25], ..., [ 1. , 3.2 , 10.24], [ 1. , 3. , 9. ], [ 1. , 3.2 , 10.24]])
fit_transform takes our x values, and output a list of our data raised from power of 0 to power of 2 (since we set the degree of our polynomial to 2).
in our example
It looks like feature sets for multiple linear regression analysis, right? Yes. It Does. Indeed, Polynomial regression is a special case of linear regression, with the main idea of how do you select your features. Just consider replacing the with , with , and so on. Then the degree 2 equation would be turn into:
Now, we can deal with it as 'linear regression' problem. Therefore, this polynomial regression is considered to be a special case of traditional multiple linear regression. So, you can use the same mechanism as linear regression to solve such a problems.
so we can use LinearRegression() function to solve it:
clf = linear_model.LinearRegression() train_y_ = clf.fit(train_x_poly, train_y) # The coefficients print ('Coefficients: ', clf.coef_) print ('Intercept: ',clf.intercept_)
Coefficients: [[ 0. 49.37812843 -1.34299862]] Intercept: [109.5652137]
As mentioned before, Coefficient and Intercept , are the parameters of the fit curvy line. Given that it is a typical multiple linear regression, with 3 parameters, and knowing that the parameters are the intercept and coefficients of hyperplane, sklearn has estimated them from our new set of feature sets. Lets plot it:
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue') XX = np.arange(0.0, 10.0, 0.1) yy = clf.intercept_+ clf.coef_*XX+ clf.coef_*np.power(XX, 2) plt.plot(XX, yy, '-r' ) plt.xlabel("Engine size") plt.ylabel("Emission")
Text(0, 0.5, 'Emission')
from sklearn.metrics import r2_score test_x_poly = poly.fit_transform(test_x) test_y_ = clf.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) )
Mean absolute error: 24.07 Residual sum of squares (MSE): 1019.92 R2-score: 0.66
# write your code here poly3 = PolynomialFeatures(degree=3) train_x_poly3 = poly3.fit_transform(train_x) clf3 = linear_model.LinearRegression() train_y3_ = clf3.fit(train_x_poly3, train_y) # The coefficients print ('Coefficients: ', clf3.coef_) print ('Intercept: ',clf3.intercept_) plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue') XX = np.arange(0.0, 10.0, 0.1) yy = clf3.intercept_+ clf3.coef_*XX + clf3.coef_*np.power(XX, 2) + clf3.coef_*np.power(XX, 3) plt.plot(XX, yy, '-r' ) plt.xlabel("Engine size") plt.ylabel("Emission") test_x_poly3 = poly3.fit_transform(test_x) test_y3_ = clf3.predict(test_x_poly3) print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y3_ - test_y))) print("Residual sum of squares (MSE): %.2f" % np.mean((test_y3_ - test_y) ** 2)) print("R2-score: %.2f" % r2_score(test_y3_ , test_y) )
Coefficients: [[ 0. 25.66407454 5.16037412 -0.53593094]] Intercept: [134.80264424] Mean absolute error: 24.18 Residual sum of squares (MSE): 1022.70 R2-score: 0.67
Double-click here for the solution.
IBM SPSS Modeler is a comprehensive analytics platform that has many machine learning algorithms. It has been designed to bring predictive intelligence to decisions made by individuals, by groups, by systems – by your enterprise as a whole. A free trial is available through this course, available here: SPSS Modeler
Also, you can use Watson Studio to run these notebooks faster with bigger datasets. Watson Studio is IBM's leading cloud solution for data scientists, built by data scientists. With Jupyter notebooks, RStudio, Apache Spark and popular libraries pre-packaged in the cloud, Watson Studio enables data scientists to collaborate on their projects without having to install anything. Join the fast-growing community of Watson Studio users today with a free account at Watson Studio
Saeed Aghabozorgi, PhD is a Data Scientist in IBM with a track record of developing enterprise level applications that substantially increases clients’ ability to turn data into actionable knowledge. He is a researcher in data mining field and expert in developing advanced analytic methods like machine learning and statistical modelling on large datasets.