Keras for Regression

Keras Basics

2 min read

Published Nov 17 2025


11
0
0
0

KerasNeural NetworksPythonTensorFlow

Regression models predict continuous numeric values.

Examples:

  • Predicting house prices
  • Predicting temperature
  • Forecasting sales
  • Predicting age
  • Predicting a score or rating

For this section, we will use the California Housing dataset, a real tabular dataset commonly used in ML.

We will cover:

  1. Loading the dataset
  2. Normalising the inputs
  3. Building a regression network
  4. Training it
  5. Evaluating it (MAE/MSE/RMSE)
  6. Predicting new values





Load the California Housing Dataset

The dataset comes from scikit-learn.

from sklearn.datasets import fetch_california_housing
import numpy as np

data = fetch_california_housing()

# features
X = data.data
# target values
y = data.target

Check shapes:

print(X.shape)
# (20640, 8)

print(y.shape)
# (20640,)

There are 8 numerical features per house (median income, rooms, population, etc.).






Train/Test Split

We’ll split the dataset manually:

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
)





Normalise the Inputs

Neural networks must work with normalised features for stability.

Keras has a built-in preprocessing layer:

from tensorflow.keras import layers
from tensorflow import keras

normaliser = layers.Normalization()
normaliser.adapt(X_train)

This layer:

  • Computes mean and variance on training data
  • Applies normalisation consistently during training and inference





Build a Regression Model

Simple MLP for regression:

model = keras.Sequential([
    normaliser,
    layers.Dense(64, activation='relu'),
    layers.Dense(32, activation='relu'),
    # Output = 1 numeric value
    layers.Dense(1)
])

Important details:

  • No activation on final layer
  • Regression networks predict raw values





Compile the Model

Regression uses:

  • Loss: mean squared error (MSE)
  • Metrics: mean absolute error (MAE)
model.compile(
    optimizer='adam',
    loss='mse',
    metrics=['mae']
)

MAE is the easiest to interpret (units are same as target).






Train the Model

history = model.fit(
    X_train, y_train,
    epochs=10,
    batch_size=32,
    validation_split=0.1
)

This dataset trains very quickly.






Evaluate on Test Set

mse, mae = model.evaluate(X_test, y_test)
print("MAE:", mae)
print("RMSE:", np.sqrt(mse))

Typical results:

  • MAE ≈ 0.40–0.55
  • RMSE ≈ 0.55–0.70

This means your predictions are off by about:

  • $0.40–$0.55 median house price units
  • The dataset target is in $100,000s, so MAE ≈ 0.5 means ≈ $50,000 error





Making Predictions

sample = X_test[:1]
pred = model.predict(sample)
print("Predicted:", pred[0][0])
print("Actual:", y_test[0])





Visualising Loss Curves

import matplotlib.pyplot as plt

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['Train Loss', 'Validation Loss'])
plt.show()






Improving Regression Models (Quick Tips)

Add more layers / units - Regression tasks often need deeper networks.


Add regularisation

layers.Dense(64, activation='relu', kernel_regularizer='l2')

Use Dropout

layers.Dropout(0.2)

Use learning rate schedules

keras.optimizers.Adam(learning_rate=0.001)

Train for more epochs - But watch for overfitting.


Try the Functional API - Useful for complex tabular models.






Full Working Script

from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
import numpy as np

from tensorflow import keras
from tensorflow.keras import layers

# Load dataset
data = fetch_california_housing()
X = data.data
y = data.target

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Normalisation layer
normalizer = layers.Normalization()
normalizer.adapt(X_train)

# Build model
model = keras.Sequential([
    normalizer,
    layers.Dense(64, activation='relu'),
    layers.Dense(32, activation='relu'),
    layers.Dense(1)
])

# Compile
model.compile(
    optimizer='adam',
    loss='mse',
    metrics=['mae']
)

# Train
history = model.fit(
    X_train, y_train,
    epochs=10,
    batch_size=32,
    validation_split=0.1
)

# Evaluate
mse, mae = model.evaluate(X_test, y_test)
print("MAE:", mae)
print("RMSE:", np.sqrt(mse))

# Predict
print("Predicted:", model.predict(X_test[:1])[0][0])
print("Actual:", y_test[0])

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact