<jupyter_start><jupyter_text>Simple Linear Regression Importing needed packages<jupyter_code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pylab as pl
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Downloading the data To download the data, we use !Wget to download from IBM object storage<jupyter_code>!wget -O FuelConsumption.csv https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv<jupyter_output>--2021-03-10 11:27:03--  https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%202/data/FuelConsumptionCo2.csv
Resolving cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)... 192.168.3.11
Connecting to cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud (cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud)|192.168.3.11|: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.07s   

2021-03-10 11:27:03 (951 KB/s) - ‘FuelConsumption.csv’ saved [72629/72629]<jupyter_text>Understanding the data FuelConsumption.csv MODELYEAR eg.2014  MAKE e.g. Acura MODEL e.g. ILX VEHICLE CLASS e.g.SUV ENGINE SIZE e.g.4.7 CYLINDERS e.g.6 TRANSMISSION e.g.A6 FUEL CONSUMPTION IN CITY(L/100 KM) e.g. 9.9 FUEL CONSUMPTION IN HWY(L/100KM) e.g.8.9 FUEL CONSUMPTION IN COMB(L/100KM) e.g.9.2 CO2 EMISSIONS(g/KM) e.g. 182-->LOW-->0 Reading the data in<jupyter_code>df = pd.read_csv("FuelConsumption.csv")

# take a look at the dataset

df.head()<jupyter_output><empty_output><jupyter_text>Data Exploration Lets first have a descriptive exploration on our data<jupyter_code># Summarize the data
df.describe()<jupyter_output><empty_output><jupyter_text>Let us select some features to explore more<jupyter_code>cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]
cdf.head(9)<jupyter_output><empty_output><jupyter_text>We can plot each of these features<jupyter_code>viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']]
viz.hist()
plt.show()<jupyter_output><empty_output><jupyter_text>Now,lets plot each of these features vs the emissions to see how linear is their relation<jupyter_code>plt.scatter(cdf.FUELCONSUMPTION_COMB,cdf.CO2EMISSIONS,color = "blue")
plt.xlabel("FuelConsumption")
plt.ylabel("Co2Emissions")
plt.show()
plt.scatter(cdf.ENGINESIZE,cdf.CO2EMISSIONS,color = "red")
plt.xlabel("Engine Size")
plt.ylabel("CO2 Emissions")
plt.show()
plt.scatter(cdf.CYLINDERS,cdf.CO2EMISSIONS,color = "green")
plt.xlabel("Engine Size")
plt.ylabel("Cylinders")
plt.show()<jupyter_output><empty_output><jupyter_text>Creating train and test data sets 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 more accurate evaluation on or out of sample accuracy because the testing data set is not partof the dataset that is used to train the data.It is more realistic for real world problems. This means that we know the outcome of the each data point in the data set,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. Lets split our data set into train and test sets,80% of the entire data for training and 20% for testing.We create a mask to select random rows usingnp.random.rand() function<jupyter_code>msk =np.random.rand(len(df)) < 0.8
msk
train = cdf[msk]

train.shape
test = cdf[~msk]
test.shape<jupyter_output><empty_output><jupyter_text>Simple Regression Model Linear Regression fits linear model with coefficients B = (B1,B2,...Bn) to minimize the 'residual sum of squares' between the actual value y in the dataset and predicted value y that using linear approximation. Train data distribution<jupyter_code>plt.scatter(train.ENGINESIZE,train.CO2EMISSIONS,color = 'green')
plt.xlabel("Engine Size")
plt.ylabel("CO2 emissions")
plt.show()<jupyter_output><empty_output><jupyter_text>Modeling Use Sklearn package to model data<jupyter_code>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("The coefficents:",regr.coef_)
print("The intercept:",regr.intercept_)<jupyter_output>The coefficents: [[39.45328958]]
The intercept: [124.64396906]<jupyter_text>As mentioned before,Coefficient and Intercept in the simple linear regression are the parameters of the fitline.Given that it is a simple linear regression,with only 2 parameters,and knowing that parameters are the intercept and slope of the line.sklearn can estimate them directly from our data.Notice that all of the data must be available to traverse and calculate the parameters. Plot outputs We can plot the fitline over the data<jupyter_code>plt.scatter(train.ENGINESIZE,train.CO2EMISSIONS,color = 'green')
plt.plot(train_x,regr.coef_[0][0] * train_x + regr.intercept_[0],'-r')
plt.xlabel("Engine Size")
plt.ylabel("CO2 Emissions")
plt.show()<jupyter_output><empty_output><jupyter_text>Evaluation We compare actual values and predicted values to caculate the accuracy of a regression model.Evaluation metrics provide a key role in the development of a modelas it provides insight to areas that require improvement. There are different model evaluation metrics,let us use MSE here to caculate the accuracy of the model basedon 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 is 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 large errors in comparision to smaller errors.- Root Mean Squared Error(RMSE)- R-Squared is not an Error,but is a popular metric for accuaracy of your model.It represents how close the data are to the fitted regression line.The higher theR-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)<jupyter_code>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: %.2f"%np.mean((test_y_ - test_y) ** 2))
print("R2-score : %.2f" %r2_score(test_y_,test_y) )<jupyter_output>Mean absolute error: 24.09
Residual sum of squares: 1032.06
R2-score : 0.64
StarcoderdataJupyterStructuredCleanDedup