Linear Models: Regression and Classification
Train linear regression and logistic regression models.
Linear Regression
LinearRegression fits a straight line (or hyperplane) by minimising least-squares error.
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
X, y = make_regression(n_samples=200, n_features=5, noise=10, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
model = LinearRegression().fit(X_tr, y_tr)
print("RMSE:", mean_squared_error(y_te, model.predict(X_te))**0.5)Model Coefficients
After fitting, inspect coef_ (feature weights) and intercept_.
from sklearn.linear_model import LinearRegression
import numpy as np
X = np.array([[1],[2],[3]])
y = np.array([2, 4, 6])
model = LinearRegression().fit(X, y)
print("Coef:", model.coef_) # [2.]
print("Intercept:", model.intercept_) # ~0All lessons in this course
- The scikit-learn API: fit, transform, predict
- Linear Models: Regression and Classification
- Tree-Based Models: Decision Trees and Random Forests
- Model Evaluation and Cross-Validation