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
coef_holds one weight per feature,intercept_the offset.mean_squared_errorandr2_scoredescribe the fit.- Predictions come back as an array, one per row of X.
Keywords and builtins used here
print
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.
Step 3 of 3 in The estimator API, step 3 of 25 in Machine learning with scikit-learn.