2. 搭建边缘AI开发环境
任务目标
在Raspberry Pi 4B(4GB及以上内存版本)上完成边缘AI开发环境搭建:安装64位操作系统、Python虚拟环境、TensorFlow Lite Runtime及PyTorch Mobile(CPU版),并验证两者均可完成张量计算推理。本案例以树莓派为硬件载体,所有命令均在树莓派终端执行。
环境依赖
- 硬件:Raspberry Pi 4B(建议4GB+内存)、32GB以上microSD卡、电源及网络连接
- 宿主机:任意系统,用于烧录镜像(推荐Raspberry Pi Imager)
- 目标系统:Raspberry Pi OS(64位)Bookworm,基于Debian 12
第一步:烧录64位操作系统
使用Raspberry Pi Imager烧录镜像时,选择 Raspberry Pi OS (64-bit)。烧录前点击Imager右下角齿轮图标,预先启用SSH并设置用户名/密码。烧录完成后插入树莓派启动,通过SSH登录。
第二步:系统更新与基础依赖
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-venv python3-pip git wget
第三步:创建Python虚拟环境
python3 -m venv ~/edge_ai_env
source ~/edge_ai_env/bin/activate
pip install --upgrade pip
第四步:安装TensorFlow Lite Runtime
TensorFlow Lite Runtime仅包含推理所需算子,体积远小于完整TensorFlow,适合边缘设备。从官方pip源直接安装(Bookworm 64位系统已提供ARM64预编译包):
pip install tflite-runtime
第五步:安装PyTorch Mobile(CPU版)
PyTorch Mobile在树莓派上通过pip安装时,需指定ARM64架构的CPU版本wheel包。执行以下命令安装PyTorch 2.x CPU版:
pip install torch --index-url https://download.pytorch.org/whl/cpu
第六步:安装必要依赖库
pip install numpy pillow
第七步:验证安装
创建验证脚本 verify_env.py,同时测试两个框架的张量计算能力:
import numpy as np
# TensorFlow Lite Runtime 验证
try:
import tflite_runtime.interpreter as tflite
interpreter = tflite.Interpreter(model_path="")
print("TFLite Runtime version OK")
except Exception as e:
print(f"TFLite Runtime import failed: {e}")
# PyTorch 验证
import torch
x = torch.rand(3, 4)
y = torch.rand(4, 5)
z = torch.matmul(x, y)
print(f"PyTorch version: {torch.__version__}")
print(f"Matrix multiplication shape: {list(z.shape)}")
print(f"PyTorch CPU inference OK: {z.sum().item() > 0}")
运行验证:
python verify_env.py
验证方法与通过标准
- 通过条件1:脚本无异常输出,显示"TFLite Runtime version OK"
- 通过条件2:PyTorch版本号正常打印,矩阵乘法输出shape为[3,5]
- 通过条件3:
python -c "import torch; print(torch.backends.mps.is_available())"返回False属正常(树莓派无MPS),CPU推理路径可用即可
常见问题排查
- pip安装torch速度慢:确认使用
--index-url https://download.pytorch.org/whl/cpu,该源提供ARM64 wheel,避免源码编译 - tflite-runtime导入报错:确认系统为64位(
uname -m应输出aarch64),32位系统需手动编译 - 虚拟环境无法激活:执行
source ~/edge_ai_env/bin/activate后,命令行前缀应出现(edge_ai_env)
至此,树莓派已具备运行TensorFlow Lite和PyTorch模型的基本推理能力,后续案例可直接在此环境上部署具体模型。