1. 安装基础开发环境
在Ubuntu上进行C++机器学习开发前,需先安装必要的编译工具和依赖库。打开终端,执行以下命令:
sudo apt update && sudo apt upgradesudo apt install build-essential cmake git2. 选择并安装C++机器学习库
C++生态中有丰富的机器学习库,可根据需求选择:
sudo apt install libdlib-devsudo apt install libmlpack-devsudo apt install libshark-devsudo apt install libopencv-dev3. 配置CMake构建系统
CMake是C++项目的常用构建工具,需创建CMakeLists.txt文件配置项目。以Dlib为例,文件内容如下:
cmake_minimum_required(VERSION 3.10)
project(MyMLProject)
set(CMAKE_CXX_STANDARD 11) # 或14/17,根据库要求调整
find_package(Dlib REQUIRED)
add_executable(MyMLProject main.cpp)
target_link_libraries(MyMLProject Dlib::Dlib)
若使用Flashlight(需提前编译并安装),配置如下:
cmake_minimum_required(VERSION 3.10)
project(MyMLProject)
set(CMAKE_CXX_STANDARD 17)
find_package(Flashlight REQUIRED)
add_executable(MyMLProject main.cpp)
target_link_libraries(MyMLProject Flashlight::Flashlight)
find_package用于定位库的头文件和链接库,target_link_libraries将库链接到项目。
4. 编写C++机器学习代码
以Dlib的线性SVM分类器为例,代码示例如下:
#include <dlib/svm.h>
#include <dlib/data_io.h>
#include <iostream>
using namespace dlib;
int main() {
try {
// 定义2维特征向量和标签类型
typedef matrix<double, 2, 1> sample_type;
typedef decision_function<linear_kernel<sample_type>> dec_funct_type;
typedef normalized_function<dec_funct_type> funct_type;
// 创建训练数据(示例:二维平面上的两类点)
std::vector<sample_type> samples;
std::vector<double> labels;
samples.push_back({1.0, 2.0}); labels.push_back(1);
samples.push_back({2.0, 3.0}); labels.push_back(1);
samples.push_back({3.0, 3.0}); labels.push_back(-1);
samples.push_back({4.0, 5.0}); labels.push_back(-1);
// 训练线性SVM
typedef linear_kernel<sample_type> kernel_type;
svm_c_trainer<kernel_type> trainer;
trainer.set_kernel(kernel_type());
dec_funct_type df = trainer.train(samples, labels);
// 预测新样本
sample_type test_sample = {2.5, 2.5};
double prediction = df(test_sample);
std::cout << "Prediction: " << prediction << std::endl;
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
代码实现了二维数据的线性SVM训练与预测,需根据实际任务调整数据加载和模型参数。
5. 编译与运行项目
mkdir build && cd buildcmake ..make./MyMLProject-ltensorflow),并指定头文件路径(如-I/path/to/tensorflow/include)。6. 注意事项
sudo apt autoremove清理无用包,或使用conda创建隔离环境(如conda create -n ml_env python=3.8)。