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.
- Environment variable (
KERAS_BACKEND) — highest priority, decided the moment Keras imports. See the first Code block. - Config file (
~/.keras/keras.json) — a persistent per-user default that sets the backend along withfloatx,epsilon, andimage_data_format. The env var overrides it. See the second Code block. - 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.