California Housing Regression

Introduction

Welcome to the final lesson of "Building and Applying Your Neural Network Library". Congratulations on making it this far — you've accomplished something truly remarkable. Over the course of this path, you've built a complete, modular neural network library from scratch, learning the inner workings of layers, activations, optimizers, loss functions, and the orchestration that brings them all together. You've also mastered the essential data preparation techniques needed for real-world machine learning applications.

Today, we're going to experience the incredible satisfaction of seeing all your hard work come together. We'll use our custom-built neural network library to tackle a real regression problem: predicting California housing prices. You'll see how the modular architecture you've carefully constructed makes it surprisingly straightforward to define complex neural networks, train them efficiently, and evaluate their performance on real data.

This lesson represents the culmination of your journey — the moment when theory meets practice, and your carefully crafted code proves its worth on a meaningful problem. Let's put your neural network library to the ultimate test!

Project Structure

neuralnets-project/
├── CMakeLists.txt
├── main.cpp
└── include/
    └── neuralnets/          ← library headers (include path root)
        ├── models/
        │   └── SequentialModel.h
        ├── layers/
        │   └── DenseLayer.h
        └── losses/
            └── Losses.h
└── src/
    ├── models/
    │   └── SequentialModel.cpp
    ├── layers/
    │   └── DenseLayer.cpp
    └── losses/
        └── Losses.cpp

You'll notice two neuralnets references — one as the project name at the root, and one as a folder inside include/. The include/neuralnets/ folder is the library's include root, which is why headers are written as "neuralnets/layers/DenseLayer.h" rather than just "layers/DenseLayer.h". This is a standard C++ library convention that namespaces your headers and avoids conflicts with other libraries. All new files in this lesson are in include/neuralnets/models/ and src/models/ — everything else was built in previous lessons.

Setting Up the Data

Let's start by including our components and setting up the data preprocessing pipeline. Since you mastered data preparation in the previous lesson, we'll handle this efficiently and effortlessly:

#include <iostream>
#include <vector>
#include <random>
#include <fstream>
#include <sstream>
#include <string>
#include <Eigen/Dense>
#include "neuralnets/models/SequentialModel.h"
#include "neuralnets/layers/DenseLayer.h"
#include "neuralnets/losses/Losses.h"
#include "neuralnets/preprocessing/StandardScaler.h"

using namespace Eigen;
using namespace neuralnets;

// Generate synthetic California housing data for demonstration
std::pair<MatrixXd, MatrixXd> generateHousingData(int n_samples = 20640) {
    std::random_device rd;
    std::mt19937 gen(42); // Fixed seed for reproducibility
    std::normal_distribution<double> normal(0.0, 1.0);
    std::uniform_real_distribution<double> uniform(0.0, 1.0);
    
    MatrixXd X(n_samples, 8); // 8 features like the original dataset
    VectorXd y(n_samples);
    
    // Generate synthetic features representing housing characteristics
    for (int i = 0; i < n_samples; ++i) {
        X(i, 0) = uniform(gen) * 15.0 + 32.5;  // Latitude-like
        X(i, 1) = uniform(gen) * 4.0 - 124.0;  // Longitude-like  
        X(i, 2) = uniform(gen) * 50.0 + 1.0;   // Housing age
        X(i, 3) = uniform(gen) * 35000.0 + 500.0; // Total rooms
        X(i, 4) = uniform(gen) * 6000.0 + 100.0;  // Total bedrooms
        X(i, 5) = uniform(gen) * 12000.0 + 500.0; // Population
        X(i, 6) = uniform(gen) * 4500.0 + 100.0;  // Households
        X(i, 7) = uniform(gen) * 12.0 + 0.5;      // Median income
        
        // Generate target (house value) based on features with some noise
        double price = 0.5 + 0.3 * X(i, 7) + 0.1 * (50.0 - X(i, 2)) / 50.0 + 
                      0.2 * normal(gen) * 0.5; // Add noise
        y(i) = std::max(0.1, std::min(5.0, price)); // Clamp between 0.1 and 5.0
    }
    
    return {X, y.reshaped(n_samples, 1)};
}

// Split data into training and test sets
std::tuple<MatrixXd, MatrixXd, MatrixXd, MatrixXd> trainTestSplit(
    const MatrixXd& X, const MatrixXd& y, double test_size = 0.2, int random_state = 42) {
    
    std::mt19937 gen(random_state);
    std::vector<int> indices(X.rows());
    std::iota(indices.begin(), indices.end(), 0);
    std::shuffle(indices.begin(), indices.end(), gen);
    
    int test_samples = static_cast<int>(X.rows() * test_size);
    int train_samples = X.rows() - test_samples;
    
    MatrixXd X_train(train_samples, X.cols());
    MatrixXd X_test(test_samples, X.cols());
    MatrixXd y_train(train_samples, y.cols());
    MatrixXd y_test(test_samples, y.cols());
    
    for (int i = 0; i < train_samples; ++i) {
        X_train.row(i) = X.row(indices[i]);
        y_train.row(i) = y.row(indices[i]);
    }
    
    for (int i = 0; i < test_samples; ++i) {
        X_test.row(i) = X.row(indices[train_samples + i]);
        y_test.row(i) = y.row(indices[train_samples + i]);
    }
    
    return {X_train, X_test, y_train, y_test};
}

int main() {
    auto [X, y] = generateHousingData();
    auto [X_train, X_test, y_train, y_test] = trainTestSplit(X, y, 0.2, 42);
    
    // Reusing StandardScaler
    // then apply the same transformation to test data to avoid data leakage
    preprocessing::StandardScaler scaler_X;
    MatrixXd X_train_scaled = scaler_X.fit_transform(X_train);
    MatrixXd X_test_scaled = scaler_X.transform(X_test);

    preprocessing::StandardScaler scaler_y;
    MatrixXd y_train_scaled = scaler_y.fit_transform(y_train);
    MatrixXd y_test_scaled = scaler_y.transform(y_test);

    // Retrieve mean and std for inverse transforming predictions later
    double mean_y = scaler_y.get_mean()(0);
    double std_y = scaler_y.get_std()(0);
    
    int num_features = X_train_scaled.cols();
    
    std::cout << "Data loaded and preprocessed successfully!" << std::endl;
    std::cout << "Training samples: " << X_train.rows() << std::endl;
    std::cout << "Test samples: " << X_test.rows() << std::endl;
    std::cout << "Features: " << num_features << std::endl;

Defining the Neural Network Architecture

Now comes the exciting part — defining our neural network architecture. We'll create a multi-layer perceptron (MLP) with two hidden layers, perfectly suited for this regression task:

    // Define the MLP architecture using SequentialModel
    auto model = std::make_unique<models::SequentialModel>();
    model->add(std::make_unique<layers::DenseLayer>(num_features, 64, "relu"));
    model->add(std::make_unique<layers::DenseLayer>(64, 32, "relu"));
    model->add(std::make_unique<layers::DenseLayer>(32, 1, "linear")); // Linear output for regression
    
    std::cout << "\nNeural network architecture defined:" << std::endl;
    std::cout << "Input layer: " << num_features << " features" << std::endl;
    std::cout << "Hidden layer 1: 64 neurons (ReLU)" << std::endl;
    std::cout << "Hidden layer 2: 32 neurons (ReLU)" << std::endl;
    std::cout << "Output layer: 1 neuron (Linear)" << std::endl;

This architecture represents a sophisticated neural network design. The first hidden layer takes our 8 input features and expands them to 64 neurons, allowing the network to learn complex feature combinations. The ReLU activation introduces nonlinearity, enabling the network to model complex relationships between housing features and prices.

The second hidden layer gradually reduces the dimensionality from 64 to 32 neurons, creating a funnel-like architecture that progressively distills the learned features into more refined representations. Finally, the output layer uses linear activation to produce a single continuous value — the predicted house price.

Compiling the Model

Now we'll compile our model with appropriate training configurations so that it's ready to begin the learning process:

    // Compile the model
    model->compile("sgd", 0.005, "mse"); // Smaller LR for this dataset

The compilation step configures our training setup. We're using SGD (stochastic gradient descent) with a learning rate of 0.005, which is slightly smaller than in our previous examples. Real-world datasets often benefit from more conservative learning rates that allow for stable, consistent learning across the diverse feature landscape.

When you run this code, you'll see:

Model compiled with optimizer: sgd (lr: 0.005), loss: mse

Training the Network

Now for the moment of truth — training our neural network on real data:

    // Train the model
    std::cout << "\nTraining the model..." << std::endl;
    model->fit(X_train_scaled, y_train_scaled, 200, 32, true); // epochs=200, batch_size=32, verbose=true

This single method call triggers a sophisticated training process. Your model will process 200 epochs of training, where each epoch involves multiple mini-batches of 32 samples each. The verbose output shows the learning progress:

Training the model...
Epoch    1/200, Loss: 1.000209
Epoch   20/200, Loss: 0.311592
Epoch   40/200, Loss: 0.265016
Epoch   60/200, Loss: 0.245686
Epoch   80/200, Loss: 0.229533
Epoch  100/200, Loss: 0.222904
Epoch  120/200, Loss: 0.218033
Epoch  140/200, Loss: 0.212335
Epoch  160/200, Loss: 0.208022
Epoch  180/200, Loss: 0.204843
Epoch  200/200, Loss: 0.201297
Training finished.

The decreasing loss values demonstrate successful learning. Your network started with a loss of 1.000 and steadily improved to 0.201 — a clear sign that it's learning meaningful patterns in the housing data. The gradual, consistent decrease indicates stable training without the erratic behavior that can plague poorly configured networks.

Making Predictions and Evaluating Performance

With our model trained, we can now make predictions on the test set and evaluate how well it generalizes to unseen data:

    // Make predictions on the test set
    MatrixXd y_pred_scaled = model->predict(X_test_scaled);
    
    // Evaluate performance on scaled data
    double test_loss_scaled = losses::mse_loss(y_test_scaled, y_pred_scaled);
    std::cout << "\nTest MSE (scaled): " << std::fixed << std::setprecision(4) << test_loss_scaled << std::endl;

This produces our first evaluation metric:

Test MSE (scaled): 0.2083

The test MSE of 0.2083 is quite close to our final training loss of 0.201, which is excellent news. This similarity indicates that our model is generalizing well rather than overfitting to the training data. When test performance closely matches training performance, it suggests we've found genuine patterns rather than memorizing specific training examples.

However, this scaled MSE, while useful for training, doesn't give us an intuitive sense of prediction accuracy. Housing prices measured in standardized units don't mean much to us humans, who think in dollars.

Interpreting Results in Real-World Terms

Looking at Sample Predictions

Conclusion

Congratulations! You've successfully completed the entire journey of building and applying your own neural network library. What you've accomplished in this final lesson represents the true power of the modular, well-designed system you've constructed over the past five lessons. Your achievement is remarkable — you've taken raw California housing data and successfully trained a multi-layer neural network to predict house prices with meaningful accuracy.

The elegance of your solution demonstrates the value of good software design, with clean, readable code that seamlessly integrates data preprocessing, model definition, training, and evaluation. In the upcoming practice exercises, you'll have the opportunity to apply these skills hands-on, building confidence in your ability to tackle real-world machine learning problems with your custom-built neural network library.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal