02-Linear Regression Project - Solutions
02-Linear Regression Project - Solutions
0.1 Imports
** Import pandas, numpy, matplotlib,and seaborn. Then set %matplotlib inline (You’ll import
sklearn as you need it.)**
Check the head of customers, and check out its info() and describe() methods.
[3]: customers.head()
[3]: Email \
0 [email protected]
1 [email protected]
1
2 [email protected]
3 [email protected]
4 [email protected]
Address Avatar \
0 835 Frank Tunnel\nWrightmouth, MI 82180-9605 Violet
1 4547 Archer Common\nDiazchester, CA 06566-8576 DarkGreen
2 24645 Valerie Unions Suite 582\nCobbborough, D… Bisque
3 1414 David Throughway\nPort Jason, OH 22070-1220 SaddleBrown
4 14023 Rodriguez Passage\nPort Jacobville, PR 3… MediumAquaMarine
[4]: customers.describe()
2
[5]: customers.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 500 entries, 0 to 499
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Email 500 non-null object
1 Address 500 non-null object
2 Avatar 500 non-null object
3 Avg. Session Length 500 non-null float64
4 Time on App 500 non-null float64
5 Time on Website 500 non-null float64
6 Length of Membership 500 non-null float64
7 Yearly Amount Spent 500 non-null float64
dtypes: float64(5), object(3)
memory usage: 31.4+ KB
3
** Do the same but with the Time on App column instead. **
[8]: sns.jointplot(x='Time on App',y='Yearly Amount Spent',data=customers)
4
** Use jointplot to create a 2D hex bin plot comparing Time on App and Length of Membership.**
[9]: sns.jointplot(x='Time on App',y='Length of␣
↪Membership',kind='hex',data=customers)
5
Let’s explore these types of relationships across the entire data set. Use pairplot to
recreate the plot below.(Don’t worry about the the colors)
[10]: sns.pairplot(customers)
6
Based off this plot what looks to be the most correlated feature with Yearly Amount
Spent?
[11]: # Length of Membership
Create a linear model plot (using seaborn’s lmplot) of Yearly Amount Spent vs. Length
of Membership.
[12]: sns.lmplot(x='Length of Membership',y='Yearly Amount Spent',data=customers)
7
0.4 Training and Testing Data
Now that we’ve explored the data a bit, let’s go ahead and split the data into training and testing
sets. ** Set a variable X equal to the numerical features of the customers and a variable y equal
to the “Yearly Amount Spent” column. **
[13]: y = customers['Yearly Amount Spent']
** Use model_selection.train_test_split from sklearn to split the data into training and testing
sets. Set test_size=0.3 and random_state=101**
[15]: from sklearn.model_selection import train_test_split
8
0.5 Training the Model
Now its time to train our model on our training data!
** Import LinearRegression from sklearn.linear_model **
[17]: from sklearn.linear_model import LinearRegression
[18]: lm = LinearRegression()
[19]: lm.fit(X_train,y_train)
[19]: LinearRegression()
Coefficients:
[25.98154972 38.59015875 0.19040528 61.27909654]
** Create a scatterplot of the real test values versus the predicted values. **
[22]: plt.scatter(y_test,predictions)
plt.xlabel('Y Test')
plt.ylabel('Predicted Y')
9
0.7 Evaluating the Model
Let’s evaluate our model performance by calculating the residual sum of squares and the explained
variance score (R^2).
** Calculate the Mean Absolute Error, Mean Squared Error, and the Root Mean Squared Error.
Refer to the lecture or to Wikipedia for the formulas**
[23]: # calculate these metrics by hand!
from sklearn import metrics
MAE: 7.228148653430853
MSE: 79.81305165097487
RMSE: 8.933815066978656
0.8 Residuals
You should have gotten a very good model with a good fit. Let’s quickly explore the residuals to
make sure everything was okay with our data.
Plot a histogram of the residuals and make sure it looks normally distributed. Use
either seaborn distplot, or just plt.hist().
10
[24]: sns.distplot((y_test-predictions),bins=50);
0.9 Conclusion
We still want to figure out the answer to the original question, do we focus our efforst on mobile
app or website development? Or maybe that doesn’t even really matter, and Membership Time is
what is really important. Let’s see if we can interpret the coefficients at all to get an idea.
** Recreate the dataframe below. **
[25]: coeffecients = pd.DataFrame(lm.coef_,X.columns)
coeffecients.columns = ['Coeffecient']
coeffecients
[25]: Coeffecient
Avg. Session Length 25.981550
Time on App 38.590159
Time on Website 0.190405
Length of Membership 61.279097
11
• Holding all other features fixed, a 1 unit increase in Time on App is associated with an
increase of 38.59 total dollars spent.
• Holding all other features fixed, a 1 unit increase in Time on Website is associated with an
increase of 0.19 total dollars spent.
• Holding all other features fixed, a 1 unit increase in Length of Membership is associated
with an increase of 61.27 total dollars spent.
Do you think the company should focus more on their mobile app or on their website?
This is tricky, there are two ways to think about this: Develop the Website to catch up to the
performance of the mobile app, or develop the app more since that is what is working better. This
sort of answer really depends on the other factors going on at the company, you would probably
want to explore the relationship between Length of Membership and the App or the Website before
coming to a conclusion!
12