Skip to content
TensorFlow

Compile and Train

Compile, fit, and evaluate a Keras model.

By EZ4Code Team
compilefitevaluate

Code

import tensorflow as tf
import numpy as np

model = tf.keras.Sequential([
    tf.keras.layers.Dense(64, activation="relu", input_shape=(10,)),
    tf.keras.layers.Dense(2, activation="softmax"),
])

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"],
)

x = np.random.rand(500, 10).astype("float32")
y = np.random.randint(0, 2, size=(500,))

history = model.fit(x, y, validation_split=0.2, epochs=10,
                    batch_size=32, verbose=2)

# Evaluate and predict
loss, acc = model.evaluate(x, y, verbose=0)
preds = model.predict(x[:5], verbose=0)
print(history.history.keys(), acc)

Explanation

compile() wires an optimizer, a loss function, and metrics into the model before training. fit() runs mini-batch gradient descent, returning a History object whose history dict stores per-epoch loss and metric values. evaluate() reports final metrics and predict() returns forward-pass outputs.

More TensorFlow Snippets