The model.fit() function trains a machine learning model by showing it data many times. It helps the model learn patterns to make good predictions.
model.fit() training loop in TensorFlow
model.fit(x, y, epochs=10, batch_size=32, validation_data=None, callbacks=None)
x is the input data, and y is the target labels.
epochs is how many times the model sees the whole dataset.
x_train and y_train for 5 full passes.model.fit(x_train, y_train, epochs=5)model.fit(x_train, y_train, epochs=10, batch_size=64)
model.fit(x_train, y_train, epochs=10, validation_data=(x_val, y_val))This code creates a simple neural network to classify data into 3 groups. It trains the model for 3 epochs with batches of 16 samples. After training, it prints the final accuracy on the training data.
import tensorflow as tf from tensorflow.keras import layers, models # Create simple model model = models.Sequential([ layers.Dense(10, activation='relu', input_shape=(4,)), layers.Dense(3, activation='softmax') ]) # Compile model with loss and optimizer model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Sample data: 150 samples, 4 features, 3 classes import numpy as np x_train = np.random.random((150, 4)) y_train = np.random.randint(0, 3, 150) # Train model history = model.fit(x_train, y_train, epochs=3, batch_size=16) # Print training accuracy after last epoch print(f"Final training accuracy: {history.history['accuracy'][-1]:.4f}")
The batch_size controls how many samples the model looks at before updating its knowledge.
Using validation_data helps you see if the model is learning well or just memorizing.
You can add callbacks to stop training early or save the best model.
model.fit() trains your model by showing data multiple times.
You can control training length with epochs and speed with batch_size.
Validation data helps check if the model is learning properly during training.