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

Keras · Module

model.fit

Model.fit trains a compiled Keras model over batches for a chosen number of epochs. It accepts arrays, tensors, mappings, and dataset-like inputs, and can run validation during training.

How it works

After compilation, fit repeatedly divides compatible input data into batches, performs optimizer updates, and records metric values for each epoch. It can obtain targets from paired arguments or supported dataset-like inputs, and can optionally evaluate validation data during training.

Syntax

Model.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, dict, or dataset-likeTraining inputs, such as arrays, tensors, dictionaries, PyDataset instances, datasets, data loaders, or generators.
yarray-like, tensor, or NoneTarget values; omit when targets are yielded by x.
batch_sizeinteger or NoneSamples per gradient update; defaults to 32 when omitted.
epochsintegerNumber of epochs to train.
verboseauto, 0, 1, or 2Verbosity mode.
callbackslist or NoneCallbacks invoked during training.
validation_splitfloatFraction of array or tensor data reserved for validation.
validation_datatuple or dataset-likeData used for validation.
shufflebooleanWhether to shuffle training data.
class_weightdict or NoneClass weighting for training.
sample_weightarray-like or NonePer-sample weighting for training.
initial_epochintegerEpoch at which to begin training.

Returns

A History object containing the training history, including loss and metric values by epoch.

Key points

  • The epochs argument controls how many training passes are run; by default, it is 1.
  • batch_size determines how many samples contribute to each gradient update, defaulting to 32 when omitted.
  • With ordinary in-memory data, one epoch covers the complete supplied dataset unless steps_per_epoch is set.
  • Named-input models may receive a dictionary keyed by input names.

Example: Train a binary classifier

import numpy as np
import keras

x = np.random.random((100, 4))
y = (x.sum(axis=1) > 2).astype("float32")

model = keras.Sequential([
    keras.layers.Input(shape=(4,)),
    keras.layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
history = model.fit(x, y, batch_size=16, epochs=2, validation_split=0.2)
print(history.history.keys())

Builds, compiles, and trains a small binary classifier, while reserving 20% of the array data for validation.

When to use it

In-memory supervised training

Train on arrays or tensors

Streaming and batched input pipelines

Pass a PyDataset, dataset, data loader, or generator

Training with validation

Monitor generalization while optimizing

Weighted training

Adjust optimization emphasis per class or example

Interview questions

QWhat does an epoch mean in Model.fit?

fit trains a compiled model for a specified number of epochs. Each epoch normally traverses the provided training data once, unless steps_per_epoch changes that behavior.

Follow-up: How would you train from an infinite dataset? Set steps_per_epoch so Keras knows how many batches constitute each epoch.

QHow do validation_split and validation_data differ?

validation_split takes a fraction of array or tensor inputs for validation, whereas validation_data explicitly supplies validation inputs and targets. The split option is unavailable for dataset inputs.

Follow-up: How would you validate a tf.data.Dataset? Pass it through validation_data and, when needed, control evaluation with validation_steps.

QWhat does Model.fit return?

The method returns a History object containing the recorded loss and metric values for training and validation. Its history attribute maps metric names to values collected across epochs.

Follow-up: How can training be resumed while preserving epoch numbering? Pass the epoch immediately before the restart as initial_epoch; combine it with a larger epochs value.

  • Model.compile
  • Model.evaluate
  • Model.predict
  • keras.callbacks.Callback
  • keras.utils.PyDataset

Source: Model training APIs - Keras. Checked 2026-10-15.