TF-Keras (Legacy Keras 2)

2.21.0 · maintenance · verified Thu Apr 09

TF-Keras is a deep learning API written in Python, running on top of the TensorFlow machine learning platform. It represents the legacy Keras 2, which was the TensorFlow-specific implementation of the Keras API and the default Keras from 2019 to 2023. Version 2.21.0 is current. This package is in maintenance mode, receiving bug fixes and regular releases, but no new features or performance improvements, as development has shifted to Keras 3 (the multi-backend Keras).

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to build, compile, train, and evaluate a simple neural network for classifying MNIST handwritten digits using the `tf_keras` library. It showcases the Sequential API, common layers like Dense and Dropout, and standard training procedures. It also includes a crucial environment variable setting for compatibility with newer TensorFlow versions.

import os
import numpy as np
import tf_keras as keras
from tf_keras import layers

# Set environment variable to ensure Keras 2 is used if TensorFlow >= 2.16 is also installed
os.environ['TF_USE_LEGACY_KERAS'] = '1'

# Load a dataset (MNIST handwritten digits)
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

# Preprocess the data
x_train = x_train.reshape(-1, 28 * 28).astype('float32') / 255.0
x_test = x_test.reshape(-1, 28 * 28).astype('float32') / 255.0

# Define the model using the Sequential API
model = keras.Sequential([
    layers.Dense(128, activation='relu', input_shape=(784,)),
    layers.Dropout(0.2),
    layers.Dense(10, activation='softmax')
])

# Compile the model
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

# Train the model
print("\nTraining the model...")
history = model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1)

# Evaluate the model
print("\nEvaluating the model...")
loss, accuracy = model.evaluate(x_test, y_test)
print(f"Test Loss: {loss:.4f}, Test Accuracy: {accuracy:.4f}")

# Make predictions
predictions = model.predict(x_test[:5])
predicted_classes = np.argmax(predictions, axis=1)
print(f"\nFirst 5 test samples predictions: {predicted_classes}")
print(f"True labels: {y_test[:5]}")

view raw JSON →