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

TensorFlow Model Training

TensorFlow Model Training

TensorFlow provides a full set of tools for building and training neural network models.

Model training is the process of letting a model automatically adjust its parameters through data to gain predictive capability.

Core Elements of Model Training


Training Process

1. Data Preparation

Example

import

tensorflow

as

tf

from

tensorflow.

keras

import

datasets

Load the dataset (using MNIST as an example)

(

train_images

,

train_labels

)

,

(

test_images

,

test_labels

)

=

datasets.

mnist

.

load_data

(

)

Data preprocessing

train_images

=

train_images.

reshape

(

(

60000

,

28

,

28

,

1

)

)

.

astype

(

'float32'

)

/

255

test_images

=

test_images.

reshape

(

(

10000

,

28

,

28

,

1

)

)

.

astype

(

'float32'

)

/

255

Convert to a TensorFlow Dataset

train_dataset

=

tf.

data

.

Dataset

.

from_tensor_slices

(

(

train_images

,

train_labels

)

)

train_dataset

=

train_dataset.

shuffle

(

10000

)

.

batch

(

64

)

2. Model Building

Example

from

tensorflow.

keras

import

layers

,

models

Build a Sequential model

model

=

models.

Sequential

(

[

    layers.

Conv2D

(

32

,

(

3

,

3

)

,

activation

=

'relu'

,

input_shape

=

(

28

,

28

,

1

)

)

,

    layers.

MaxPooling2D

(

(

2

,

2

)

)

,

    layers.

Conv2D

(

64

,

(

3

,

3

)

,

activation

=

'relu'

)

,

    layers.

MaxPooling2D

(

(

2

,

2

)

)

,

    layers.

Conv2D

(

64

,

(

3

,

3

)

,

activation

=

'relu'

)

,

    layers.

Flatten

(

)

,

    layers.

Dense

(

64

,

activation

=

'relu'

)

,

    layers.

Dense

(

10

,

activation

=

'softmax'

)

]

)

View the model structure

model.

summary

(

)

3. Model Compilation

Example

model.

compile

(

optimizer

=

'adam'

,

              loss

=

'sparse_categorical_crossentropy'

,

              metrics

=

[

'accuracy'

]

)

Compilation option description

Parameters Optional values Description
optimizer 'adam', 'sgd', 'rmsprop', etc. Optimization algorithm selection
loss 'mse', 'categorical_crossentropy', etc. Loss function type
metrics ['accuracy'], ['mse'], etc. Evaluation metrics list

4. Model Training

Example

history

=

model.

fit

(

train_dataset

,

                    epochs

=

10

,

                    validation_data

=

(

test_images

,

test_labels

)

)

Main parameters of the fit() method

Parameters Type Description
x Input data Training data
y Target data Label data
epochs Integers Number of Training Epochs
batch_size Integers Amount of data per batch
validation_data Tuple Validation dataset
callbacks List List of callbacks

Training process visualization

Training curves

Example

import

matplotlib.

pyplot

as

plt

Plot training and validation accuracy curves

plt.

plot

(

history.

history

[

'accuracy'

]

,

label

=

'Training Accuracy'

)

plt.

plot

(

history.

history

[

'val_accuracy'

]

,

label

=

'Validation Accuracy'

)

plt.

xlabel

(

'Epoch'

)

plt.

ylabel

(

'Accuracy'

)

plt.

legend

(

)

plt.

show

(

)

Training Flowchart


Advanced Training Techniques

Custom training loop

Example

Define the loss function and optimizer

loss_fn

=

tf.

keras

.

losses

.

SparseCategoricalCrossentropy

(

)

optimizer

=

tf.

keras

.

optimizers

.

Adam

(

)

Custom training steps

@

tf.

function

def

train_step

(

images

,

labels

)

:

   

with

tf.

GradientTape

(

)

as

tape:

        predictions

=

model

(

images

)

        loss

=

loss_fn

(

labels

,

predictions

)

    gradients

=

tape.

gradient

(

loss

,

model.

trainable_variables

)

    optimizer.

apply_gradients

(

zip

(

gradients

,

model.

trainable_variables

)

)

   

return

loss

Custom training loop

for

epoch

in

range

(

10

)

:

   

for

images

,

labels

in

train_dataset:

        loss

=

train_step

(

images

,

labels

)

   

print

(

f

'Epoch {epoch}, Loss: {loss.numpy()}'

)

Using Callbacks

Example

from

tensorflow.

keras

.

callbacks

import

ModelCheckpoint

,

EarlyStopping

Create a callback

callbacks

=

[

    ModelCheckpoint

(

'best_model.h5'

,

save_best_only

=

True

)

,

    EarlyStopping

(

patience

=

3

,

monitor

=

'val_loss'

)

]

Train with callbacks

model.

fit

(

train_dataset

,

          epochs

=

20

,

          validation_data

=

(

test_images

,

test_labels

)

,

          callbacks

=

callbacks

)


Common Problems and Solutions

Training Troubleshooting Table

Symptom Possible cause Solution
Loss does not decrease Learning rate too high/too low Adjust the learning rate
Accuracy fluctuates greatly Batch size inappropriate Adjust batch_size
Overfitting Model too complex Add regularization or Dropout
Slow training Hardware limitations Use GPU acceleration or reduce the model size

Performance Optimization Suggestions

  1. Data pipeline optimization:

Example

# Use prefetch and cache to speed up data loading
train_dataset = train_dataset.cache().prefetch(buffer_size=tf.data.AUTOTUNE)
2.

Mixed-precision training:

Example

policy = tf.keras.mixed_precision.Policy('mixed_float16')
tf.keras.mixed_precision.set_global_policy(policy)
3.

Distributed training:

Example

strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
    model = create_model()
    model.compile(...)

Practical Exercise

Exercise 1: Basic Training

Using the Fashion MNIST dataset, build a CNN model and complete training, with the following requirements:

Exercise 2: Advanced Techniques

Based on Exercise 1:

  1. Add an EarlyStopping callback
  2. Implement learning rate decay
  3. Use ModelCheckpoint to save the best model

Exercise 3: Custom Training

Try implementing the task of Exercise 1 with a custom training loop, and compare the differences with the fit() method.


Through this article, you should have mastered the core workflow and key techniques of TensorFlow model training. In practical applications, you need to adjust training strategies according to specific problems and data characteristics. It is recommended to start with a simple model, gradually increase complexity, and find the best training configuration through experiments.