Ubuntu下Caffe编译安装全版本兼容指南

本文系统梳理Ubuntu 18.04–24.04各版本中Caffe编译安装的关键障碍,涵盖底层依赖(OpenCV、HDF5、Boost)版本校验、Python ABI兼容性(NumPy≤1.21.6)、CUDA/cuDNN组合约束、Makefile.config精准配置(路径、GCC标准、GPU开关)、典型报错根因定位(链接失败、ABI断裂、CUDA语言鸿沟)及四层验证方法。强调降级哲学、单线程调试、clean彻底性与Docker隔离等实战潜规则。

1. 为什么Caffe在Ubuntu上的安装至今仍是“玄学”级体验

“全网最全”这个后缀,不是标题党,而是无数人在终端里反复敲下 make all 又看着它报错时,用血泪写下的共识。我第一次在Ubuntu 20.04上装Caffe,是在一个没有GPU的旧笔记本上——本意是跑个LeNet做手写数字识别的Demo,结果卡在 protobuf 版本冲突上整整三天。后来在某高校实验室带学生做图像处理课程设计时,发现同一份 Makefile.config ,在A同学的Ubuntu 18.04上编译通过,在B同学刚重装的22.04上却连 hdf5 头文件都找不到。这不是偶然,而是Caffe这个诞生于深度学习爆发初期的框架,其构建逻辑与现代Linux发行版演进节奏之间,存在一种结构性错位。

Caffe的核心矛盾在于:它极度依赖底层C++生态的确定性,而Ubuntu的包管理、Python环境、CUDA工具链又天然追求向前兼容与版本滚动。比如 libhdf5-dev 在18.04中默认是1.10.4,在20.04中升到1.10.6,在22.04中直接跳到1.13.0——而Caffe源码里硬编码的 #include <hdf5.h> 路径,在1.13.0中已被移至 <hdf5/hdf5.h> 。这种微小的路径偏移,不会触发语法错误,却会让链接器在生成 libcaffe.so 时静默失败,最终在运行时抛出 undefined symbol: H5Fopen 。更隐蔽的是Python接口问题:Caffe的 pycaffe 模块要求 numpy 必须是1.16.x,但Ubuntu 22.04的 apt install python3-numpy 默认装1.23.x,二者ABI不兼容,导致 import caffe 直接段错误。

所以,所谓“全网最全”,本质是把所有可能断裂的环节都预先拧紧。它不承诺一次成功,但保证你遇到的每一个报错,都能在本文中找到对应位置的根因分析和可验证的修复动作。这不是教科书式的线性流程,而是一张覆盖了Ubuntu 18.04至24.04主流版本、CPU/GPU双模式、Python2/Python3兼容性的故障地图。你不需要记住所有命令,只需要在报错信息里抓取关键词(比如 hdf5 、 protobuf 、 boost 、 nvcc ),然后跳转到对应章节,执行三步操作:确认当前状态 → 执行精准修复 → 验证修复效果。接下来的内容,就是这张地图的完整展开。

2. 环境准备:不是“照着做”,而是“先看清自己站在哪”

安装Caffe的第一步,从来不是下载代码,而是对当前Ubuntu系统进行一次外科手术式的诊断。很多教程直接从 git clone 开始,这就像没量血压就开降压药——你根本不知道自己的系统是否已经“高血压”(版本冲突)或“低血糖”(依赖缺失)。我带过的几十个学生项目里,超过70%的失败源于跳过了这一步。下面的操作,请逐行执行并记录输出,它们将决定你后续是走高速路还是泥泞小道。

2.1 系统基础信息锚定

首先确认你的Ubuntu版本和架构,这是所有决策的起点:

lsb_release -a
uname -m

关键看两点: Codename (如 focal 代表20.04, jammy 代表22.04)和 Architecture ( x86_64 是标准, aarch64 则需特殊处理)。注意:不要相信 cat /etc/os-release 里的 VERSION_ID ,某些云服务器镜像会篡改该字段, lsb_release -a 才是权威。

提示:如果你看到 Codename: noble (24.04),请立刻停在这里。截至2024年中,Caffe官方master分支尚未适配GCC 13和glibc 2.39,强行编译大概率在 make all 第37%处因 std::string_view 符号未定义而崩溃。建议降级到22.04 LTS或使用Docker隔离环境。

2.2 底层依赖的“三重校验”

Caffe的三大基石依赖—— protobuf 、 hdf5 、 boost ——必须满足版本区间且头文件路径一致。执行以下命令,获取精确版本号:

# protobuf:Caffe要求3.1.0 ≤ version < 3.20.0(3.20.0+引入C++20特性,与Caffe C++11不兼容)
protoc --version
dpkg -l | grep libprotobuf

# hdf5:要求1.10.x(1.10.4~1.10.7最稳),1.12.x以上需手动修改源码路径
h5cc --version
dpkg -l | grep libhdf5

# boost:要求1.58.0 ≤ version ≤ 1.71.0(1.72.0+移除了`boost::filesystem::path::operator/`,Caffe调用此API)
dpkg -l | grep libboost-dev

这里有个关键陷阱: dpkg -l 显示的包名可能包含 dev 后缀(如 libprotobuf-dev ),但 protoc --version 显示的是 protoc 编译器版本。二者必须严格匹配!例如, libprotobuf-dev 是3.12.4,但 protoc 是3.21.12,说明你通过 conda 或源码安装了新版 protoc ,而系统库仍是旧版——这会导致 make all 时 protoc 生成的 .pb.cc 文件与链接的 libprotobuf.so ABI不匹配,报错 undefined reference to 'google::protobuf::internal::WireFormatLite::WriteString' 。

2.3 Python环境的“静默杀手”

Caffe的Python接口( pycaffe )对Python环境极其敏感。执行以下检查:

python3 --version
python3 -c "import numpy; print(numpy.__version__)"
python3 -c "import setuptools; print(setuptools.__version__)"

核心约束:

  • numpy 必须≤1.21.6(1.22.0+移除了 numpy.distutils ,而Caffe的 setup.py 仍依赖它)
  • setuptools 必须≥45.0.0(太旧无法解析 pyproject.toml )

如果 numpy 版本超标, 不要 用 pip install numpy==1.21.6 暴力降级——这会破坏系统Python的其他包。正确做法是创建独立虚拟环境:

sudo apt install python3-venv
python3 -m venv ~/caffe_env
source ~/caffe_env/bin/activate
pip install --upgrade pip
pip install numpy==1.21.6 setuptools==58.1.0

注意:激活虚拟环境后, which python3 必须指向 ~/caffe_env/bin/python3 ,否则后续 make pycaffe 会链接到系统Python,导致 import caffe 失败。

2.4 CUDA与cuDNN的“版本锁链”

如果你需要GPU加速,CUDA和cuDNN的版本组合是另一重地狱。Caffe官方文档只说“支持CUDA 10.0+”,但实际测试表明:

Ubuntu版本 推荐CUDA cuDNN版本 关键原因
18.04 10.2 7.6.5 CUDA 10.2是最后一个支持GCC 7.5的版本,与Ubuntu 18.04默认编译器完美匹配
20.04 11.2 8.1.0 CUDA 11.2支持GCC 9.3,避免 nvcc 与 g++ 版本不匹配导致的 __builtin_assume_aligned 未声明错误
22.04 11.8 8.6.0 CUDA 11.8是最后一个支持Ubuntu 22.04内核5.15的版本,更高版本需手动编译NVIDIA驱动

验证CUDA安装:

nvcc --version
nvidia-smi  # 查看驱动版本,必须≥CUDA对应最低要求(如CUDA 11.8要求驱动≥520.61.05)

cuDNN的验证不能只看 /usr/include/cudnn.h ,因为很多教程用 tar 解压方式安装,容易漏掉 lib 目录。执行:

ls -l /usr/lib/x86_64-linux-gnu/libcudnn*
# 正确应有 libcudnn.so.8 -> libcudnn.so.8.6.0 和 libcudnn_static.a

如果只有 libcudnn.so.8 软链接而无真实文件,说明cuDNN未正确安装, make all 会在 src/caffe/layers/cudnn_conv_layer.cpp 处因找不到 cudnnConvolutionForward 符号而失败。

3. Makefile.config定制:每一行都是一个决策点

Caffe的 Makefile.config 不是配置文件,而是一份C++编译器的“作战指令集”。网上流传的模板往往直接复制粘贴,但其中每一行开关都对应着底层依赖的物理存在。我见过最离谱的案例:某开发者在 Makefile.config 中启用了 USE_CUDNN := 1 ,但系统根本没装cuDNN, make all 却能通过——因为Caffe的Makefile有容错机制,当检测不到cuDNN头文件时,会自动关闭该选项,但后续在运行时调用 CuDNNConvolutionLayer 就会崩溃。所以,定制 Makefile.config 的本质,是让编译器“诚实”地暴露所有依赖缺口。

3.1 基础路径映射:从“猜”到“确认”

打开 Makefile.config ,第一组需要修改的是 INCLUDE_DIRS 和 LIBRARY_DIRS 。不要凭记忆填写,用 find 命令精准定位:

# 查找hdf5头文件真实路径(Ubuntu 22.04中通常是/usr/include/hdf5/serial/)
find /usr/include -name "hdf5.h" 2>/dev/null

# 查找protobuf头文件(通常在/usr/include/google/protobuf/)
find /usr/include -name "protobuf.h" 2>/dev/null

# 查找boost头文件(通常在/usr/include/boost/)
find /usr/include -name "boost.hpp" 2>/dev/null

根据搜索结果,修改 Makefile.config 中的路径:

# 原始(错误):INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include
# 正确(Ubuntu 22.04):
INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/include/hdf5/serial/ /usr/include/google/protobuf/ /usr/include/boost/

# 原始(错误):LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib
# 正确(需确认libhdf5.so位置):
LIBRARY_DIRS := $(PYTHON_LIB) /usr/lib/x86_64-linux-gnu/hdf5/serial/ /usr/lib/x86_64-linux-gnu/

关键细节: /usr/lib/x86_64-linux-gnu/hdf5/serial/ 这个路径在Ubuntu 22.04中是 libhdf5-dev 包安装的专用库目录,里面包含 libhdf5.so 和 libhdf5_hl.so 。如果漏掉这个路径, make all 会报 cannot find -lhdf5_hl 。

3.2 编译器与标准:GCC版本的“隐形墙”

Caffe要求C++11标准,但不同Ubuntu版本的GCC默认标准不同。Ubuntu 18.04的GCC 7.5默认C++14,Ubuntu 22.04的GCC 11.2默认C++17。Caffe源码中大量使用 auto 和 nullptr ,这些在C++11中合法,但在C++17中某些模板推导规则变化可能导致编译失败。因此,必须显式指定标准:

# 在COMMON_FLAGS中添加(不是替换!)
COMMON_FLAGS += -std=c++11

更隐蔽的问题是 nvcc 与 g++ 的版本协同。CUDA 11.2的 nvcc 要求主机编译器为GCC 9.3,但Ubuntu 20.04默认GCC 9.4。此时 nvcc 会发出警告 Unsupported GCC version ,但继续编译——直到链接阶段才报错 undefined reference to 'std::__cxx11::basic_string' 。解决方案是强制 nvcc 使用GCC 9.3:

sudo apt install gcc-9 g++-9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 90 --slave /usr/bin/g++ g++ /usr/bin/g++-9

然后在 Makefile.config 中指定:

# CUDA compiler
NVCC := /usr/local/cuda/bin/nvcc -ccbin /usr/bin/gcc-9

3.3 Python接口的“ABI契约”

pycaffe 的成败,取决于 Makefile.config 中Python相关路径与当前激活环境的绝对一致。假设你已按2.3节创建了 ~/caffe_env 虚拟环境,执行:

# 获取Python头文件路径
python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())"

# 获取Python库路径
python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"

输出类似:

/home/yourname/caffe_env/include/python3.10
/home/yourname/caffe_env/lib/python3.10/site-packages

将这些路径填入 Makefile.config :

# Uncomment to use Python 3 (default is Python 2)
USE_PYTHON3 := 1

# Python (general)
PYTHON_INCLUDE := /home/yourname/caffe_env/include/python3.10 \
                  /home/yourname/caffe_env/lib/python3.10/site-packages/numpy/core/include

# Python library
PYTHON_LIB := /home/yourname/caffe_env/lib

注意: PYTHON_INCLUDE 第二行必须包含 numpy 的 core/include 路径,否则 caffe.proto 中 repeated float data = 1; 会被 protoc 生成错误的 std::vector<float> 类型,导致 blob.cpp 编译失败。

3.4 GPU模式的“条件编译开关”

启用GPU支持不是简单地把 CPU_ONLY := 1 改成 0 。你需要根据CUDA和cuDNN的实际安装情况,分层开启:

# 如果CUDA已安装且nvcc可用,取消注释
USE_CUDNN := 1

# 如果仅需CUDA基础加速(无cuDNN),保留此行
# USE_CUDNN := 0

# 如果使用Intel CPU,可启用MKL(但需额外安装Intel MKL)
# USE_MKL := 1

# 如果系统有多个GPU,启用NCCL(用于多机训练)
# USE_NCCL := 1

最关键的一步是验证cuDNN头文件是否存在:

ls /usr/include/cudnn.h
# 若存在,说明cuDNN头文件已就位;若不存在,即使设置了USE_CUDNN := 1,编译也会跳过cuDNN代码

如果 /usr/include/cudnn.h 不存在,但cuDNN库文件在 /usr/lib/x86_64-linux-gnu/ ,说明你用 tar 解压安装,需手动创建符号链接:

sudo ln -sf /usr/lib/x86_64-linux-gnu/cudnn.h /usr/include/cudnn.h

4. 编译过程排错:从报错信息反向定位根因

make all 是Caffe安装的“压力测试”,它会暴露所有前期准备的漏洞。网上教程常把报错归为“环境问题”,但实际每个错误都有唯一根因。下面按报错信息关键词分类,给出可复现的排查链路。记住:不要跳过任何中间步骤,每个 echo 和 grep 都是在缩小问题范围。

4.1 hdf5 相关报错:路径、版本、链接的三重奏

典型报错:

/usr/bin/ld: cannot find -lhdf5_hl
/usr/bin/ld: cannot find -lhdf5

这不是“没装hdf5”,而是链接器找不到 libhdf5_hl.so 。执行诊断:

# 1. 确认libhdf5-dev是否安装
dpkg -l | grep libhdf5-dev

# 2. 查找libhdf5_hl.so的真实位置
find /usr -name "libhdf5_hl.so*" 2>/dev/null

# 3. 检查Makefile.config中的LIBRARY_DIRS是否包含该路径
grep "LIBRARY_DIRS" Makefile.config

如果 find 返回 /usr/lib/x86_64-linux-gnu/hdf5/serial/libhdf5_hl.so.100 ,但 LIBRARY_DIRS 中没有 /usr/lib/x86_64-linux-gnu/hdf5/serial/ ,这就是根因。修复后,用 make all -j1 单线程编译验证,避免并行编译掩盖路径错误。

更隐蔽的报错:

In file included from src/caffe/util/hdf5.cpp:1:
/usr/include/hdf5/serial/hdf5.h:25:10: fatal error: H5public.h: No such file or directory

这表示 hdf5.h 头文件内部引用了 H5public.h ,但后者不在 #include 搜索路径中。Ubuntu 22.04的 libhdf5-dev 包将 H5public.h 放在 /usr/include/hdf5/serial/ ,而 hdf5.h 在同目录。所以 INCLUDE_DIRS 必须是 /usr/include/hdf5/serial/ ,而不是 /usr/include/hdf5/ 。

4.2 protobuf 报错:编译器、版本、生成代码的三角矛盾

典型报错:

src/caffe/proto/caffe.pb.cc:12345: undefined reference to 'google::protobuf::internal::WireFormatLite::WriteString'

这是 protoc 生成的代码与链接的 libprotobuf.so ABI不匹配。诊断步骤:

# 1. 查看protoc版本
protoc --version  # 记录为X.Y.Z

# 2. 查看libprotobuf.so版本
strings /usr/lib/x86_64-linux-gnu/libprotobuf.so.17 | grep "3\." | head -1

# 3. 检查二者是否一致
# 若protoc是3.21.12,libprotobuf.so是3.12.4,则冲突

修复方案:卸载非apt安装的 protoc ,强制使用系统版本:

# 卸载conda或源码安装的protoc
which protoc  # 若返回/opt/conda/bin/protoc,则
rm /opt/conda/bin/protoc

# 重新链接系统protoc
sudo ln -sf /usr/bin/protoc /usr/local/bin/protoc

另一个高频报错:

error: ‘kint32max’ was not declared in this scope

这是 protobuf 3.20.0+引入的C++20特性,与Caffe的C++11不兼容。解决方案是降级 protobuf :

sudo apt remove libprotobuf-dev protobuf-compiler
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protobuf-all-3.19.4.tar.gz
tar -xf protobuf-all-3.19.4.tar.gz
cd protobuf-3.19.4
./configure --prefix=/usr
make -j$(nproc)
sudo make install
sudo ldconfig

4.3 boost 报错:文件系统路径操作的ABI断裂

典型报错:

src/caffe/util/io.cpp:123: error: no match for ‘operator/’ (operand types are ‘boost::filesystem::path’ and ‘const char [5]’)

这是 boost::filesystem::path::operator/ 在 boost 1.72.0+中被移除,而Caffe源码仍在使用。诊断:

dpkg -l | grep libboost-filesystem
# 若版本≥1.72.0,则必须降级

安全降级方案(Ubuntu 22.04):

# 下载boost 1.71.0源码
wget https://boostorg.jfrog.io/artifactory/main/release/1.71.0/source/boost_1_71_0.tar.gz
tar -xf boost_1_71_0.tar.gz
cd boost_1_71_0
./bootstrap.sh --prefix=/usr
sudo ./b2 install

注意: ./b2 install 会覆盖系统 /usr/include/boost/ ,因此必须在 Makefile.config 中确保 INCLUDE_DIRS 包含 /usr/include/ ,且顺序在其他路径之前。

4.4 nvcc 与 g++ 混合编译报错:CUDA的“语言鸿沟”

典型报错:

/usr/include/c++/11/bits/stl_vector.h:361:25: error: ‘__builtin_assume_aligned’ was not declared in this scope

这是 nvcc 调用的主机编译器( g++ )版本过高, __builtin_assume_aligned 在GCC 11中被重命名。解决方案是强制 nvcc 使用GCC 9:

# 确认GCC 9已安装
gcc-9 --version

# 修改Makefile.config中的NVCC定义
NVCC := /usr/local/cuda/bin/nvcc -ccbin /usr/bin/gcc-9

另一个CUDA报错:

src/caffe/layers/cudnn_conv_layer.cpp:123: error: ‘CUDNN_CONVOLUTION_BWD_DATA_PREFER_FASTEST’ was not declared in this scope

这是cuDNN版本过低(<7.6.0)或过高(>8.6.0)。验证cuDNN版本:

cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2
# 输出应为 #define CUDNN_MAJOR 8, #define CUDNN_MINOR 6, #define CUDNN_PATCHLEVEL 0

若版本不符,重新安装匹配的cuDNN。

5. 安装后验证与常见运行时问题

编译通过只是万里长征第一步。 make install 和 make pycaffe 完成后,必须进行四层验证:基础库加载、Python接口导入、CPU推理、GPU推理。每一层失败都指向不同的系统环节。

5.1 libcaffe.so 加载验证:动态链接的“临门一脚”

即使 make all 成功, libcaffe.so 也可能因RPATH缺失而无法被Python加载。验证:

# 检查libcaffe.so的依赖
ldd build/lib/libcaffe.so | grep "not found"

# 检查RPATH是否包含必要路径
readelf -d build/lib/libcaffe.so | grep RPATH

如果 ldd 显示 libhdf5.so.100 => not found ,说明 libcaffe.so 未嵌入 hdf5 库路径。临时修复:

# 将hdf5库路径加入LD_LIBRARY_PATH
export LD_LIBRARY_PATH="/usr/lib/x86_64-linux-gnu/hdf5/serial/:$LD_LIBRARY_PATH"

永久修复(推荐):在 Makefile.config 中添加RPATH:

# 在LINKFLAGS中添加
LINKFLAGS := -Wl,-rpath,/usr/lib/x86_64-linux-gnu/hdf5/serial/ -Wl,-rpath,/usr/lib/x86_64-linux-gnu/

然后重新 make all 。

5.2 pycaffe 导入验证:Python路径的“最后一公里”

执行 python3 -c "import caffe" ,若报错 ModuleNotFoundError: No module named 'caffe' ,说明 pycaffe 未正确安装。检查:

# 查看pycaffe生成位置
ls python/caffe/__init__.py

# 检查PYTHONPATH是否包含caffe/python
echo $PYTHONPATH

# 若为空,临时添加
export PYTHONPATH=$(pwd)/python:$PYTHONPATH

永久生效:将 export PYTHONPATH=/path/to/caffe/python:$PYTHONPATH 加入 ~/.bashrc 。

更隐蔽的导入错误:

ImportError: /path/to/caffe/python/caffe/_caffe.cpython-310-x86_64-linux-gnu.so: undefined symbol: _ZNK6google8protobuf7Message11GetTypeNameEv

这是 _caffe.so 链接的 libprotobuf.so 与Python导入的 protobuf 模块版本不一致。解决方案:确保虚拟环境中 protobuf 版本与系统 libprotobuf-dev 一致,并在 Makefile.config 中 PYTHON_INCLUDE 指向虚拟环境的 include 路径。

5.3 CPU推理验证:用LeNet跑通第一个Demo

进入 examples/mnist/ 目录,执行:

# 下载MNIST数据
./get_mnist.sh

# 转换为LMDB格式
./create_mnist.sh

# 训练(CPU模式)
build/tools/caffe train --solver=examples/mnist/lenet_solver.prototxt

若报错 Check failed: error == cudaSuccess (30 vs. 0) unknown error ,说明Caffe误启用了GPU模式。检查 Makefile.config 中 CPU_ONLY := 1 是否取消注释,或在命令中强制:

build/tools/caffe train --solver=examples/mnist/lenet_solver.prototxt --gpu=-1

5.4 GPU推理验证:监控显存与计算单元

启用GPU训练前,先确认CUDA设备可见:

build/tools/caffe device_query -gpu=all

正常输出应包含 Device id: 0 及显存信息。若报错 Failed to initialize GPU ,检查:

  • nvidia-smi 是否可见GPU
  • CUDA_VISIBLE_DEVICES 环境变量是否被设为 -1
  • Makefile.config 中 USE_CUDNN := 1 是否启用

训练时实时监控GPU:

# 新终端中执行
watch -n 1 nvidia-smi

若显存占用为0,说明Caffe未调用GPU,检查 lenet_solver.prototxt 中 solver_mode: GPU 是否设置。

6. 经验总结:那些文档里不会写的“潜规则”

在带了上百个Caffe项目后,我总结出几条血泪经验,它们不写在任何官方文档里,却是决定成败的关键。

6.1 “降级哲学”:在Ubuntu上,新版本不等于更好

Ubuntu 22.04的GCC 11.2、Python 3.10、NumPy 1.23,对绝大多数现代框架是福音,但对Caffe却是灾难。我的固定策略是:在全新系统上,先装 libprotobuf-dev=3.12.4-1ubuntu1 、 libhdf5-dev=1.10.6+repack-3ubuntu1 等精确版本,再编译Caffe。用 apt list --installed | grep package 锁定版本,比盲目升级更可靠。

6.2 make all -j1 :并行编译是调试的敌人

所有教程都推荐 make all -j$(nproc) 加速,但这是调试阶段的最大误区。并行编译会淹没关键错误信息,让 undefined reference 报错混在数百行 Compiling xxx.cpp 日志中。我的工作流是:首次编译必用 -j1 ,待完全通过后,再用 -j$(nproc) 加速后续编译。

6.3 build/ 目录是“污染源”

每次修改 Makefile.config 或系统依赖后,必须彻底清理 build/ 目录:

rm -rf build/
mkdir build
cd build
cmake ..  # 若用CMake方式
# 或直接 make all

残留的 .o 文件会继承旧的编译参数,导致“明明改了配置,却还报同样错误”。

6.4 Docker不是逃避,而是隔离的智慧

对于生产环境或团队协作,我强烈推荐放弃原生安装,改用Docker。一个最小化镜像只需:

FROM nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04
RUN apt-get update && apt-get install -y \
    build-essential \
    libprotobuf-dev libleveldb-dev libsnappy-dev \
    libhdf5-serial-dev protobuf-compiler \
    libatlas-base-dev libboost-dev libboost-filesystem-dev \
    python3-dev python3-pip && \
    pip3 install numpy==1.21.6
COPY caffe /opt/caffe
WORKDIR /opt/caffe
RUN make all -j4 && make pycaffe

这样,所有环境变量、路径、版本都被固化,新人 docker build 一次即可,无需理解底层原理。

最后分享一个小技巧:当你在深夜面对 make all 的红色报错束手无策时,把报错信息中最前面的文件名(如 src/caffe/util/hdf5.cpp )和行号(如 123 )复制到Caffe GitHub仓库的源码中搜索,往往能找到其他用户提交的相同issue,以及维护者给出的补丁。Caffe虽老,但它的社区依然在呼吸——只是需要你用对方法去倾听。

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值