When predicting outcomes based on multiple factors, a single line isn't enough. We must fit a multidimensional plane through our data. Instead of one slope, we now have a weight for each input feature, and the model learns how each factor contributes to the final prediction.
hθ(x) = θ0 + θ1x1 + θ2x2hθ(x) = θTx.
Use Scikit-Learn to fit a plane to the provided 2-feature X matrix and y vector. Print the weights and intercept.
Import LinearRegression from sklearn.linear_model. Instantiate the model and pass the 2D X matrix and y vector into .fit(). Because X is already 2D (a list of lists), no .reshape() is needed!
model = LinearRegression()
model.fit(X, y)
The learned parameters are in model.coef_ (an array of weights, one per feature) and model.intercept_ (the bias).
Note: This is the same workflow as Simple Linear Regression, but now our input X has multiple columns — one for each feature.
import)numpy) and our machine learning toolbox (sklearn).import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1, 2], [2, 4], [3, 5], [4, 4], [5, 7]])
y = np.array([5.1, 10.2, 14.5, 12.8, 19.7])
model = LinearRegression()
model.fit(). The algorithm figures out a separate weight for each column.model.fit(X, y)
model.coef_ now returns an array of weights — one for each feature column. The first element is w₁ and the second is w₂. The intercept is still a single number.print(f"Weights: {model.coef_}")
print(f"Intercept: {model.intercept_}")
Waiting for execution...
Use NumPy matrix algebra (The Normal Equation) to calculate the weights directly. No ML library allowed!
The Normal Equation solves for all weights at once using matrix algebra:
W = (Xᵀ X)⁻¹ Xᵀ Y
Use np.linalg.inv() for the matrix inverse and .T for the transpose. Don't forget to add a column of 1s to X to account for the intercept!
W = (Xᵀ X)⁻¹ Xᵀ Y
Note: With multiple features, basic division fails. We use matrix algebra to solve for all weights simultaneously. Think of it as solving a system of equations in one shot.
numpy and define your X matrix (2 features) and y vector.import numpy as np
X = np.array([[1, 2], [2, 4], [3, 5], [4, 4], [5, 7]])
y = np.array([5.1, 10.2, 14.5, 12.8, 19.7])
1s to our X matrix. This "absorbs" the bias into the matrix math so we can solve for everything in one equation.X_b = np.c_[np.ones((len(X), 1)), X]
X_T = X_b.T
.dot() method multiplies matrices together. np.linalg.inv() finds the inverse (think of it as "dividing" matrices). We chain these together following the formula from top to bottom.weights = np.linalg.inv(X_T.dot(X_b)).dot(X_T).dot(y)
weights array contains all our values. The first number is the intercept (b), because we added the 1s column first. The rest are the feature weights (w₁, w₂).print(f"Intercept (b): {weights[0]}")
print(f"Weight 1 (w1): {weights[1]}")
print(f"Weight 2 (w2): {weights[2]}")
Waiting for execution...