Candle 是 Rust 的极简 ML 框架,重点关注性能(包括 GPU 支持)和易用性。
今天我们来使用Candle完成一个深度 学习的Hello World案例:手写数字识别。
我们使用最简单的线性模型来训练一个自己的手写数字识别模型,作为Candle框架的
最简单入门案例。
环境
Rust:1.75.0-nightlycandle-core:0.3.0candle-nn:0.3.0candle-datasets:0.3.0
提示
candle-nn当前版本中依赖了Rust nightly
Cargo.toml内容如下
rand: 随机数anyhow: 处理异常clap: 解析命令行参数
[package]
name = "linear_mnist"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
candle-core = { git = "https://github.com/huggingface/candle.git", version = "0.3.0" }
candle-nn = { git = "https://github.com/huggingface/candle.git", version = "0.3.0" }
rand = "0.8.5"
anyhow = "1"
clap = { version = "4.4.4", features = ["derive"] }
candle-datasets = { git = "https://github.com/huggingface/candle.git", version = "0.3.0" }
创建项目并安装Candle相关模块
- 使用
cargo new创建linear_mnist项目 - 进入项目目录
- 安装
candle三个模块candle-corecandle-nncandle-datasets
- 安装其他依赖库
randanyhowclap
具体操作如下:
cargo new linear_mnist
cd linear_mnist
cargo add --git https://github.com/huggingface/candle.git candle-core
cargo add --git https://github.com/huggingface/candle.git candle-nn
cargo add --git https://github.com/huggingface/candle.git candle-datasets
代码
导入相关依赖
- 导入
clap::Parser解析命令行参数 - 导入
candle_core的相关依赖Device: 数据计算时放置的设备Result: 处理异常Tensor: 张量数据类型D: 是一个enum,包含Minus1和Minus2DType: 数据类型enum结构,包含支持的数据类型