C.W.K.
Stream
Lesson 05 of 08 · published

model.fit()

~9 min · training

Level 0Keras Apprentice
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

One call, the whole training loop

model.fit() is where everything you configured in compile() finally runs. Under one call hides the entire loop — batching, the forward pass, the loss, backprop, the optimizer step, metric accumulation, and the callback bus firing at every boundary. The arguments in the Code section are the knobs you'll reach for most: epochs is how many times you sweep the data, batch_size is how many samples feed each gradient step, and validation is wired in one of two ways.

The arguments that actually change outcomes

Use validation_split=0.2 to carve a validation set off the tail of your training data when you don't have a dedicated one; pass validation_data=(x_val, y_val) when you do — that's the honest choice, because validation_split takes the last slice without shuffling, so a sorted dataset gives you a garbage validation set. class_weight is the lever for imbalanced data: weight the rare class up so its mistakes count more, instead of letting the model win by always predicting the majority.

Whatever you pass, fit() hands back a History object. Its .history attribute is a dict of per-epoch lists — loss, val_loss, every metric and its val_ twin. That's your entire learning curve, and the next lesson's callbacks are what act on it automatically while training runs.

Code

model.fit() with its key arguments and the History object·python
history = model.fit(
    x_train, y_train,
    epochs=20,                 # Number of passes through the data
    batch_size=32,              # Samples per gradient update
    validation_split=0.2,       # Use 20% of training data for validation
    # OR: validation_data=(x_val, y_val),
    class_weight={0: 1.0, 1: 5.0},  # For imbalanced data
    callbacks=[...],              # List of callback instances
)

# history.history contains loss/metric values per epoch
print(history.history["loss"])         # [0.83, 0.54, 0.41, ...]
print(history.history["val_accuracy"]) # [0.72, 0.81, 0.85, ...]

External links

Exercise

Train MNIST for 10 epochs. Save history.history. Plot training/validation loss and accuracy on two subplots. Identify the epoch where validation loss starts climbing.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.