Supervised Learning with scikit-learn
George Boorman
Core Curriculum Manager, DataCamp
$y = ax + b$
Simple linear regression uses one feature
$y$ = target
$x$ = single feature
$a$, $b$ = parameters/coefficients of the model - slope, intercept
How do we choose $a$ and $b$?
Define an error function for any given line
Choose the line that minimizes the error function
Error function = loss function = cost function
$RSS = $ $\displaystyle\sum_{i=1}^{n}(y_i-\hat{y_i})^2$
Ordinary Least Squares (OLS): minimize RSS
$$ y = a_{1}x_{1} + a_{2}x_{2} + b$$
$$ y = a_{1}x_{1} + a_{2}x_{2} + a_{3}x_{3} +... + a_{n}x_{n}+ b$$
from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
reg_all = LinearRegression()
reg_all.fit(X_train, y_train)
y_pred = reg_all.predict(X_test)
$R^2$: quantifies the variance in target values explained by the features
High $R^2$:
reg_all.score(X_test, y_test)
0.356302876407827
$MSE = $ $\displaystyle\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y_i})^2$
$RMSE = $ $\sqrt{MSE}$
from sklearn.metrics import mean_squared_error
mean_squared_error(y_test, y_pred, squared=False)
24.028109426907236
Supervised Learning with scikit-learn