In-memory supervised training
Train on arrays or tensors
Keras · Module
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.
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.
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,
)| Name | Type | Description |
|---|---|---|
x | array-like, tensor, dict, or dataset-like | Training inputs, such as arrays, tensors, dictionaries, PyDataset instances, datasets, data loaders, or generators. |
y | array-like, tensor, or None | Target values; omit when targets are yielded by x. |
batch_size | integer or None | Samples per gradient update; defaults to 32 when omitted. |
epochs | integer | Number of epochs to train. |
verbose | auto, 0, 1, or 2 | Verbosity mode. |
callbacks | list or None | Callbacks invoked during training. |
validation_split | float | Fraction of array or tensor data reserved for validation. |
validation_data | tuple or dataset-like | Data used for validation. |
shuffle | boolean | Whether to shuffle training data. |
class_weight | dict or None | Class weighting for training. |
sample_weight | array-like or None | Per-sample weighting for training. |
initial_epoch | integer | Epoch at which to begin training. |
A History object containing the training history, including loss and metric values by epoch.
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.steps_per_epoch is set.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.
Train on arrays or tensors
Pass a PyDataset, dataset, data loader, or generator
Monitor generalization while optimizing
Adjust optimization emphasis per class or example
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.
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.
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.compileModel.evaluateModel.predictkeras.callbacks.Callbackkeras.utils.PyDataset