keras

keras-teamApache-2.0活跃维护

面向人类友好的深度学习 API,用 Python 编写,可跑在 TensorFlow、JAX、PyTorch 上,帮开发者快速搭建和训练神经网络。

Deep Learning for humans

v3.15.1发布于 2026-07-29 18:25 UTC64,420star +4 / 7 天19,818fork同步于 2026-11-10 23:19 UTC

怎么上手

由 README 提炼,执行前请确认
pip install keras --upgrade
pip install tensorflow  # 或 jax / torch 作为后端
硬件要求按 README 说明

README 未说明具体显存要求;requirements.txt 默认安装仅 CPU 版本的 TensorFlow、JAX、PyTorch,GPU 支持需改用 requirements-{backend}-cuda.txt 并预装 NVIDIA 驱动;支持从笔记本扩展到 GPU 或 TPU 集群。

纯 CPU 可运行需要 CUDA
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

多后端深度学习框架,同一套 Keras 代码可跑在 JAX、TensorFlow、PyTorch 或 OpenVINO 上

面向人类友好的深度学习 API,用 Python 编写,可跑在 TensorFlow、JAX、PyTorch 上,帮开发者快速搭建和训练神经网络。

核心能力

  • 支持 JAX、TensorFlow、PyTorch、OpenVINO 四种后端切换
  • 用 KERAS_BACKEND 环境变量或 ~/.keras/keras.json 配置后端
  • 可作为 tf.keras 的替代,直接复用现有代码与 .keras 格式
  • 自定义层和模型可在原生 TF、JAX、PyTorch 训练循环中复用
  • 可直接消费 tf.data.Dataset 或 PyTorch DataLoader 数据

容易踩的坑

pip install keras 只装框架本体,必须另装 tensorflow、jax 或 torch 之一作为后端;后端必须在 import keras 前通过 KERAS_BACKEND 或 ~/.keras/keras.json 配置,导入后无法更改;OpenVINO 后端仅支持推理,只能用于 model.predict();各后端有最低版本要求(TensorFlow 2.16.1、JAX 0.4.20、PyTorch 2.6.0、OpenVINO 2026.2.0),且建议每个后端使用独立干净的 Python 环境以避免 CUDA 版本冲突。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v3.15.1
  1. v3.12.4Keras 3.12.42026-07-29 · 2026-07-29 22:19 UTC
    查看更新说明

    Keras 3.12.4

    Keras 3.12.4 is a security patch release that hardens dataset loading and model file handling against insecure deserialization and decompression-bomb attacks.

    Security Fixes

    • Restrict unpickling when loading IMDB and Reuters datasets — Replaces np.load(allow_pickle=True) with a restricted unpickler that only permits numpy array reconstruction, preventing arbitrary code execution via crafted .npz files (CWE-502). (#23047) by @LinZiyuu
    • Verify all intermediary H5 groups when navigating H5 files — Manually resolves nested H5 group paths to verify group types at each step, preventing potential path traversal. (#23168) by @hertschuh
    • Reject decompression-bomb members on the .keras asset extraction path — Adds per-member decompression-ratio checks before extracting .keras archives to disk, preventing disk-exhaustion attacks via crafted archives. (#23101) by @LinZiyuu
    • Restrict unpickling when loading CIFAR datasets — Replaces bare cPickle.load in CIFAR-10/100 batch loading with the numpy-only RestrictedUnpickler, blocking arbitrary code execution via pickle gadgets. (#23252) by @SABITHSAHEB

    Contributors

    Thank you to all the contributors who made this release possible! 🎉

    • @LinZiyuu — Security hardening for IMDB, Reuters, and .keras asset extraction (#23047, #23101)
    • @hertschuh — H5 group verification (#23168)
    • @SABITHSAHEB — CIFAR dataset pickle restriction (#23252)

    Full Changelog: https://github.com/keras-team/keras/compare/v3.12.3...v3.12.4

  2. v3.15.1Keras 3.15.1最新正式版2026-07-29 · 2026-07-29 18:25 UTC

    Release Notes

    Keras 3.15.1 is a patch release containing important security hardening, bug fixes, and Python 3.14 compatibility improvements.

    Security Fixes

    • Restrict unpickling when loading IMDB and Reuters datasets — Prevents insecure deserialization (CWE-502) by replacing bare np.load(allow_pickle=True) with a restricted unpickler that only permits numpy array reconstruction. (#23047) by @LinZiyuu
    • Verify all intermediary H5 groups when navigating H5 files — Manually resolves nested H5 group paths to verify group types at each step, preventing potential path traversal issues. (#23168) by @hertschuh
    • Reject decompression-bomb members on the .keras asset extraction path — Adds per-member decompression-ratio checks before extracting .keras archives to disk, preventing disk-exhaustion attacks via crafted archives. (#23101) by @LinZiyuu
    • Restrict unpickling when loading CIFAR datasets — Replaces bare cPickle.load in CIFAR-10/100 batch loading with the numpy-only RestrictedUnpickler, blocking arbitrary code execution via pickle gadgets. (#23252) by @SABITHSAHEB

    Bug Fixes

    • Refactor _load_state to capture weight store while preserving Keras test passing — Improves model loading efficiency by capturing the weight store into a local variable, and enhances nested container detection in legacy files with isolated failure tracking. (#23226) by @buildwithsuhana
    • Fix TraceContext error for NNX backend — Fixes TraceContext errors when using JAX NNX backend with models like T5 that lack a build method. Skips trace-level checks during symbolic shape inference and handles Flax 0.12 API changes. Fixes #23289. (#23326) by @divyashreepathihalli

    Compatibility

    • Fixes for Python 3.14 — Resolves NotImplementedError boolean coercion changes in Python 3.14 and fixes dimension filtering in shape utilities. (#23259) by @hertschuh

    Contributors

    Thank you to all the contributors who made this release possible! 🎉

    • @LinZiyuu — Security hardening for IMDB, Reuters, and .keras asset extraction (#23047, #23101)
    • @hertschuh — H5 group verification, Python 3.14 compatibility (#23168, #23259)
    • @buildwithsuhana — Model loading refactor (#23226)
    • @SABITHSAHEB — CIFAR dataset pickle restriction (#23252)
    • @divyashreepathihalli — NNX backend TraceContext fix (#23326)

    Full Changelog: https://github.com/keras-team/keras/compare/v3.15.0...v3.15.1

  3. v3.12.32026-06-26 · 2026-06-26 17:52 UTC
    查看更新说明

    Keras 3.12.3 is a security patch release that hardens model saving, loading, and deserialization against a range of attack vectors.

    HDF5 Hardening

    • Eject ExternalLink/SoftLink groups in KerasFileEditor (#22899)
      • Prevents HDF5 external/soft links from being exploited to read arbitrary files during model editing.
    • Reject ExternalLink/SoftLink on legacy .h5 dispatcher (#22900)
      • Extends HDF5 link rejection to the legacy load_weights path for .h5 files.
    • Reject HDF5 shape-bomb datasets (#22975)
      • Blocks HDF5 datasets that declare excessively large shapes to trigger out-of-memory crashes during load_model/load_weights.
    • Reject HDF5 virtual datasets in KerasFileEditor (#22976)
      • Prevents virtual dataset references from being used to access external files.

    Archive Hardening

    • Reject hard-link tar members escaping extraction directory (#22973)
      • Blocks tar hard links whose target resolves outside the extraction root.
    • Reject decompression-bomb archive members (#23010)
      • Detects and rejects .keras archive members that declare far more data than is actually stored, preventing memory exhaustion.
    • Prevent symlink traversal during extraction (#23015)
      • Resolves paths with realpath to prevent symlink-based directory traversal attacks.
    • Reject npz weight bombs (#23016)
      • Validates npz weight members against shape/decompression bombs before allocating memory.
    • Validate DiskIOStore asset paths (#23017)
      • Ensures asset paths stay within the working directory during model saving/loading.
    • Use filter="data" in TarFile.extractall (#23108)
      • Applies Python's built-in tar extraction safety filter on supported versions.

    Deserialization Safety

    • Fix insecure deserialization in dataset utilities (#23026)
      • Closes an insecure deserialization path in dataset utility functions.
    • Explicitly disable pickle in np.load (#23034)
      • Prevents pickle execution when loading NumPy weight files.
    • Make Lambda/TorchModuleWrapper from_config fail closed (#23048)
      • When safe_mode is unset, Lambda and TorchModuleWrapper deserialization now fails closed instead of silently allowing arbitrary code execution.
    • Restrict reloadable APIs (#23115)
      • Expands the list of APIs that should not be part of a deserialized model.

    Full Changelog: https://github.com/keras-team/keras/compare/v3.12.2...v3.12.3

  4. v3.15.02026-06-24 · 2026-06-24 23:38 UTC
    查看更新说明

    Highlights

    • Keras-to-Torch Export: New export_torch enables exporting Keras models to native PyTorch nn.Module format, along with LiteRT (TFLite) export support for the PyTorch backend.
    • Sliding Window Attention: Added sliding_window parameter to MultiHeadAttention and GroupedQueryAttention for efficient long-context attention.
    • Flash / Fused SDPA: Causal-only MHA/GQA now automatically dispatches to Flash Attention (cuDNN SDPA), and the manual attention path correctly applies causal masking.
    • Multi-Optimizer Training: New MultiOptimizer supports assigning different optimizers to sub-networks.
    • New Math Operations: Added unique, pinv, matrix_rank, fabs, fmax, fmin, erfc, dsplit, percentile, nanpercentile, sobel_edges, and ssim (structural similarity) to keras.ops.
    • Security Hardening: Comprehensive hardening of model reloading against HDF5 exploits, tar/zip traversal attacks, insecure deserialization.

    New Features and Operations

    Multi-Backend Operations

    • New NumPy Operations: Added unique, fabs, fmax, fmin, dsplit, erfc, percentile, nanpercentile in keras.ops.numpy.
    • New Linear Algebra Operations: Added pinv (pseudo-inverse) and matrix_rank in keras.ops.linalg.
    • New Image Operations: Added sobel_edges for edge detection and ssim (structural similarity) in keras.ops.image.
    • Negative Axes in Transpose: keras.ops.transpose now supports negative axis values.

    Layers and Attention

    • Sliding Window Attention: MultiHeadAttention and GroupedQueryAttention layers support the sliding_window parameter for efficient long-sequence processing.
    • Flash Attention Engagement: Causal-only attention in MHA/GQA now uses Flash SDPA for significant speedups.
    • Fused Bidirectional LSTM/GRU: JAX backend now fuses Bidirectional LSTM into a single cuDNN call; fused bidirectional GRU added for Torch backend.
    • CTC Beam Search Decoder: Added CTC beam search decoding for the Torch backend.

    Training and Optimizers

    • MultiOptimizer: Supports training sub-networks with different optimizers.
    • SKLearn Classifier: Added predict_proba method to SKLearnClassifier.

    Export and Deployment

    • Keras-to-Torch Export: Export Keras models to native PyTorch nn.Module via model.export(..., format="torch").
    • LiteRT (TFLite) Export for PyTorch: Added LiteRT export support for models using the PyTorch backend.
    • LiteRT Compatibility Fix: Fixed LiteRT export for Keras 3 + TF 2.20 + Python 3.13.
    • ONNX Export: Support for dict/list inputs in Torch ONNX export; documented static input signature requirement for LiteRT PyTorch export.

    Distribution and Parallelism

    • ModelParallel Improvements: Defined contiguous replica-group data shard ID convention; added distribution information (num_processes, num_model_replicas, data_shard_id).
    • Initializer Distribution Layout: Initializers can now handle the distribution layout directly with JAX.
    • TF Dataset Distribution: Refactored TF dataset distribution with centralized sharding routing; fixed data distribution for model training in JAX.

    OpenVINO Backend Support

    The OpenVINO backend received continued improvements:

    • New Operations: Implemented glu, sparsemax, gaussian_blur, logdet, cholesky, lu_factor, erfc, segment_min, segment_prod, percentile, nanmedian, nanpercentile, unique, flash_attn, greedy ctc_decode, solve_triangular, compute_homography_matrix, and image transforms (affine, perspective, elastic).
    • Opset Upgrades: Upgraded to opset16 for select operations and full upgrade.
    • Fixes: Dynamic/symbolic shape handling, mask propagation, random seed determinism, dropout during predict, Lanczos interpolation in resize, dynamic batch shape propagation, and improved efficiency using native op
  5. v3.14.12026-05-07 · 2026-05-07 22:22 UTC
    查看更新说明

    Saving & Reloading

    • Harden path and link resolution when extracting files from archives (#22839)
      • Fixed link resolution bug when validating links extracted from TAR archives.
      • Fixed path confusion bug when validating files extracted from ZIP and TAR archives (including .keras files).
      • Added path validation when extracting assets from Orbax checkpoints.
    • Harden H5 validation code and apply it to legacy .h5 files (#22801)
      • Disallow external links and virtual datasets in H5 files.
      • Also apply all the validation to the legacy .h5 file extraction.
    • Improve validation and error reporting in functional model deserialization (#22800)
      • Detect loops in the graph when deserializing a functional model.
      • Improve error reporting for missing nodes in the graph.

    Other Fixes

    • Fix data sharding logic in ModelParallel (#22179)
    • Fix regression with metrics passed to compile (#22663)
      • Fixed a regression introduced in #22308 where y_pred (as a list) and y_true (as a dict with keys matching Functional model output names) were not ordered identically and could be paired incorrectly.
    • Fix regression preventing compilation with the L1L2 regularizer (#22629)
    • Fix test compatibility with JAX 0.10.0 (#22694)

    Full Changelog: https://github.com/keras-team/keras/compare/v3.14.0...v3.14.1

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Keras 3: Deep Learning for Humans

    Keras 3 is a multi-backend deep learning framework, with support for JAX, TensorFlow, PyTorch, and OpenVINO (for inference-only). Effortlessly build and train models for computer vision, natural language processing, audio processing, timeseries forecasting, recommender systems, etc.

    • Accelerated model development: Ship deep learning solutions faster thanks to the high-level UX of Keras and the availability of easy-to-debug runtimes like PyTorch or JAX eager execution.
    • State-of-the-art performance: By picking the backend that is the fastest for your model architecture (often JAX!), leverage speedups ranging from 20% to 350% compared to other frameworks. Benchmark here.
    • Datacenter-scale training: Scale confidently from your laptop to large clusters of GPUs or TPUs.

    Join nearly three million developers, from burgeoning startups to global enterprises, in harnessing the power of Keras 3.

    Installation

    Install with pip

    Keras 3 is available on PyPI as keras. Note that Keras 2 remains available as the tf-keras package.

    1. Install keras:
    pip install keras --upgrade
    
    1. Install backend package(s).

    To use keras, you should also install the backend of choice: tensorflow, jax, or torch. Additionally, The openvino backend is available with support for model inference only.

    1. (Optional) Install remote file access support.

    To save to and load from Google Cloud Storage (gs:// paths) without TensorFlow, install the gcs extra:

    pip install "keras[gcs]"
    

    Local installation

    Minimal installation

    Keras 3 is compatible with Linux and macOS systems. For Windows users, we recommend using WSL2 to run Keras. To install a local development version:

    1. Install dependencies:
    pip install -r requirements.txt
    
    1. Run installation command from the root directory.
    python pip_build.py --install
    
    1. Run API generation script when creating PRs that update keras_export public APIs:
    ./shell/api_gen.sh
    

    Backend Compatibility Table

    The following table lists the minimum supported versions of each backend for the latest stable release of Keras (v3.x):

    BackendMinimum Supported Version
    TensorFlow2.16.1
    JAX0.4.20
    PyTorch2.6.0
    OpenVINO2026.2.0
    Adding GPU support

    The requirements.txt file will install a CPU-only version of TensorFlow, JAX, and PyTorch. For GPU support, we also provide a separate requirements-{backend}-cuda.txt for TensorFlow, JAX, and PyTorch. These install all CUDA dependencies via pip and expect a NVIDIA driver to be pre-installed. We recommend a clean Python environment for each backend to avoid CUDA version mismatches. As an example, here is how to create a JAX GPU environment with conda:

    conda create -y -n keras-jax python=3.10
    conda activate keras-jax
    pip install -r requirements-jax-cuda.txt
    python pip_build.py --install
    

    Configuring your backend

    You can export the environment variable KERAS_BACKEND or you can edit your local config file at ~/.keras/keras.json to configure your backend. Available backend options are: "tensorflow", "jax", "torch", "openvino". Example:

    export KERAS_BACKEND="jax"
    

    In Colab, you can do:

    import os
    
    os.environ["KERAS_BACKEND"] = "jax"
    
    import keras
    

    Note: The backend must be configured before importing keras, and the backend cannot be changed after the package has been imported.

    Note: The OpenVINO backend is an inference-only backend, meaning it is designed only for running model predictions using model.predict() method.

    Backwards compatibility

    Keras 3 is intended to work as a drop-in replacement for tf.keras (when using the TensorFlow backend). Just take your existing tf.keras code, make sure that your calls to model.save() are using the up-to-date .keras format, and you're done.

    If your tf.keras model does not include custom components, you can start running it on top of JAX or PyTorch immediately.

    If it does include custom components (e.g. custom layers or a custom train_step()), it is usually possible to convert it to a backend-agnostic implementation in just a few minutes.

    In addition, Keras models can consume datasets in any format, regardless of the backend you're using: you can train your models with your existing tf.data.Dataset pipelines or PyTorch DataLoaders.

    Why use Keras 3?

    • Run your high-level Keras workflows on top of any framework -- benefiting at will from the advantages of each framework, e.g. the scalability and performance of JAX or the production ecosystem options of TensorFlow.
    • Write custom components (e.g. layers, models, metrics) that you can use in low-level workflows in any framework.
      • You can take a Keras model and train it in a training loop written from scratch in native TF, JAX, or PyTorch.
      • You can take a Keras model and use it as part of a PyTorch-native Module or as part of a JAX-native model function.
    • Make your ML code future-proof by avoiding framework lock-in.
    • As a PyTorch user: get access to power and usability of Keras, at last!
    • As a JAX user: get access to a fully-featured, battle-tested, well-documented modeling and training library.

    Read more in the Keras 3 release announcement.