What is Regression?
Regression means predicting a number, such as a house price, a temperature or the number of sales. In contrast, classification predicts a category.
| Part | Regression choice |
| Output layer | Dense(1) with no activation |
| Loss | mse (or mae / huber) |
| Metric | mae (mean absolute error) |
| Scaling | Scale the input features |
Step 1: Load Data
python
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import keras
from keras import layers
data = fetch_california_housing()
X, y = data.data, data.target # y is the median house value in $100,000
print(X.shape) # (20640, 8)
print(data.feature_names)
Step 2: Split and Scale
We scale the inputs because features such as income and population have very different ranges. Fit the scaler on the training data only.
python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train) # learn mean and std from train
X_test = scaler.transform(X_test) # apply the same to test
Why only fit on training data? If the scaler sees the test data, information leaks from the test set into training. This is called data leakage and it makes your results look better than they really are.
Step 3: Build the Model
python
model = keras.Sequential([
keras.Input(shape=(8,)),
layers.Dense(64, activation="relu"),
layers.Dense(32, activation="relu"),
layers.Dense(1) # no activation: any number
])
model.compile(optimizer="adam", loss="mse", metrics=["mae"])
Step 4: Train
python
history = model.fit(
X_train, y_train,
epochs=50,
batch_size=32,
validation_split=0.2,
verbose=0
)
Step 5: Evaluate and Predict
python
loss, mae = model.evaluate(X_test, y_test, verbose=0)
print("Test MAE:", mae) # about 0.35 -> roughly $35,000 average error
preds = model.predict(X_test[:5]).ravel()
for p, real in zip(preds, y_test[:5]):
print(f"Predicted: {p:.2f} Real: {real:.2f}")
Result
Predicted and real prices are close, for example 2.41 versus 2.35, though not exactly the same.
Check the Learning Curve
python
import matplotlib.pyplot as plt
plt.plot(history.history["loss"], label="train")
plt.plot(history.history["val_loss"], label="validation")
plt.legend()
plt.show()
Ideas to Improve
- Add Dropout or L2 if validation loss rises
- Use
EarlyStopping
- Try more neurons or one more layer
- Compare with a simple linear regression to see if the neural network really helps
Conclusion
Regression with Keras follows the same pattern as classification, with a linear output and MSE loss. Always scale the inputs, and measure the error in understandable units.
Quick Summary: Scale features, use Dense(1) without activation, train with MSE and report MAE.