Most Keras projects pass data through the same lifecycle before the model is ready for larger datasets or deployment code. A compiled model trains with fit(), checks held-out data with evaluate(), and returns inference arrays with predict().
The script uses the standalone Keras package with the JAX backend and small NumPy arrays. That keeps the focus on the built-in model methods instead of dataset pipeline construction, checkpointing, or saved-model loading.
The same sequence still applies after changing the model architecture, loss function, or input source. fit() returns a History object, evaluate() can return a metric dictionary, and predict() returns batched NumPy arrays whose first dimension matches the requested samples.
import os os.environ["KERAS_BACKEND"] = "jax" import keras import numpy as np keras.utils.set_random_seed(7) rng = np.random.default_rng(7) x_train = rng.uniform(size=(64, 2)).astype("float32") y_train = (x_train[:, 0] > x_train[:, 1]).astype("float32") x_test = rng.uniform(size=(16, 2)).astype("float32") y_test = (x_test[:, 0] > x_test[:, 1]).astype("float32")
The KERAS_BACKEND value must be set before import keras. Use tensorflow or torch only when that backend is installed in the same environment.
Related: How to install Keras with pip
Related: How to set the Keras backend
model = keras.Sequential( [ keras.layers.Input(shape=(2,)), keras.layers.Dense(8, activation="relu"), keras.layers.Dense(1, activation="sigmoid"), ] )
model.compile( optimizer=keras.optimizers.Adam(learning_rate=0.05), loss=keras.losses.BinaryCrossentropy(), metrics=[keras.metrics.BinaryAccuracy(name="accuracy")], )
BinaryAccuracy matches the single sigmoid output and binary target array used in the script.
Related: How to compile a model in Keras
history = model.fit( x_train, y_train, validation_data=(x_test, y_test), epochs=25, batch_size=8, verbose=0, )
validation_data records val_loss and val_accuracy in the returned History object without changing the training arrays.
results = model.evaluate(x_test, y_test, verbose=0, return_dict=True) predictions = model.predict(x_test[:4], verbose=0) print(f"backend: {keras.backend.backend()}") print("history keys:", ", ".join(sorted(history.history.keys()))) print(f"epochs completed: {len(history.history['loss'])}") print(f"test loss: {results['loss']:.3f}") print(f"test accuracy: {results['accuracy']:.3f}") print(f"prediction shape: {predictions.shape}") rounded = ", ".join(f"{value:.3f}" for value in predictions[:3, 0]) print(f"first prediction values: [{rounded}]")
return_dict=True names the evaluation outputs, which avoids relying on metric order when reading the result.
$ python train_evaluate_predict.py backend: jax history keys: accuracy, loss, val_accuracy, val_loss epochs completed: 25 test loss: 0.042 test accuracy: 1.000 prediction shape: (4, 1) first prediction values: [0.014, 1.000, 0.886]