Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TensorFlow Example – Regression Problem

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


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


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

- `rmsprop`: A good default for most problems - `mse` (Mean Squared Error): Mean squared error - `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


5. Evaluate the model

Example

Evaluate on the test set

test_mse_score

,

test_mae_score

=

model.

evaluate

(

test_data

,

test_targets

)

print

(

f

"Test set MAE: {test_mae_score}"

)

Interpreting Evaluation Metrics

- For example, MAE=2.5 means the average prediction deviation is $25,000

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

)

)

print

(

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

)

   

print

(

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

Problem 2: Low training error but high test error

Problem 3: Predicted values deviate greatly from actual values