Module 10 · Machine learning: linear regression · Lesson 46 of 66

Project: app or website?

An online clothing store wants to know where to invest. Let linear regression decide.

In this lesson · about 30 minutes

  • Explore a data set with joint plots and pair plots
  • Train, test and evaluate a regression model
  • Turn coefficients into a business recommendation

An online clothing store sells through a mobile app and a website. Customers also come in for style sessions. The company wants to know: should it put its effort into the app or the website?

The (made-up) data has one row per customer: email, address, avatar color, and these numbers:

  • Avg. Session Length: average minutes per in-store style session
  • Time on App and Time on Website: average minutes spent
  • Length of Membership: years as a member
  • Yearly Amount Spent: dollars per year, what we'll predict

Exercise

1. Website time and spending

Make a joint plot of Time on Website (x) against Yearly Amount Spent (y). Is there a pattern?

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
customers = pd.read_csv('Ecommerce_Customers.csv')

Compare with the app

Now the same with Time on App. Notice the clearer upward trend.

Exercise

2. App time and membership

Make a hexagon joint plot of Time on App (x) against Length of Membership (y).

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
customers = pd.read_csv('Ecommerce_Customers.csv')

Every pair at once

Which feature looks most related to Yearly Amount Spent? Look along the bottom row.

Exercise

3. The strongest link

The pair plot suggests Length of Membership matters most. Draw a linear model plot of Yearly Amount Spent (y) against Length of Membership (x).

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
customers = pd.read_csv('Ecommerce_Customers.csv')

Exercise

4. Training and test data

Set X to the four number columns ('Avg. Session Length', 'Time on App', 'Time on Website', 'Length of Membership') and y to 'Yearly Amount Spent'. Split them with test_size=0.3 and random_state=101.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
customers = pd.read_csv('Ecommerce_Customers.csv')

Exercise

5. Train and predict

Create a LinearRegression called lm, fit it to the training data, and save its predictions for X_test as predictions. Then show lm.coef_.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
customers = pd.read_csv('Ecommerce_Customers.csv')
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
X = customers[['Avg. Session Length', 'Time on App', 'Time on Website', 'Length of Membership']]
y = customers['Yearly Amount Spent']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)

Exercise

6. How good is it?

Draw a scatter plot of y_test (x) against predictions (y), labeled 'Y Test' and 'Predicted Y'. Then print the MAE, MSE and RMSE.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
customers = pd.read_csv('Ecommerce_Customers.csv')
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
X = customers[['Avg. Session Length', 'Time on App', 'Time on Website', 'Length of Membership']]
y = customers['Yearly Amount Spent']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
lm = LinearRegression()
lm.fit(X_train, y_train)
predictions = lm.predict(X_test)

The residuals

If the model fits well, the errors look like a bell curve around zero. They do.

Exercise

7. The answer

Make a DataFrame called coefficients with the feature names as the index and one column, 'Coefficient', holding lm.coef_. Show it.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
customers = pd.read_csv('Ecommerce_Customers.csv')
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
X = customers[['Avg. Session Length', 'Time on App', 'Time on Website', 'Length of Membership']]
y = customers['Yearly Amount Spent']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
lm = LinearRegression()
lm.fit(X_train, y_train)
predictions = lm.predict(X_test)

What it means

Holding everything else fixed, each extra minute of average app time goes with about $39 more spending a year, while each extra minute on the website goes with only about $0.19. Another year of membership is worth about $61.

So should the company invest in the app or the website? There are two good answers: build on what already works (the app), or fix what doesn't (the website, which may be underperforming). Either way, membership length matters most, so keeping customers longer is the biggest lever. Data informs the decision; it doesn't make it for you.

Exercises solved: 0 of 7

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.