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

Keras · Function

fit

Model.fit trains a compiled Keras model for a chosen number of epochs using array-, tensor-, or dataset-like inputs. It supports batching, validation, weighting, callbacks, and step controls.

How it works

After compilation, fit divides training data into batches, performs gradient updates, and repeats dataset iteration for the requested epochs. It can accept arrays, tensors, named-input mappings, or supported dataset and generator interfaces, while optionally applying validation, weights, callbacks, and step limits.

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, tensor, mapping, PyDataset, Dataset, DataLoader, or generatorInput samples or an input-producing dataset, loader, or generator.
yarray, tensor, or NoneTarget samples; omit when x yields targets.
batch_sizeinteger or NoneSamples per gradient update; defaults to 32 when unspecified.
epochsintegerNumber of training epochs.
verbose"auto", 0, 1, or 2Verbosity mode.
callbackslist or NoneCallbacks invoked during training.
validation_splitfloatFraction of array or tensor data reserved for validation.
validation_datatuple, Dataset, or NoneExplicit validation data.
shufflebooleanWhether to shuffle training data.
class_weightdict or NoneClass-level weighting factors.
sample_weightarray or NonePer-sample weighting factors.
initial_epochintegerEpoch at which to begin training.

Returns

A History object containing the training history.

Key points

  • The epochs argument sets how many complete dataset iterations the training run performs.
  • batch_size determines how many samples contribute to each gradient update; if omitted, it defaults to 32.
  • validation_split takes a fraction of array or tensor input data for validation, leaving that portion out of training.
  • validation_data explicitly supplies validation inputs and targets, and can be used instead of an automatically held-out split.
  • The return value is a History object containing the training history, including recorded losses and metrics.

Common mistakes

  • When x supplies targets through a dataset, loader, or generator, omit y because targets are obtained from x.

Example: Train a classifier with validation

import keras
import numpy as np

x = np.random.random((100, 4))
y = np.random.randint(2, size=(100, 1))

model = keras.Sequential([
    keras.layers.Dense(8, activation="relu"),
    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)

Compiles a binary classifier and trains it for two epochs while reserving 20% of the arrays for validation.

When to use it

Array-based supervised training

Train a model on in-memory arrays with mini-batches and a held-out fraction.

Streaming or input-pipeline training

Feed batches from a PyDataset, tf.data Dataset, DataLoader, or generator.

Validation monitoring

Monitor generalization during training with explicit validation inputs.

Weighted training

Handle unequal class frequencies or varying example importance.

Interview questions

QWhat does Model.fit do, and what is the role of batch_size?

fit trains a compiled model for a fixed number of epochs. Each epoch is an iteration over the dataset, and batch_size controls the number of samples used per gradient update.

Follow-up: How would you train from a Dataset? Pass the Dataset as x, omit y when it yields targets, and control iteration with steps_per_epoch if needed.

QHow do validation_split and validation_data differ?

validation_split reserves a fraction of array or tensor training data for validation. For dataset-based input, use validation_data because validation_split is not available there.

Follow-up: How can validation frequency be controlled? Set validation_freq to an integer or a container of epoch indices.

QWhat does fit return, and how can training behavior be customized?

fit returns a History object containing records of loss and metrics for the training and validation phases. callbacks can observe training events and alter behavior during the run.

Follow-up: How can class imbalance be addressed? Supply class_weight for per-class weighting or sample_weight for per-example weighting.

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

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