Start learning free

LESSON 41 OF 165 · MACHINE LEARNING: MODELS

Predict a Number: Linear Regression

Practice

In the last module your tree answered with a class, like 0 or 1. Some questions need a number instead: how many dollars did this customer spend? A model that predicts a number is a regression model.

Linear regression decides with one sum: each feature times a weight it learned, plus a starting amount. LinearRegression(), from sklearn.linear_model, makes an empty model. model.fit(X, y) learns the weights from the training rows and their answers. model.predict(rows) gives back an array with one number per row, with decimals, and the array's own .round(1) rounds every number in it to 1 decimal.

from sklearn.linear_model import LinearRegression

X = [[1], [2], [3]]   # hours of work
y = [10, 20, 30]      # dollars earned
m = LinearRegression()
m.fit(X, y)
print(m.predict([[4]]).round(1))   # [40.]

The starting code reads customers.csv, keeps visits and orders in X and spent in y, and splits them into 225 training rows and 75 test rows. It prints the first 5 test rows, rows. When you're done, each row also shows the model's guess and what the customer really spent. The last line comes from a check that asks your fitted model about 10 visits and 3 orders:

     visits  orders  predicted  real
208      18       6      393.4   357
188       5       2      132.5   310
12        8       1       52.1    22
221       2       3      212.9   104
239       9       1       49.6     0
Guess for 10 visits and 3 orders: 193.5

Your task: below the split, make a LinearRegression model in model, fit it on X_train and y_train, and keep its guesses for X_test[:5] in predictions. Then add the columns "predicted" (the guesses rounded to 1 decimal) and "real" (y_test[:5]) to rows.


Assignment
Follow the Coding Tutorial to fit a linear regression on visits and orders and print its guesses next to the real amounts.


Hint
The answers in y are dollars, so predict gives back dollars too. y_test[:5] lines up with X_test[:5], row by row.


STEP 1 OF 5
    Ctrl + Enter to check