
A real estate company receives thousands of property records and wants to estimate house prices based on location, income levels, population, and housing characteristics. The team has historical data, but manually estimating every property's value is slow and inconsistent.
This is a typical predictive modeling problem.
Instead of writing rules such as "houses in expensive areas should cost more," we can train a machine learning model to identify patterns from historical data and use those patterns to estimate prices for properties it has never seen before.
In this tutorial, we'll build a house-price prediction model using Python and PyTorch. We'll use the California Housing dataset, which contains real housing data derived from the 1990 U.S. Census. We'll prepare the data, build a neural network, train it, evaluate its predictions, and save the trained model for future use.
The goal is to build something that works as a complete machine learning experiment, rather than just writing a few PyTorch layers and calling it a predictive model.
1. Install the Required Libraries
Create a project directory:
mkdir pytorch-predictive-model
cd pytorch-predictive-modelCreate a virtual environment:
python -m venv venvActivate it on macOS or Linux:
source venv/bin/activateOn Windows:
venv\Scripts\activateInstall the dependencies:
pip install torch scikit-learn pandas numpy matplotlib joblibWe'll use each library for a specific purpose:
PyTorch: Building and training the neural network.
Scikit-learn: Loading the dataset, splitting data, scaling features, and calculating evaluation metrics.
Pandas: Exploring the dataset.
NumPy: Working with numerical data.
Matplotlib: Visualizing actual and predicted prices.
Joblib: Saving the preprocessing scaler.
2. Load Real Housing Data
We'll use the California Housing dataset available through Scikit-learn.
It contains 20,640 observations, with eight input features describing housing districts.
The features include:
Feature | Meaning |
|---|---|
MedInc | Median income in the district |
HouseAge | Median house age |
AveRooms | Average number of rooms |
AveBedrms | Average number of bedrooms |
Population | District population |
AveOccup | Average household occupancy |
Latitude | Geographic latitude |
Longitude | Geographic longitude |
The target is the median house value, represented in units of $100,000.
For example, a target value of 2.5 represents a median house value of approximately $250,000.
Create train.py and load the dataset:
import pandas as pd
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True)
df = housing.frame
print(df.head())
print(df.shape)
print(df.info())The dataset is downloaded the first time it is requested and cached locally by Scikit-learn.
Let's inspect the target distribution:
print(df["MedHouseVal"].describe())This is an important step. Before training a model, we should understand the values we're trying to predict.
For example, we should check:
Whether features contain missing values.
Whether some features have unusually large values.
Whether the target has extreme observations.
Whether the features have different numerical scales.
A neural network can struggle when one feature has values around 0.5 and another has values around 20,000. We'll handle that with feature scaling.
3. Separate Input Features and Target Values
Our model needs two things:
Input features that describe a property.
Target values representing the known house prices.
Separate them:
X = df.drop(columns=["MedHouseVal"])
y = df["MedHouseVal"]
print("Features:", X.shape)
print("Target:", y.shape)The feature matrix has eight columns, while the target contains one value for every observation.
Conceptually, one training example looks like this:
Input:
MedInc = 5.2
HouseAge = 25
AveRooms = 6.1
AveBedrms = 1.2
Population = 850
AveOccup = 2.8
Latitude = 34.1
Longitude = -118.2
Expected output:
MedHouseVal = 3.4The model learns a relationship between the input values and the expected output.
It doesn't memorize a formula that we manually provide. During training, it adjusts its internal parameters to reduce the difference between its predictions and the actual values.
4. Split the Dataset into Training and Testing Data
One of the easiest mistakes in machine learning is evaluating a model using the same data used to train it.
A model might perform very well on training data but fail when it receives new observations.
To avoid this, we'll keep separate training and testing datasets.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42
)
print("Training samples:", len(X_train))
print("Testing samples:", len(X_test))This gives us approximately:
16,512 training observations.
4,128 testing observations.
The training data teaches the model. The testing data measures how well it performs on observations it hasn't seen during training.
For a more advanced experiment, we could also create a separate validation set for choosing hyperparameters and monitoring training.
5. Scale the Input Features
Consider two features:
Median Income: 3.5
Population: 1200Their numerical ranges are very different.
Neural networks generally train more reliably when input features have comparable scales. We'll use StandardScaler to transform each feature.
The transformation is:
[
x_{\text{scaled}} = \frac{x-\mu}{\sigma}
]
Here:
(x) is the original feature value.
(\mu) is the training-set mean.
(\sigma) is the training-set standard deviation.
Implement the scaling:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)Notice that we call fit_transform() only on the training data.
For testing data, we use transform() with the same fitted scaler.
This is important because fitting the scaler on the entire dataset would allow information from the test set to influence preprocessing. That is a form of data leakage.
6. Convert the Data into PyTorch Tensors
PyTorch models work with tensors rather than Pandas DataFrames.
We'll convert the feature arrays and target values into floating-point tensors.
import torch
X_train_tensor = torch.tensor(
X_train_scaled,
dtype=torch.float32
)
X_test_tensor = torch.tensor(
X_test_scaled,
dtype=torch.float32
)
y_train_tensor = torch.tensor(
y_train.to_numpy().reshape(-1, 1),
dtype=torch.float32
)
y_test_tensor = torch.tensor(
y_test.to_numpy().reshape(-1, 1),
dtype=torch.float32
)Why use float32?
Neural networks commonly use 32-bit floating-point values for numerical computations. This is a practical default for many training workloads.
The reshape(-1, 1) operation gives the target values a two-dimensional shape:
Before: (16512,)
After: (16512, 1)This matches the shape of our model's output, which will contain one predicted house value per input row.
7. Create a Dataset and DataLoader
We could pass the entire training dataset into the model at once. However, this becomes inefficient for larger datasets.
Instead, we'll divide the data into smaller batches.
PyTorch provides two useful classes:
TensorDatasetcombines input and target tensors.DataLoaderprovides batches of samples during training.
from torch.utils.data import TensorDataset, DataLoader
train_dataset = TensorDataset(
X_train_tensor,
y_train_tensor
)
test_dataset = TensorDataset(
X_test_tensor,
y_test_tensor
)
train_loader = DataLoader(
train_dataset,
batch_size=64,
shuffle=True
)
test_loader = DataLoader(
test_dataset,
batch_size=64,
shuffle=False
)With a batch size of 64, the model processes up to 64 observations in one training step.
We shuffle the training data so the model doesn't repeatedly encounter observations in the same order.
For evaluation, shuffling is unnecessary.
8. Build the Predictive Model Using PyTorch
Now we'll create the neural network.
Our problem is a regression task because we want to predict a continuous numerical value rather than select a category.
We'll use a simple feed-forward neural network.
import torch.nn as nn
class HousePriceModel(nn.Module):
def __init__(self):
super().__init__()
self.network = nn.Sequential(
nn.Linear(8, 64),
nn.ReLU(),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 16),
nn.ReLU(),
nn.Linear(16, 1)
)
def forward(self, x):
return self.network(x)Let's understand the architecture.
First layer:
nn.Linear(8, 64)The model receives eight input features and transforms them into 64 values.
Activation function:
nn.ReLU()ReLU introduces non-linearity, allowing the network to learn relationships that cannot be represented by a simple linear transformation.
Hidden layers:
nn.Linear(64, 32)
nn.Linear(32, 16)These layers progressively transform the learned representations.
Output layer:
nn.Linear(16, 1)We need one numerical prediction, so the final layer contains one output neuron.
We don't apply a sigmoid or softmax activation to the output because house-price regression is not a probability classification problem.
9. Choose the Loss Function and Optimizer
A model needs a way to measure how wrong its predictions are.
For regression, we'll use Mean Squared Error (MSE).
[
MSE = \frac{1}{n}\sum_{i=1}^{n}(y_i-\hat{y}_i)^2
]
Here, (y_i) represents the actual value and (\hat{y}_i) represents the predicted value.
In PyTorch:
model = HousePriceModel()
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(
model.parameters(),
lr=0.001
)Adam is a commonly used optimizer that adjusts model parameters using gradients.
The learning rate controls how large the parameter updates are during training.
If it is too high, training may become unstable. If it is too low, learning may take a long time.
MSE gives larger errors more weight because the differences are squared. That's useful in many regression tasks, but we should also evaluate the model using metrics in the original price units.
10. Train the Model
This is where the model starts learning from historical housing data.
Every training batch follows the same process:
Pass input features through the network.
Compare predictions with actual prices.
Calculate the loss.
Calculate gradients using backpropagation.
Update the model parameters.
Let's implement the training loop:
epochs = 100
for epoch in range(epochs):
model.train()
total_loss = 0
for features, targets in train_loader:
predictions = model(features)
loss = loss_function(
predictions,
targets
)
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item()
average_loss = total_loss / len(train_loader)
if (epoch + 1) % 10 == 0:
print(
f"Epoch [{epoch + 1}/{epochs}], "
f"Loss: {average_loss:.4f}"
)There are three particularly important operations here.
Reset gradients:
optimizer.zero_grad()PyTorch accumulates gradients by default. Resetting them before each backward pass prevents gradients from previous batches from being unintentionally added.
Calculate gradients:
loss.backward()Autograd calculates how the loss changes with respect to the trainable parameters.
Update model parameters:
optimizer.step()The optimizer uses those gradients to update the network weights.
As training progresses, the loss should generally decrease. However, a decreasing training loss alone doesn't prove that the model is learning patterns that generalize to new data.
That's why we need a separate evaluation process.
11. Evaluate the Model on Unseen Data
After training, we'll evaluate the model using the testing dataset.
We don't want to calculate gradients during evaluation because we're not updating the network parameters.
model.eval()
predictions_list = []
actual_list = []
with torch.no_grad():
for features, targets in test_loader:
predictions = model(features)
predictions_list.extend(
predictions.squeeze(1).tolist()
)
actual_list.extend(
targets.squeeze(1).tolist()
)We now have predicted and actual house values.
Let's calculate some regression metrics.
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score
)
mae = mean_absolute_error(
actual_list,
predictions_list
)
mse = mean_squared_error(
actual_list,
predictions_list
)
rmse = mse ** 0.5
r2 = r2_score(
actual_list,
predictions_list
)
print("MAE:", mae)
print("RMSE:", rmse)
print("R2 Score:", r2)These metrics tell us different things.
Mean Absolute Error (MAE)
MAE calculates the average absolute difference between actual and predicted values.
Root Mean Squared Error (RMSE)
RMSE gives more weight to large prediction errors than MAE does.
R² Score
R² measures how much of the variation in the target values is explained by the model relative to a mean-prediction baseline.
An R² value closer to 1 generally indicates better fit, although it should never be interpreted without considering the dataset and evaluation setup.
Remember that the target is measured in units of $100,000.
For example, an MAE of 0.30 means an average absolute error of approximately $30,000.
The actual metrics will depend on the training configuration, random split, and model architecture. Run the code to obtain your results rather than assuming a particular accuracy.
12. Compare Actual Prices with Predictions
A single evaluation metric doesn't always explain where a model makes mistakes.
Let's compare actual and predicted values for a few observations.
results = pd.DataFrame({
"Actual Price": actual_list[:10],
"Predicted Price": predictions_list[:10]
})
results["Absolute Error"] = abs(
results["Actual Price"] -
results["Predicted Price"]
)
print(results)Because the target is measured in $100,000 units, multiply these values by 100,000 to display approximate dollar amounts.
For example:
results["Actual Price USD"] = (
results["Actual Price"] * 100000
)
results["Predicted Price USD"] = (
results["Predicted Price"] * 100000
)
print(
results[
["Actual Price USD", "Predicted Price USD"]
]
)This makes the model's errors easier to understand.
A prediction of $350,000 against an actual value of $370,000 is quite different from a prediction of $350,000 against an actual value of $600,000.
Both count as errors, but the second one is much more significant.
13. Visualize Model Predictions
A scatter plot helps us see whether predicted values are close to actual values.
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
plt.scatter(
actual_list,
predictions_list,
alpha=0.4
)
plt.xlabel("Actual House Value")
plt.ylabel("Predicted House Value")
plt.title("Actual vs Predicted House Prices")
plt.plot(
[0, 5],
[0, 5],
linestyle="--"
)
plt.tight_layout()
plt.show()The dashed line represents perfect predictions.
Points close to that line indicate predictions close to the actual values. Points far away indicate larger errors.
This visualization can reveal problems that aren't obvious from the overall MAE or RMSE.
One important limitation of this particular dataset is that its target values are capped. The model cannot learn house values beyond the target range represented in the dataset, so it should not be treated as a reliable estimator for expensive properties outside that range.
14. Save the Trained Model
Training a model every time someone wants to make a prediction is unnecessary.
We can save its learned parameters and load them later.
torch.save(
model.state_dict(),
"house_price_model.pth"
)We also need to save the scaler.
This is important because new input data must undergo exactly the same preprocessing used during training.
import joblib
joblib.dump(
scaler,
"feature_scaler.pkl"
)Our project now has two important artifacts:
pytorch-predictive-model/
├── train.py
├── house_price_model.pth
└── feature_scaler.pklThe model file contains learned neural-network parameters, while the scaler contains the training-set means and standard deviations used to transform input features.
15. Make Predictions on New Property Data
Let's create a separate predict.py file.
We'll recreate the same model architecture, load its parameters, load the scaler, and predict the value of a new property.
import torch
import torch.nn as nn
import joblib
import numpy as np
class HousePriceModel(nn.Module):
def __init__(self):
super().__init__()
self.network = nn.Sequential(
nn.Linear(8, 64),
nn.ReLU(),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 16),
nn.ReLU(),
nn.Linear(16, 1)
)
def forward(self, x):
return self.network(x)
model = HousePriceModel()
model.load_state_dict(
torch.load(
"house_price_model.pth",
map_location="cpu",
weights_only=True
)
)
model.eval()
scaler = joblib.load("feature_scaler.pkl")Now prepare a new property record.
The feature order must match the original training dataset:
new_property = np.array([[
5.2, # MedInc
25.0, # HouseAge
6.1, # AveRooms
1.2, # AveBedrms
850.0, # Population
2.8, # AveOccup
34.1, # Latitude
-118.2 # Longitude
]])Scale the new input and generate a prediction:
scaled_property = scaler.transform(new_property)
property_tensor = torch.tensor(
scaled_property,
dtype=torch.float32
)
with torch.no_grad():
prediction = model(property_tensor)
predicted_value = prediction.item()
predicted_price = predicted_value * 100000
print(
f"Estimated House Value: ${predicted_price:,.2f}"
)The output is an estimate generated by the trained model. The example input is illustrative, not a verified property record or a guaranteed market valuation.
16. Improve the Model Before Using It in Production
The neural network we've built is a useful learning example, but it should not automatically become a production pricing system.
There are several improvements worth testing.
Compare Against a Simple Baseline
Before using a neural network, compare it with a model that predicts the mean training-set target for every test observation.
from sklearn.dummy import DummyRegressor
baseline = DummyRegressor(strategy="mean")
baseline.fit(X_train_scaled, y_train)
baseline_predictions = baseline.predict(
X_test_scaled
)
baseline_mae = mean_absolute_error(
y_test,
baseline_predictions
)
print("Baseline MAE:", baseline_mae)
print("PyTorch MAE:", mae)If the neural network does not outperform this baseline, it isn't providing useful predictive value yet.
You should also compare it against traditional models such as Linear Regression, Random Forest, and Gradient Boosting. Neural networks are not automatically the best choice for tabular data.
Experiment with Hidden Layers
We currently use three hidden layers.
You can experiment with different architectures:
nn.Linear(8, 128)
nn.ReLU()
nn.Linear(128, 64)
nn.ReLU()
nn.Linear(64, 1)More layers and neurons don't necessarily mean better predictions. They can also increase training time and overfitting.
Add Validation and Early Stopping
A validation dataset can help identify when the model stops improving on unseen observations.
If training loss continues decreasing while validation loss increases, the model may be overfitting.
Early stopping can terminate training when validation performance no longer improves.
Tune Hyperparameters
Some useful parameters to experiment with include:
Learning rate
Batch size
Number of epochs
Number of hidden layers
Number of neurons
Weight decay
Change one or a small number of parameters at a time and compare validation performance.
Improve the Dataset
The quality of predictions depends heavily on the quality and relevance of the data.
For a real estate application, more recent property transactions, property condition, local amenities, nearby infrastructure, and property-specific characteristics could improve the usefulness of the model.
The California Housing dataset is based on historical district-level information, not current individual property listings. Its predictions should be treated as an educational example rather than current real estate valuations.
17. Where Predictive Models Are Used in Real Applications
The same approach can be applied to many business problems.
Real estate: Estimate property prices using historical transactions and property characteristics.
E-commerce: Predict product demand using historical orders, seasonality, and pricing.
Banking: Estimate credit risk using financial and repayment information, with appropriate fairness and regulatory controls.
Manufacturing: Predict equipment failures using sensor readings and maintenance history.
Healthcare: Estimate certain clinical risks using appropriately validated datasets and clinical oversight.
Logistics: Forecast delivery demand and shipment volumes based on historical patterns.
The important part is choosing a target that can be measured and collecting input features that are available when the prediction needs to be made.
Conclusion
Building a predictive model with PyTorch involves much more than defining a neural network.
We started with real housing data, explored its features, separated training and testing observations, scaled the input values, converted them into tensors, and trained a feed-forward neural network.
We then evaluated its predictions using MAE, RMSE, and R², compared the results with actual values, and saved both the trained model and its preprocessing scaler for future predictions.
The same workflow can be adapted to sales forecasting, demand prediction, customer behavior analysis, and many other regression problems.
One practical lesson is worth keeping in mind: a more complex model is not necessarily a better model. Reliable predictions come from relevant data, correct preprocessing, careful evaluation, and comparisons against simpler approaches.
For the next step, try replacing the California Housing dataset with a dataset from a business problem you're interested in and see whether the same training pipeline can solve it.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


