<jupyter_start><jupyter_text>Data Science with Python Module 4 - Model Development   4.1	Simple and Multiple Linear Regression 4.2	Model Evaluation using Visualization 4.3	Polynomial Regression and Pipelines 4.4	Measures for In-Sample Evaluation 4.5	Prediction and Decision Making  4.6	Workshop 4                    4.1 Simple and Multiple Linear Regression     [1/2] Simple Linear Regression (SLR)          [2/2] Multiple Linear Regression (MLR)       4.2 Model Evaluation using Visualization  [1/3] Regression Plothttps://seaborn.pydata.org/generated/seaborn.regplot.html     [2/3] Residual (Error) Plothttps://seaborn.pydata.org/generated/seaborn.residplot.html   Above residual plot with no appearance of any patterns indicates that the model assumptions are satisfied for these data. Above residual plot that has a “fan shape” indicates a heterogeneous variance (non-constant variance). The residuals tend to fan out or fan in as error variance increases or decreases.**What Causes Heteroscedasticity?**https://statisticsbyjim.com/regression/heteroscedasticity-regression/Heteroscedasticity, also spelled heteroskedasticity, occurs more often in datasets that have a large range between the largest and smallest observed values. While there are numerous reasons why heteroscedasticity can exist, a common explanation is that the error variance changes proportionally with a factor. This factor might be a variable in the model.In some cases, the variance increases proportionally with this factor but remains constant as a percentage. For instance, a 10% change in a number such as 100 is much smaller than a 10% change in a large number such as 100,000. In this scenario, you expect to see larger residuals associated with higher values. That’s why you need to be careful when working with wide ranges of values!  Above residual plot that tends to “swoop” indicates that a linear model may not be appropriate. The model may need higher-order terms of x, or a non-linear model may be needed to better describe the relationship between y and x. Transformations on x or y may also be considered.    [3/3] Distribution Plothttps://seaborn.pydata.org/generated/seaborn.distplot.html     4.3 Polynomial Regression and Pipelines [ optinal ]            4.4 Measures for In-Sample Evaluation   [1/2] Mean Squared Error (MSE)      [2/2] R-squared ( $R^2$ )       4.5 Prediction and Decision Making          MSE = 3495  MSE = 3652  $R^2$ = 0.9987  $R^2$ = 0.8051   4.6 Workshop 4 Model DevelopmentWelcome!In this section, we will develop several models that will predict the price of the car using the variables or features. This is just an estimate but should give us an objective idea of how much the car should cost. Some questions we want to ask in this module    Do I know if the dealer is offering fair value for my trade-in?    Do I know if I put a fair value on my car?Data Analytics, we often use Model Development to help us predict future observations from the data we have.A Model will help us understand the exact relationship between different variables and how these variables are used to predict the result. Table of Contents    Simple and Multiple Linear Regression     Model Evaluation using Visualization     Polynomial Regression and Pipelines     Measures for In-Sample Evaluation     Prediction and Decision Making Estimated Time Needed: 120 min  Setup  Import libraries<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>load data and store in dataframe df:<jupyter_code># path of data 
path = 'dataset/auto_EDA.csv'
df = pd.read_csv(path)
df.head()<jupyter_output><empty_output><jupyter_text>1. Simple and Multiple Linear Regression Linear Regression One example of a Data  Model that we will be using isSimple Linear Regression.Simple Linear Regression is a method to help us understand the relationship between two variables:    The predictor/independent variable (X)    The response/dependent variable (that we want to predict)(Y)The result of Linear Regression is a linear function that predicts the response (dependent) variable as a function of the predictor (independent) variable. $$ Y: Response \ Variable\\ X: Predictor \ Variables$$  Linear function:$$Yhat = a + b  X$$     a refers to the intercept of the regression line0, in other words: the value of Y when X is 0    b refers to the slope of the regression line, in other words: the value with which Y changes when X increases by 1 unit Lets load the modules for linear regression<jupyter_code>from sklearn.linear_model import LinearRegression<jupyter_output><empty_output><jupyter_text>Create the linear regression object<jupyter_code>lm = LinearRegression()
lm<jupyter_output><empty_output><jupyter_text>How could Highway-mpg help us predict car price? For this example, we want to look at how highway-mpg can help us predict car price.Using simple linear regression, we will create a linear function with "highway-mpg" as the predictor variable and the "price" as the response variable.<jupyter_code>X = df[['highway-mpg']]
Y = df['price']<jupyter_output><empty_output><jupyter_text>Fit the linear model using highway-mpg.<jupyter_code>lm.fit(X,Y)<jupyter_output><empty_output><jupyter_text>We can output a prediction<jupyter_code>Yhat=lm.predict(X)
Yhat[0:5]<jupyter_output><empty_output><jupyter_text>What is the value of the intercept (a)?<jupyter_code>lm.intercept_<jupyter_output><empty_output><jupyter_text>What is the value of the Slope (b)?<jupyter_code>lm.coef_<jupyter_output><empty_output><jupyter_text>What is the final estimated linear model we get? As we saw above, we should get a final linear model with the structure: $$Yhat = a + b  X$$ Plugging in the actual values we get: price = 38423.31 - 821.73 x  highway-mpg Question 1 a): Create a linear regression object?<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below:lm1 = LinearRegression()lm1 --> Question 1 b): Train the model using 'engine-size' as the independent variable and 'price' as the dependent variable?<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below:lm1.fit(df[['engine-size']], df[['price']])lm1--> Question 1 c):Find the slope and intercept of the model? Slope<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Intercept<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below:Code:Slope print('Slope lm.coef_ is : \n%s' % lm1.coef_)Interceptprint('Intercept lm.intercept_ is : \n%s' % lm1.intercept_)--> Question 1 d): What is the equation of the predicted line. You can use x and yhat or 'engine-size' or 'price'?<jupyter_code># Write you answer in words here
# 
# 
# 
#<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below: Write you answer in words here using X and Y : Yhat=-7963.34 + 166.86*X Price=-7963.34 + 166.86*engine-size--> Multiple Linear Regression What if we want to predict car price using more than one variable?If we want to use more variables in our model to predict car price, we can use Multiple Linear Regression.Multiple Linear Regression is very similar to Simple Linear Regression, but this method is used to explain the relationship between one continuous response (dependent) variable and two or more predictor (independent) variables.Most of the real-world regression models involve multiple predictors. We will illustrate the structure by using four predictor variables, but these results can generalize to any integer: $$Y: Response \ Variable\\X_1 :Predictor\ Variable \ 1\\X_2: Predictor\ Variable \ 2\\X_3: Predictor\ Variable \ 3\\X_4: Predictor\ Variable \ 4\\$$ $$a: intercept\\b_1 :coefficients \ of\ Variable \ 1\\b_2: coefficients \ of\ Variable \ 2\\b_3: coefficients \ of\ Variable \ 3\\b_4: coefficients \ of\ Variable \ 4\\$$ The equation is given by $$Yhat = a + b_1 X_1 + b_2 X_2 + b_3 X_3 + b_4 X_4$$ From the previous section, we have identified influential variables/predictors of price could be:    Curb-weight    Engine-size    Horsepower    Highway-mpg    Width    Length    City-mpg    Wheel-base    Bore    Let's develop a model using these influential ones as the predictor variables.<jupyter_code>Z = df[['curb-weight', 'engine-size', 'horsepower', 'highway-mpg']]<jupyter_output><empty_output><jupyter_text>Fit the linear model using the four above-mentioned variables.<jupyter_code>lm.fit(Z, df['price'])<jupyter_output><empty_output><jupyter_text>Have a glance at $R^2$ to check how good the trained model is:<jupyter_code># R^2
lm.score(Z, df['price'])<jupyter_output><empty_output><jupyter_text>What is the value of the intercept (a)?<jupyter_code>lm.intercept_<jupyter_output><empty_output><jupyter_text>What are the values of the coefficients (b1, b2, b3, b4)?<jupyter_code>lm.coef_<jupyter_output><empty_output><jupyter_text>What is the final estimated linear model that we get? As we saw above, we should get a final linear function with the structure:$$Yhat = a + b_1 X_1 + b_2 X_2 + b_3 X_3 + b_4 X_4$$What is the linear function we get in this example? Price = -15811.863767729246 + 4.70805253 x curb-weight + 81.51280006 x engine-size + 53.53022809 x horsepower + 36.1593925 x highway-mpg  Question  2 a): Create and train a Multiple Linear Regression model "lm2" where the response variable is price, and the predictor variable is 'normalized-losses' and  'highway-mpg'.<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below:lm2 = LinearRegression()lm2.fit(df[['normalized-losses' , 'highway-mpg']],df['price'])--> Question  2 b): Find the coefficient of the model?<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below:lm2.coef_--> 2.  Model Evaluation using Visualization Now that we've developed some models, how do we evaluate our models and how do we choose the best one? One way to do this is by using visualization. import the visualization package: seaborn<jupyter_code># import the visualization package: seaborn
import seaborn as sns
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Regression Plot When it comes to simple linear regression, an excellent way to visualize the fit of our model is by using regression plots.This plot will show a combination of a scattered data points (a scatter plot), as well as the fitted linear regression line going through the data. This will give us a reasonable estimate of the relationship between the two variables, the strength of the correlation, as well as the direction (positive or negative correlation).  Let's visualize Horsepower as potential predictor variable of price:<jupyter_code>width = 12
height = 10
plt.figure(figsize=(width, height))
sns.regplot(x="highway-mpg", y="price", data=df)
plt.ylim(0,)<jupyter_output><empty_output><jupyter_text>We can see from this plot that price is negatively correlated to highway-mpg, since the regression slope is negative.One thing to keep in mind when looking at a regression plot is to pay attention to how scattered the data points are around the regression line. This will give you a good indication of the variance of the data, and whether a linear model would be the best fit or not. If the data is too far off from the line, this linear model might not be the best model for this data. Let's compare this plot to the regression plot of "peak-rpm".<jupyter_code>plt.figure(figsize=(width, height))
sns.regplot(x="peak-rpm", y="price", data=df)
plt.ylim(0,)<jupyter_output><empty_output><jupyter_text>Comparing the regression plot of "peak-rpm" and "highway-mpg" we see that the points for "highway-mpg" are much closer to the generated line and on the average decrease. The points for "peak-rpm" have more spread around the predicted line, and it is much harder to determine if the points are decreasing or increasing as the "highway-mpg" increases. Question 3:Given the regression plots above is "peak-rpm" or "highway-mpg" more strongly correlated with "price". Use the method  ".corr()" to verify your answer.<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below:The variable "highway-mpg" has a stronger linear correlation with "price", it is approximate: -0.704692  compared to   "peak-rpm" which is approximate: -0.101616. You can verify it using the following command/code:df[["peak-rpm","highway-mpg","price"]].corr()--> Residual PlotA good way to visualize the variance of the data is to use a residual plot.What is a residual?The difference between the observed car price/value (y) and the predicted car price/value (Yhat) is called the residual (e). When we look at a regression plot, the residual is the distance from the data point to the fitted regression line.So what is a residual plot?A residual plot is a graph that shows the residuals on the vertical y-axis and the independent variable on the horizontal x-axis.What do we pay attention to when looking at a residual plot?We look at the spread of the residuals:- If the points in a residual plot are randomly spread out around the x-axis, then a linear model is appropriate for the data. Why is that? Randomly spread out residuals means that the variance is constant, and thus the linear model is a good fit for this data.<jupyter_code>width = 14
height = 8
plt.figure(figsize=(width, height))
sns.residplot(df['highway-mpg'], df['price']).tick_params(labelsize=14)
plt.show()<jupyter_output><empty_output><jupyter_text>What is this plot telling us?We can see from this residual plot that the residuals are not randomly spread around the x-axis, which leads us to believe that maybe a non-linear model is more appropriate for this data. Multiple Linear Regression How do we visualize a model for Multiple Linear Regression? This gets a bit more complicated because you can't visualize it with regression or residual plot.One way to look at the fit of the model is by looking at the distribution plot: We can look at the distribution of the fitted values that result from the model and compare it to the distribution of the actual values. First lets make a prediction<jupyter_code>Y_hat = lm.predict(Z)
plt.figure(figsize=(width, height))


ax1 = sns.distplot(df['price'], hist=False, color="r", label="Actual Value")
sns.distplot(Yhat, hist=False, color="b", label="Fitted Values" , ax=ax1)


plt.title('Actual vs Fitted Values for Price')
plt.xlabel('Price (in dollars)')
plt.ylabel('Proportion of Cars')

plt.show()
plt.close()<jupyter_output><empty_output><jupyter_text>We can see that the fitted values are reasonably close to the actual values, since the two distributions overlap a bit. However, there is definitely some room for improvement. 3. Polynomial Regression and Pipelines Polynomial regression is a particular case of the general linear regression model or multiple linear regression models. We get non-linear relationships by squaring or setting higher-order terms of the predictor variables.There are different orders of polynomial regression: Quadratic - 2nd order$$Yhat = a + b_1 X^2 +b_2 X^2 $$Cubic - 3rd order$$Yhat = a + b_1 X^2 +b_2 X^2 +b_3 X^3\\$$Higher order:$$Y = a + b_1 X^2 +b_2 X^2 +b_3 X^3 ....\\$$ We saw earlier that a linear model did not provide the best fit while using highway-mpg as the predictor variable. Let's see if we can try fitting a polynomial model to the data instead. We will use the following function to plot the data:<jupyter_code>def PlotPolly(model, independent_variable, dependent_variabble, Name):
    x_new = np.linspace(15, 55, 100)
    y_new = model(x_new)

    plt.plot(independent_variable, dependent_variabble, '.', x_new, y_new, '-')
    plt.title('Polynomial Fit with Matplotlib for Price ~ Length')
    ax = plt.gca()
    ax.set_facecolor((0.9, 0.9, 0.9)) # set plot background color to grey
    fig = plt.gcf()
    plt.xlabel(Name)
    plt.ylabel('Price of Cars')

    plt.show()
    plt.close()<jupyter_output><empty_output><jupyter_text>lets get the variables<jupyter_code>x = df['highway-mpg']
y = df['price']<jupyter_output><empty_output><jupyter_text>Let's fit the polynomial using the function polyfit, then use the function poly1d to display the polynomial function. **[1/2] Here we use a polynomial of the 2nd order (quadratic) **<jupyter_code># Here we use a polynomial of the 2nd order (quadratic) 
f = np.polyfit(x, y, 2)
p = np.poly1d(f)
print(p)<jupyter_output>2
45.35 x - 3773 x + 8.419e+04<jupyter_text>Let's plot the function<jupyter_code>PlotPolly(p, x, y, 'highway-mpg')
np.polyfit(x, y, 2)<jupyter_output><empty_output><jupyter_text>**[2/2] Here we use a polynomial of the 3rd order (cubic)**<jupyter_code># Here we use a polynomial of the 3rd order (cubic) 
f = np.polyfit(x, y, 3)
p = np.poly1d(f)
print(p)<jupyter_output>3         2
-1.557 x + 204.8 x - 8965 x + 1.379e+05<jupyter_text>Let's plot the function<jupyter_code>PlotPolly(p, x, y, 'highway-mpg')
np.polyfit(x, y, 3)<jupyter_output><empty_output><jupyter_text>We can already see from plotting that this polynomial model performs better than the linear model. This is because the generated polynomial function  "hits" more of the data points. Question  4:Create 11 order polynomial model with the variables x and y from above?<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below:Calculate polynomialHere we use a polynomial of the 11rd order (cubic) f1 = np.polyfit(x, y, 11)p1 = np.poly1d(f1)print(p)PlotPolly(p1,x,y, 'Highway MPG')--> The analytical expression for Multivariate Polynomial function gets complicated. For example, the expression for a second-order (degree=2)polynomial with two variables is given by: $$Yhat = a + b_1 X_1 +b_2 X_2 +b_3 X_1 X_2+b_4 X_1^2+b_5 X_2^2$$ We can perform a polynomial transform on multiple features. First, we import the module:<jupyter_code>from sklearn.preprocessing import PolynomialFeatures<jupyter_output><empty_output><jupyter_text>We create a PolynomialFeatures object of degree 2:<jupyter_code>pr=PolynomialFeatures(degree=2)
pr
Z.head()
Z_pr=pr.fit_transform(Z)<jupyter_output><empty_output><jupyter_text>The original data is of 201 samples and 4 features<jupyter_code>Z.shape<jupyter_output><empty_output><jupyter_text>after the transformation, there 201 samples and 15 features<jupyter_code>Z_pr.shape<jupyter_output><empty_output><jupyter_text>Pipeline Data Pipelines simplify the steps of processing the data. We use the module Pipeline to create a pipeline. We also use StandardScaler as a step in our pipeline.<jupyter_code>from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler<jupyter_output><empty_output><jupyter_text>We create the pipeline, by creating a list of tuples including the name of the model or estimator and its corresponding constructor.<jupyter_code>Input=[('scale',StandardScaler()), 
       ('polynomial', PolynomialFeatures(degree=2)), 
       ('model', LinearRegression())
      ]<jupyter_output><empty_output><jupyter_text>we input the list as an argument to the pipeline constructor<jupyter_code>pipe=Pipeline(Input)
pipe<jupyter_output><empty_output><jupyter_text>We can normalize the data,  perform a transform and fit the model simultaneously.<jupyter_code>pipe.fit(Z, y)<jupyter_output><empty_output><jupyter_text>Similarly,  we can normalize the data, perform a transform and produce a prediction  simultaneously<jupyter_code>ypipe=pipe.predict(Z)
ypipe[0:4]<jupyter_output><empty_output><jupyter_text>Question 5:Create a pipeline that Standardizes the data, then perform prediction using a linear regression model using the features Z and targets y<jupyter_code># Write your code below and press Shift+Enter to execute<jupyter_output><empty_output><jupyter_text>Double-click here for the solution.<!-- The answer is below:Code:Input=[('scale', StandardScaler()),        ('model', LinearRegression())      ]pipe=Pipeline(Input)pipe.fit(Z, y)ypipe=pipe.predict(Z)ypipe[0:10]--> 4. Measures for In-Sample Evaluation When evaluating our models, not only do we want to visualize the results, but we also want a quantitative measure to determine how accurate the model is.Two very important measures that are often used in Statistics to determine the accuracy of a model are:    R^2 / R-squared    Mean Squared Error (MSE)    R-squaredR squared, also known as the coefficient of determination, is a measure to indicate how close the data is to the fitted regression line.    The value of the R-squared is the percentage of variation of the response variable (y) that is explained by a linear model.Mean Squared Error (MSE)The Mean Squared Error measures the average of the squares of errors, that is, the difference between actual value (y) and the estimated value (ŷ). Model 1: Simple Linear Regression Let's calculate the R^2<jupyter_code>#highway_mpg_fit
lm.fit(X, Y)
# Find the R^2
print('[SLR] The R-square is: ', lm.score(X, Y))<jupyter_output>[SLR] The R-square is:  0.496591188434<jupyter_text>We can say that ~ 49.66% of the variation of the price is explained by this simple linear model "horsepower_fit". Let's calculate the MSE We can predict the output i.e., "yhat" using the predict method, where X is the input variable:<jupyter_code>Yhat=lm.predict(X)
print('[SLR] The output of the first four predicted value is: ', Yhat[0:4])<jupyter_output>[SLR] The output of the first four predicted value is:  [ 16236.50464347  16236.50464347  17058.23802179  13771.3045085 ]<jupyter_text>lets import the function mean_squared_error from the module metrics<jupyter_code>from sklearn.metrics import mean_squared_error<jupyter_output><empty_output><jupyter_text>we compare the predicted results with the actual results<jupyter_code>mse = mean_squared_error(df['price'], Yhat)
print('[SLR] The mean square error (MSE) of price and predicted value is : %.2f ($^2)' % mse)
# root mean square error (RMSE) in $ unit
rmse = np.sqrt(mse)
print('[SLR] The root mean square error (RMSE) of price and predicted value is : %.2f ($)' % rmse)<jupyter_output>[SLR] The root mean square error (RMSE) of price and predicted value is : 5624.50 ($)<jupyter_text>Model 2: Multiple Linear Regression Let's calculate the $R^2$<jupyter_code># fit the model 
lm.fit(Z, df['price'])
# Find the R^2
print('[MLR] The R-square is: ', lm.score(Z, df['price']))<jupyter_output>[MLR] The R-square is:  0.809373252218<jupyter_text>We can say that ~ 80.94 % of the variation of price is explained by this multiple linear regression model. Let's calculate the MSE  we produce a prediction<jupyter_code>Y_predict_multifit = lm.predict(Z)<jupyter_output><empty_output><jupyter_text>we compare the predicted results with the actual results<jupyter_code>mse = mean_squared_error(df['price'], Y_predict_multifit)
print('[MLR] The mean square error (MSE) of price and predicted value is : %.2f ($^2)' % mse)
# root mean square error (RMSE) in $ unit
rmse = np.sqrt(mse)
print('[MLR] The root mean square error (RMSE) of price and predicted value is : %.2f ($)' % rmse)<jupyter_output>[MLR] The root mean square error (RMSE) of price and predicted value is : 3461.11 ($)<jupyter_text>Model 3: Polynomial Regression Let's calculate the $R^2$ let’s import the function r2_score from the module metrics as we are using a different function<jupyter_code>from sklearn.metrics import r2_score<jupyter_output><empty_output><jupyter_text>We apply the function to get the value of $R^2$<jupyter_code>r_squared = r2_score(y, p(x))
print('[PLR] The R-square value is: ', r_squared)<jupyter_output>[PLR] The R-square value is:  0.674194666391<jupyter_text>We can say that ~ 67.42 % of the variation of price is explained by this polynomial fit We can also calculate the MSE & RMSE:<jupyter_code>mse = mean_squared_error(df['price'], p(x))
print('[PLR] The mean square error (MSE) of price and predicted value is : %.2f ($^2)' % mse)
# root mean square error (RMSE) in $ unit
rmse = np.sqrt(mse)
print('[PLR] The root mean square error (RMSE) of price and predicted value is : %.2f ($)' % rmse)<jupyter_output>[PLR] The root mean square error (RMSE) of price and predicted value is : 4524.84 ($)<jupyter_text>5. Prediction and Decision MakingPredictionIn the previous section, we trained the model using the method fit. Now we will use the method predict to produce a prediction. Lets import pyplot for plotting; we will also be using some functions from numpy.<jupyter_code>import matplotlib.pyplot as plt
import numpy as np

%matplotlib inline<jupyter_output><empty_output><jupyter_text>Create a new input<jupyter_code>new_input=np.arange(1, 100, 1).reshape(-1, 1)<jupyter_output><empty_output><jupyter_text>Fit the model<jupyter_code>lm.fit(X, Y)
lm<jupyter_output><empty_output><jupyter_text>Produce a prediction<jupyter_code>yhat=lm.predict(new_input)
yhat[0:5]<jupyter_output><empty_output><jupyter_text>we can plot the data<jupyter_code>plt.figure(figsize=(10, 6))
plt.plot(new_input, yhat)
plt.title('Regression Predictive Model')
plt.xlabel('Highway MPG')
plt.ylabel('Car Price ($)')
plt.tick_params(labelsize=14)
plt.show()<jupyter_output><empty_output><jupyter_text>Decision Making: Determining a Good Model Fit Now that we have visualized the different models, and generated the R-squared and MSE values for the fits, how do we determine a good model fit?    What is a good R-squared value?When comparing models, the model with the higher R-squared value is a better fit for the data.    What is a good MSE?When comparing models, the model with the smallest MSE value is a better fit for the data.Let's take a look at the values for the different models.Simple Linear Regression: Using Highway-mpg as a Predictor Variable of Price.    R-squared: 0.4966    MSE: 3.16 x10^7    Multiple Linear Regression: Using Curb-weight, Engine-size, Horsepower, and Highway-mpg as Predictor Variables of Price.    R-squared: 0.8094    MSE: 1.2 x10^7    Polynomial Regression: Using Highway-mpg as a Predictor Variable of Price.    R-squared: 0.6742    MSE: 2.05 x 10^7 Simple Linear Regression Model (SLR) vs Multiple Linear Regression Model (MLR) Usually, the more variables you have, the better your model is at predicting, but this is not always true. Sometimes you may not have enough data, you may run into numerical problems, or many of the variables may not be useful and or even act as noise. As a result, you should always check the MSE and R^2.So to be able to compare the results of the MLR vs SLR models, we look at a combination of both the R-squared and MSE to make the best conclusion about the fit of the model.    MSEThe MSE of SLR is  3.16x10^7  while MLR has an MSE of 1.2 x10^7.  The MSE of MLR is much smaller.    R-squared: In this case, we can also see that there is a big difference between the R-squared of the SLR and the R-squared of the MLR. The R-squared for the SLR (~0.497) is very small compared to the R-squared for the MLR (~0.809).This R-squared in combination with the MSE show that MLR seems like the better model fit in this case, compared to SLR. Simple Linear Model (SLR) vs Polynomial Regression Model (PLR)     MSE: We can see that Polynomial model brought down the MSE, since this MSE is smaller than the one from the SLR.     R-squared: The R-squared for the Polyfit is larger than the R-squared for the SLR, so the Polynomial regression also brought up the R-squared quite a bit.Since the Polynomial model resulted in a lower MSE and a higher R-squared, we can conclude that this was a better fit model than the simple linear regression for predicting Price with Highway-mpg as a predictor variable. Multiple Linear Regression (MLR) vs Polynomial Regression Model (PLR)     MSE: The MSE for the MLR is smaller than the MSE for the Polynomial model.    R-squared: The R-squared for the MLR is also much larger than for the Polynomial model. Conclusion: Comparing these three models, we conclude that the MLR model is the best model to be able to predict price from our dataset. This result makes sense, since we have about 30 variables in total, and we know that more than one of those variables are potential predictors of the final car price.<jupyter_code>print(' Number of variables including target Price : %s' % len(df.columns))
df.tail()<jupyter_output>Number of variables including target Price : 32
{'fraction_non_alphanumeric': 0.08110070176651571, 'fraction_numerical': 0.02067272790126871, 'mean_word_length': 5.173282116944089, 'pattern_counts': {'":': 0, '<': 240, '<?xml version=': 0, '>': 240, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '60', 'dir': 'jupyter-structured-clean-dedup', 'id': '630557', 'license': 'CNRI-Python', 'n_tokens_mistral': 9186, 'n_tokens_neox': 8511, 'n_words': 3636, 'path': 'Module 4 Model Development.ipynb', 'repo_name': 'dd-consulting/DDC-Data-Science-Python', 'size': '28927'}