Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

TensorFlow · Module

model.fit

Trains a compiled Keras model for a chosen number of epochs using arrays, tensors, or dataset-like inputs. It supports batching, validation, weighting, callbacks, shuffling, and resuming training.

How it works

After a model is compiled with an optimizer, loss, and optional metrics, fit divides suitable in-memory data into batches and repeatedly processes the dataset for the requested epochs. It can also consume dataset-like inputs, run validation, apply weights, invoke callbacks, and resume from a nonzero initial epoch.

Syntax

fit(x=None, y=None, batch_size=None, epochs=1, verbose='auto', callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_batch_size=None, validation_freq=1)

Parameters

NameTypeDescription
xarray-like, tensor, or dataset-likeInput data: array-like objects, tensors, dataset-like iterables, or other supported input structures.
yarray-like or tensor, optionalTarget data corresponding to x when targets are not included in x.
batch_sizeint or NoneSamples per gradient update; when omitted, the default is 32 for batchable array-like input.
epochsintNumber of complete passes over the training data.
verbose"auto", 0, 1, or 2Verbosity mode for progress reporting.
callbackslist or NoneCallbacks invoked during training.
validation_splitfloatFraction of array-like training data reserved for validation.
validation_datatuple or dataset-like, optionalData used for validation instead of validation_split.
shuffleboolWhether to shuffle training data before each epoch when supported.
class_weightdict or NoneClass weights used to rebalance loss contributions.
sample_weightarray-like or NonePer-sample or per-timestep loss weights.
initial_epochintEpoch index from which to resume.

Returns

A History object containing the recorded training and validation metrics for each epoch.

Key points

  • fit runs optimization over the training input for a specified number of complete dataset iterations.
  • batch_size controls how many samples contribute to one gradient update when fit batches array-like input.
  • validation_split reserves part of supported training data for validation rather than using it for optimization.
  • sample_weight changes each training example's contribution to the loss and applies only during training.

Example: Train a Keras model

import tensorflow as tf

model = tf.keras.Sequential([
    tf.keras.layers.Dense(10, activation="relu"),
    tf.keras.layers.Dense(3, activation="softmax")
])
model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

x = tf.random.normal((32, 8))
y = tf.random.uniform((32,), maxval=3, dtype=tf.int32)
history = model.fit(x, y, batch_size=8, epochs=2, verbose=0)
print(history.history.keys())

Compiles a small classifier and trains it for two epochs on in-memory tensors.

When to use it

Standard supervised training

Train a compiled model on in-memory arrays or tensors over multiple epochs.

Validation monitoring

Monitor held-out performance during training using validation_split or validation_data.

Callback-driven training

Automate checkpointing, logging, scheduling, or early termination during a run.

Resumable training

Continue a prior run while preserving epoch numbering.

Interview questions

QWhat does Model.fit do?

fit trains a compiled model over a fixed number of epochs. Each epoch iterates through the available training data, usually in batches, and the returned History records training and validation metrics.

Follow-up: How would you train from a tf.data.Dataset? Pass the dataset as x, omit batch_size because the dataset supplies batches, and use steps_per_epoch when the dataset does not define a finite epoch.

QHow do validation_split and validation_data differ?

validation_split reserves a fraction of array-like training data for validation, while validation_data explicitly supplies validation inputs and targets. validation_steps limits how many validation batches run when validation data is an iterator-like input.

Follow-up: Why might validation_split not work with a dataset? The argument is intended for supported array-like inputs; supply validation_data with a dataset instead.

QHow do callbacks and initial_epoch affect training?

callbacks receive control points during training and can monitor metrics or alter execution. initial_epoch marks the epoch from which training resumes, while epochs is the final epoch bound for the call.

Follow-up: How can training stop automatically? Use a callback such as EarlyStopping, which checks the monitored value at epoch boundaries and can halt the fit loop.

  • tf.keras.Model.compile
  • tf.keras.Model.evaluate
  • tf.keras.Model.predict
  • tf.keras.callbacks.EarlyStopping
  • tf.keras.callbacks.ModelCheckpoint
  • tf.data.Dataset

Source: tf.keras.Model. Checked 2026-10-15.