{"id":2311,"library":"tf-keras","title":"TF-Keras (Legacy Keras 2)","description":"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).","status":"maintenance","version":"2.21.0","language":"en","source_language":"en","source_url":"https://github.com/keras-team/tf-keras","tags":["deep learning","machine learning","neural networks","keras","tensorflow","legacy"],"install":[{"cmd":"pip install tf-keras","lang":"bash","label":"Install TF-Keras"}],"dependencies":[{"reason":"TF-Keras is the TensorFlow-specific implementation of Keras, requiring TensorFlow to run.","package":"tensorflow"}],"imports":[{"note":"Direct `import keras` (without installing tf_keras and setting TF_USE_LEGACY_KERAS=1) will import Keras 3, which is multi-backend and has potential API differences. `tf_keras` is the dedicated legacy Keras 2 package.","wrong":"import keras","symbol":"keras","correct":"import tf_keras as keras"},{"note":"While `from tensorflow.keras` used to be the standard for Keras 2, with TensorFlow 2.16+ it now defaults to Keras 3. For explicit Keras 2 usage, import directly from the `tf_keras` package.","wrong":"from tensorflow.keras import models, layers","symbol":"Model, layers","correct":"from tf_keras import models, layers"}],"quickstart":{"code":"import os\nimport numpy as np\nimport tf_keras as keras\nfrom tf_keras import layers\n\n# Set environment variable to ensure Keras 2 is used if TensorFlow >= 2.16 is also installed\nos.environ['TF_USE_LEGACY_KERAS'] = '1'\n\n# Load a dataset (MNIST handwritten digits)\n(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n\n# Preprocess the data\nx_train = x_train.reshape(-1, 28 * 28).astype('float32') / 255.0\nx_test = x_test.reshape(-1, 28 * 28).astype('float32') / 255.0\n\n# Define the model using the Sequential API\nmodel = keras.Sequential([\n    layers.Dense(128, activation='relu', input_shape=(784,)),\n    layers.Dropout(0.2),\n    layers.Dense(10, activation='softmax')\n])\n\n# Compile the model\nmodel.compile(\n    optimizer='adam',\n    loss='sparse_categorical_crossentropy',\n    metrics=['accuracy']\n)\n\n# Train the model\nprint(\"\\nTraining the model...\")\nhistory = model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1)\n\n# Evaluate the model\nprint(\"\\nEvaluating the model...\")\nloss, accuracy = model.evaluate(x_test, y_test)\nprint(f\"Test Loss: {loss:.4f}, Test Accuracy: {accuracy:.4f}\")\n\n# Make predictions\npredictions = model.predict(x_test[:5])\npredicted_classes = np.argmax(predictions, axis=1)\nprint(f\"\\nFirst 5 test samples predictions: {predicted_classes}\")\nprint(f\"True labels: {y_test[:5]}\")","lang":"python","description":"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."},"warnings":[{"fix":"For new projects, consider migrating to Keras 3 (`pip install keras`). To explicitly use TF-Keras (Keras 2) with TensorFlow >= 2.16, install `tf-keras` and set the environment variable `TF_USE_LEGACY_KERAS=1` before importing TensorFlow or Keras. Alternatively, import directly from `tf_keras` as shown in the imports section.","message":"TF-Keras (Keras 2) is in maintenance mode. New features are developed in Keras 3. If you install TensorFlow >= 2.16, `tf.keras` will default to Keras 3, which has a different API and multi-backend support. This can cause compatibility issues with code expecting Keras 2 behavior.","severity":"breaking","affected_versions":"TensorFlow >= 2.16.0"},{"fix":"Upgrade your Python environment to Python 3.10 or newer.","message":"Python 3.9 support has been removed as of `tf-keras` version 2.21.0.","severity":"breaking","affected_versions":"tf-keras == 2.21.0 and later"},{"fix":"Migrate to `SciKeras` for Scikit-learn compatible Keras models.","message":"The Keras Scikit-learn API wrappers (`KerasClassifier` and `KerasRegressor`) were removed starting with TensorFlow 2.13 and compatible `tf-keras` versions.","severity":"deprecated","affected_versions":"tf-keras compatible with TensorFlow >= 2.13.0"},{"fix":"When saving models, explicitly specify `save_format=\"h5\"` if you need to retain the H5 format for a `.keras` file: `model.save('my_model.keras', save_format='h5')`. For general use, consider adopting the Keras v3 saving format or `model.export()` for inference.","message":"The default model saving format (`.keras` extension) in Keras 2 is now the Keras v3 format, not the H5 format. This might break workflows that manually inspected or modified H5 files saved with a `.keras` extension.","severity":"gotcha","affected_versions":"tf-keras compatible with TensorFlow >= 2.13.0"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}