Python ML Linear Regression with scikit-learn
Linear regression predicts a number from another number. It draws the straight line that fits the data best.
Load the housing data
California Housing holds 20,640 homes. Each home has 8 measurements and one price.
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing()
print(housing.data.shape)
print(housing.target[:3])Split the data first
train_test_split holds back some rows for testing. The model learns from the rest.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
housing = fetch_california_housing()
X = housing.data[:, [0]]
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
print(len(X_train))
print(len(X_test))Fit, then predict
fit() finds the best line. predict() uses that line for a new income value.
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
housing = fetch_california_housing()
X = housing.data[:, [0]]
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
print(np.round(model.predict([[3.0]]), 3))Score the line
score() gives a number near 1 for a good fit. A score near 0 means the line explains little.
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
housing = fetch_california_housing()
X = housing.data[:, [0]]
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
print(round(model.score(X_train, y_train), 4))
print(round(model.score(X_test, y_test), 4))Example
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
housing = fetch_california_housing()
X = housing.data[:, [0]]
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
print("Slope:", round(float(model.coef_[0]), 4))
print("Intercept:", round(float(model.intercept_), 4))
print("Train score:", round(model.score(X_train, y_train), 4))
print("Test score:", round(model.score(X_test, y_test), 4))
print("First predictions:", np.round(model.predict(X_test[:3]), 3))
print("First actual prices:", y_test[:3])Key points
- Regression: a model that predicts a number, like a house price
- Use LinearRegression from sklearn.linear_model to build the line
- Use fit() to teach the model from training data
- Use predict() to ask the model for new numbers
- Use score() to see how much of the pattern the line explains
- Coefficient: the slope of the line, how much the price rises per unit
- Intercept: where the line crosses the vertical axis
In this example, the data holds California homes with one input column, the median income. train_test_split keeps some homes back for testing. LinearRegression fits the best straight line through the training homes. The slope says the price rises by about 0.42 for each extra unit of income. The test score of 0.4708 says the line explains about half of the price pattern. The first three predictions miss the real prices by a lot, and that gap is normal for one input column.
Note
The test score is the honest one. The model never saw the test rows while learning.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does model.fit(X_train, y_train) do?