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
- Data: Training, validation, and test sets
- Model architecture: Layer structure and connections of the neural network
- Loss function: Metrics that measure the difference between model predictions and true values
- Optimizer: Algorithms for adjusting model parameters
- Evaluation Metrics: Criteria for measuring model performance
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
)
(
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
-
Data pipeline optimization:
Example
train_dataset = train_dataset.cache().prefetch(buffer_size=tf.data.AUTOTUNE)
Mixed-precision training:
Example
tf.keras.mixed_precision.set_global_policy(policy)
Distributed training:
Example
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:
- Contain at least 2 convolutional layers
- Train for 10 epochs
- Record accuracy and loss changes during training
Exercise 2: Advanced Techniques
Based on Exercise 1:
- Add an EarlyStopping callback
- Implement learning rate decay
- 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.