0
0
TensorFlowml~5 mins

model.fit() training loop in TensorFlow

Choose your learning style9 modes available
Introduction

The model.fit() function trains a machine learning model by showing it data many times. It helps the model learn patterns to make good predictions.

When you want to teach a model to recognize images by showing labeled pictures multiple times.
When you have a dataset of text and want the model to learn to classify the text into categories.
When you want to improve a model's predictions by training it on new data.
When you want to track how well your model is learning during training.
When you want to stop training early if the model stops improving.
Syntax
TensorFlow
model.fit(x, y, epochs=10, batch_size=32, validation_data=None, callbacks=None)

x is the input data, and y is the target labels.

epochs is how many times the model sees the whole dataset.

Examples
Train the model on x_train and y_train for 5 full passes.
TensorFlow
model.fit(x_train, y_train, epochs=5)
Train with batches of 64 samples, for 10 passes over the data.
TensorFlow
model.fit(x_train, y_train, epochs=10, batch_size=64)
Train for 10 epochs and check performance on validation data after each epoch.
TensorFlow
model.fit(x_train, y_train, epochs=10, validation_data=(x_val, y_val))
Sample Model

This code creates a simple neural network to classify data into 3 groups. It trains the model for 3 epochs with batches of 16 samples. After training, it prints the final accuracy on the training data.

TensorFlow
import tensorflow as tf
from tensorflow.keras import layers, models

# Create simple model
model = models.Sequential([
    layers.Dense(10, activation='relu', input_shape=(4,)),
    layers.Dense(3, activation='softmax')
])

# Compile model with loss and optimizer
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Sample data: 150 samples, 4 features, 3 classes
import numpy as np
x_train = np.random.random((150, 4))
y_train = np.random.randint(0, 3, 150)

# Train model
history = model.fit(x_train, y_train, epochs=3, batch_size=16)

# Print training accuracy after last epoch
print(f"Final training accuracy: {history.history['accuracy'][-1]:.4f}")
OutputSuccess
Important Notes

The batch_size controls how many samples the model looks at before updating its knowledge.

Using validation_data helps you see if the model is learning well or just memorizing.

You can add callbacks to stop training early or save the best model.

Summary

model.fit() trains your model by showing data multiple times.

You can control training length with epochs and speed with batch_size.

Validation data helps check if the model is learning properly during training.