C.W.K.
Stream
Lesson 02 of 08 · published

Setting the Backend

~15 min · backend

Level 0Keras Apprentice
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

Three ways to choose, one that wins

Keras gives you three places to declare a backend, and they form a strict priority chain — knowing the order saves you from the classic "I set it but it didn't take" confusion.

  1. Environment variable (KERAS_BACKEND) — highest priority, decided the moment Keras imports. See the first Code block.
  2. Config file (~/.keras/keras.json) — a persistent per-user default that sets the backend along with floatx, epsilon, and image_data_format. The env var overrides it. See the second Code block.
  3. Programmatic (keras.config.set_backend(), Keras 3.5+) — useful in notebooks and tests, lowest priority. See the third Code block.

The reason the env var sits at the top is timing: the backend is bound at import keras, so anything that can be read before the rest of your code runs gets first say. Pick one method per project and stick with it — mixing them is where the surprises live.

Code

Method 1 — environment variable (set before import)·python
import os
os.environ["KERAS_BACKEND"] = "jax"
import keras  # Must come AFTER setting the env var
Method 2 — config file ~/.keras/keras.json·text
{
    "backend": "jax",
    "floatx": "float32",
    "epsilon": 1e-07,
    "image_data_format": "channels_last"
}
Method 3 — programmatic (Keras 3.5+)·python
import keras
keras.config.set_backend("torch")  # Change backend after import

External links

Exercise

Write three small scripts demonstrating backend selection — one with env var, one with os.environ, one with the config file. Confirm keras.config.backend() shows the chosen backend in each.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.