Keras 安装与配置 #

系统要求 #

text
┌─────────────────────────────────────────────────────────────┐
│                    系统要求                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  操作系统                                                   │
│  ├── Linux (Ubuntu 18.04+, CentOS 7+)                       │
│  ├── macOS 10.14+ (Intel/Apple Silicon)                     │
│  └── Windows 10/11                                          │
│                                                             │
│  Python 版本                                                │
│  └── Python 3.9 - 3.12                                      │
│                                                             │
│  硬件要求                                                   │
│  ├── CPU: 现代 64 位处理器                                  │
│  ├── 内存: 至少 8GB,推荐 16GB+                             │
│  └── GPU: NVIDIA GPU (可选,推荐)                           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

安装方式 #

方式一:pip 安装(推荐) #

bash
pip install keras tensorflow

方式二:conda 安装 #

bash
conda install -c conda-forge keras tensorflow

方式三:虚拟环境安装 #

bash
python -m venv keras-env
source keras-env/bin/activate
pip install keras tensorflow

后端配置 #

Keras 3 支持三种后端:TensorFlow、PyTorch、JAX。

text
┌─────────────────────────────────────────────────────────────┐
│                    后端选择                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  TensorFlow (默认)                                          │
│  ├── 生产部署成熟                                           │
│  ├── TPU 支持                                              │
│  ├── TensorFlow Serving                                    │
│  └── pip install keras tensorflow                          │
│                                                             │
│  PyTorch                                                    │
│  ├── 研究友好                                               │
│  ├── 动态图计算                                             │
│  ├── 调试方便                                               │
│  └── pip install keras torch                               │
│                                                             │
│  JAX                                                        │
│  ├── 高性能计算                                             │
│  ├── 自动向量化                                             │
│  ├── JIT 编译                                              │
│  └── pip install keras jax jaxlib                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

切换后端 #

python
import os

os.environ["KERAS_BACKEND"] = "tensorflow"
os.environ["KERAS_BACKEND"] = "torch"
os.environ["KERAS_BACKEND"] = "jax"

import keras
print(f"当前后端: {keras.backend.backend()}")

配置文件方式 #

创建 ~/.keras/keras.json

json
{
    "backend": "tensorflow",
    "floatx": "float32",
    "epsilon": 1e-07,
    "image_data_format": "channels_last"
}

GPU 配置 #

NVIDIA GPU 要求 #

text
┌─────────────────────────────────────────────────────────────┐
│                    GPU 配置要求                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  硬件                                                       │
│  ├── NVIDIA GPU (计算能力 3.5+)                             │
│  └── 推荐: RTX 3060+, A100, V100                           │
│                                                             │
│  软件                                                       │
│  ├── NVIDIA 驱动 (450.80.02+)                              │
│  ├── CUDA Toolkit (12.x)                                   │
│  └── cuDNN (8.x)                                           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

安装 GPU 支持 #

bash
pip install tensorflow[and-cuda]

验证 GPU #

python
import keras

print(f"可用 GPU 数量: {len(keras.backend.config.visible_devices('GPU'))}")

TensorFlow GPU 配置 #

python
import tensorflow as tf

gpus = tf.config.list_physical_devices('GPU')
if gpus:
    try:
        for gpu in gpus:
            tf.config.experimental.set_memory_growth(gpu, True)
        print(f"已配置 {len(gpus)} 个 GPU")
    except RuntimeError as e:
        print(e)

内存增长配置 #

python
import tensorflow as tf

gpus = tf.config.list_physical_devices('GPU')
if gpus:
    try:
        tf.config.experimental.set_virtual_device_configuration(
            gpus[0],
            [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4096)]
        )
    except RuntimeError as e:
        print(e)

验证安装 #

基础验证 #

python
import keras
import tensorflow as tf

print(f"Keras 版本: {keras.__version__}")
print(f"TensorFlow 版本: {tf.__version__}")
print(f"后端: {keras.backend.backend()}")

运行测试模型 #

python
import keras
import numpy as np

x_train = np.random.random((1000, 20))
y_train = np.random.randint(2, size=(1000, 1))

model = keras.Sequential([
    keras.layers.Dense(64, activation='relu', input_shape=(20,)),
    keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy')

history = model.fit(x_train, y_train, epochs=2, verbose=1)
print("Keras 安装成功!")

常见问题 #

问题 1:CUDA 版本不匹配 #

text
┌─────────────────────────────────────────────────────────────┐
│                    CUDA 版本问题                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  错误信息:                                                   │
│  Could not load dynamic library 'libcudart.so'             │
│                                                             │
│  解决方案:                                                   │
│  1. 检查 CUDA 版本                                          │
│     nvidia-smi                                              │
│                                                             │
│  2. 安装匹配的 CUDA 版本                                    │
│     pip install tensorflow[and-cuda]                        │
│                                                             │
│  3. 或使用 CPU 版本                                         │
│     pip install tensorflow-cpu                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

问题 2:内存不足 #

python
import tensorflow as tf

gpus = tf.config.list_physical_devices('GPU')
if gpus:
    tf.config.experimental.set_virtual_device_configuration(
        gpus[0],
        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=4096)]
    )

问题 3:Apple Silicon (M1/M2) 配置 #

bash
pip install tensorflow-macos tensorflow-metal
python
import tensorflow as tf

print(f"Metal GPU: {tf.config.list_physical_devices('GPU')}")

开发工具推荐 #

Jupyter Notebook #

bash
pip install jupyter
jupyter notebook

VS Code 扩展 #

text
┌─────────────────────────────────────────────────────────────┐
│                    推荐 VS Code 扩展                         │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Python ──────── Python 语言支持                            │
│  Pylance ─────── 类型检查和智能提示                         │
│  Jupyter ─────── Notebook 支持                              │
│  TensorFlow ──── TensorFlow 可视化                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Google Colab #

免费 GPU 资源,适合学习和实验:

python
import tensorflow as tf
print("GPU 可用:", tf.test.is_gpu_available())

完整安装脚本 #

Linux/macOS #

bash
#!/bin/bash

python -m venv keras-env
source keras-env/bin/activate

pip install --upgrade pip
pip install keras tensorflow numpy pandas matplotlib scikit-learn

python -c "import keras; print('Keras 安装成功!')"

Windows #

powershell
python -m venv keras-env
.\keras-env\Scripts\activate

pip install --upgrade pip
pip install keras tensorflow numpy pandas matplotlib scikit-learn

python -c "import keras; print('Keras 安装成功!')"

下一步 #

现在你已经完成了 Keras 的安装配置,接下来学习 第一个模型,开始你的深度学习之旅!

最后更新:2026-04-04