typestar

Linear regression in Python

Fitting a line, then reading the coefficients and the error.

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

X = [[1.0], [2.0], [3.0], [4.0], [5.0]]
y = [2.1, 3.9, 6.2, 7.8, 10.1]

model = LinearRegression().fit(X, y)
predicted = model.predict(X)

print(f"slope {model.coef_[0]:.2f} intercept {model.intercept_:.2f}")
print(f"mse {mean_squared_error(y, predicted):.3f}")
print(f"r2 {r2_score(y, predicted):.3f}")

How it works

  1. coef_ holds one weight per feature, intercept_ the offset.
  2. mean_squared_error and r2_score describe the fit.
  3. Predictions come back as an array, one per row of X.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
411
Tokens
129
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 3 of 3 in The estimator API, step 3 of 25 in Machine learning with scikit-learn.

← Previous Next →

Linear regression in other languages