Fitting a Linear Regression Model to the Housing Dataset with Sklearn
Introduction and Basics of Linear Regression Model Fitting
Welcome back! Today, we are delving into the practical application of predictive modeling. This lesson will focus on applying Linear Regression using the California Housing Dataset and Python, to make predictions with real-world data. This time we will be utilizing the powerful sklearn library to simplify our process, instead of implementing linear regression from scratch, this will allow us to efficiently calculate coefficients, plot data and regression lines. So, without further ado, let's dive in!
Data Loading and Preparation
Our journey begins by loading the California Housing Dataset. Here's how we do it with Python:
The fetch_california_housing function returns what sklearn calls a Bunch object. You can think of a Bunch object as a specialized dictionary that allows you to access data using either standard dictionary keys (housing['data']) or dot notation (housing.data).
Key components of this object include:
.data: A 2D NumPy array where each row is a sample and each column is a feature..target: A 1D array containing the values we want to predict (Median House Value)..feature_names: A list of the names of each column in the data array.
To prepare our data, we select the "Median Income" feature—located at index 0 of the housing.data array—using the slicing syntax [:, 0]. We then reshape it to ensure compatibility with sklearn, which expects the input features () to be a 2-dimensional structure.
Fitting the Model
With our data prepared, we can now fit our linear regression model:
Here, we initialize the LinearRegression model and fit it to our data using model.fit(X, Y). This function trains the model by finding the best coefficients that predict our target values from the given features. It does this through an optimization process, minimizing the error between actual and predicted values. Essentially, model.fit enables us to automate the complex steps of learning from data, allowing sklearn to handle the underlying mathematics. This makes fitting the model both accessible and efficient, readying it for predictions without manual intervention.

