TensorFlow Example - Regression Problem
What Is a Regression Problem
Regression is an important class of problems in machine learning, with the goal of predicting continuous-valued outputs. Unlike classification problems (which predict discrete categories), regression problems predict values in the real-number range.
Examples of Common Regression Problems
- House price prediction: predict prices based on features such as area and location
- Stock prediction: predict future stock prices based on historical data
- Temperature prediction: predict future temperatures based on weather data
Basic Workflow of Solving Regression Problems with TensorFlow

Practical: Boston Housing Price Prediction
1. Prepare data
We will use the classic Boston housing dataset, which contains 506 samples, each with 13 features:
Example
from
tensorflow.
keras
.
datasets
import
boston_housing
Load data
(
train_data
,
train_targets
)
,
(
test_data
,
test_targets
)
=
boston_housing.
load_data
(
)
Data standardization (important step)
mean
=
train_data.
mean
(
axis
=
0
)
train_data -
=
mean
std
=
train_data.
std
(
axis
=
0
)
train_data /
=
std
test_data -
=
mean
test_data /
=
std
2. Build the model
Example
from
tensorflow.
keras
import
models
from
tensorflow.
keras
import
layers
def
build_model
(
)
:
model
=
models.
Sequential
(
[
layers.
Dense
(
64
,
activation
=
'relu'
,
input_shape
=
(
train_data.
shape
[
1
]
,
)
)
,
layers.
Dense
(
64
,
activation
=
'relu'
)
,
layers.
Dense
(
1
)
The output layer does not need an activation function
]
)
return
model
Model Structure Description
- Input layer: corresponds to 13 features
- Two hidden layers: 64 neurons each, using the ReLU activation function
- Output layer: 1 neuron (predicting house price), no activation function
3. Compile the model
Example
model
=
build_model
(
)
model.
compile
(
optimizer
=
'rmsprop'
,
loss
=
'mse'
,
Mean squared error
metrics
=
[
'mae'
]
)
Mean absolute error
Key Parameter Descriptions
- optimizer: Optimizer, controls the learning process
rmsprop: A good default for most problems
- loss: Loss function, commonly used for regression problems
mse(Mean Squared Error): Mean squared error
- metrics: Evaluation metric
mae(Mean Absolute Error): Mean absolute error
4. Train the model
Example
history
=
model.
fit
(
train_data
,
train_targets
,
epochs
=
100
,
batch_size
=
16
,
validation_split
=
0.2
)
Parameter Explanations
epochs: Number of training epochsbatch_size: Amount of data per batchvalidation_split: Validation set ratio
5. Evaluate the model
Example
Evaluate on the test set
test_mse_score
,
test_mae_score
=
model.
evaluate
(
test_data
,
test_targets
)
(
f
"Test set MAE: {test_mae_score}"
)
Interpreting Evaluation Metrics
- MAE (Mean Absolute Error): The average difference between predicted and true values
- For example, MAE=2.5 means the average prediction deviation is $25,000
- MSE (Mean Squared Error): Gives larger penalties to larger errors
6. Make Predictions with the Model
Example
Predict on new data
sample
=
test_data
[
0
]
Take the first sample of the test set
prediction
=
model.
predict
(
sample.
reshape
(
1
,
1
)
)
(
f
"Predicted price: {prediction[0][0]}, actual price: {test_targets[0]}"
)
Model Optimization Tips
1. Adjust the network structure
Example
A deeper network may perform better
def
build_deeper_model
(
)
:
model
=
models.
Sequential
(
[
layers.
Dense
(
128
,
activation
=
'relu'
,
input_shape
=
(
train_data.
shape
[
1
]
,
)
)
,
layers.
Dense
(
64
,
activation
=
'relu'
)
,
layers.
Dense
(
32
,
activation
=
'relu'
)
,
layers.
Dense
(
1
)
]
)
return
model
2. Use K-fold cross-validation
Example
from
sklearn.
model_selection
import
KFold
k
=
4
kf
=
KFold
(
n_splits
=
k
)
for
train_index
,
val_index
in
kf.
split
(
train_data
)
:
Split the training and validation sets
partial_train_data
=
train_data
[
train_index
]
partial_train_targets
=
train_targets
[
train_index
]
val_data
=
train_data
[
val_index
]
val_targets
=
train_targets
[
val_index
]
Train and evaluate the model
model
=
build_model
(
)
model.
fit
(
partial_train_data
,
partial_train_targets
,
epochs
=
100
,
batch_size
=
16
,
verbose
=
0
)
val_mse
,
val_mae
=
model.
evaluate
(
val_data
,
val_targets
,
verbose
=
0
)
(
f
"Validation MAE: {val_mae}"
)
3. Add regularization to prevent overfitting
Example
from
tensorflow.
keras
import
regularizers
model
=
models.
Sequential
(
[
layers.
Dense
(
64
,
activation
=
'relu'
,
kernel_regularizer
=
regularizers.
l2
(
0.001
)
,
input_shape
=
(
train_data.
shape
[
1
]
,
)
)
,
layers.
Dense
(
64
,
activation
=
'relu'
,
kernel_regularizer
=
regularizers.
l2
(
0.001
)
)
,
layers.
Dense
(
1
)
]
)
Common Problems and Solutions
Problem 1: Unstable model performance
- Reason: Small data volume or randomness in initialization
- Solution: Increase the data volume or use K-fold cross-validation
Problem 2: Low training error but high test error
- Reason: Overfitting
- Solution: Add a Dropout layer or L2 regularization
Problem 3: Predicted values deviate greatly from actual values
- Reason: Data not standardized or unreasonable network structure
- Solution: Check data preprocessing steps, adjust network depth and width