Start learning free

LESSON 42 OF 165 · MACHINE LEARNING: MODELS

Read What the Model Learned in Python

Practice

A fitted linear regression is just a few numbers. model.coef_ holds one weight per feature, in the order of the columns of X: coef_[0] belongs to the first column, coef_[1] to the second. model.intercept_ is the starting amount: the guess for a row where every feature is 0.

A weight says how much the guess changes for one more of that feature, with the other features staying the same. It can be negative: then one more of that feature lowers the guess. The model's guess is nothing more than the starting amount plus each weight times its feature.

from sklearn.linear_model import LinearRegression

X = [[1], [2], [3]]   # hours of work
y = [15, 25, 35]      # dollars earned
m = LinearRegression()
m.fit(X, y)
print(round(m.coef_[0], 2))     # 10.0: each hour adds 10 dollars
print(round(m.intercept_, 2))   # 5.0: the guess for 0 hours

The starting code fits the model from the last lesson on visits and orders, keeps the first test row in first with X_test.iloc[0], and prints that customer with the model's guess for them. Your code prints what the model learned and does its sum by hand; a check at the end compares your sum with predict():

Per visit: -2.43
Per order: 73.12
Starting amount: -1.66
Customer: 18 visits, 6 orders
By hand: 393.43
predict(): 393.43
By hand matches predict(): True

Your task: print "Per visit:", "Per order:" and "Starting amount:" with their numbers rounded to 2 decimals. Then add the starting amount, the visit weight times first["visits"] and the order weight times first["orders"] into by_hand, and print it after "By hand:", rounded to 2 decimals.


Assignment
Follow the Coding Tutorial to print the weights and the starting amount, then check the model's guess with your own sum.


Hint
Python counts from 0: coef_[0] is the visits weight and coef_[1] the orders weight. Use the full model.coef_ and model.intercept_ in the sum, not the rounded printed numbers, so it matches predict() exactly.


STEP 1 OF 5
    Ctrl + Enter to check

    Ml Coefficients in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free