训练
要使用 Ludwig 训练模型,我们首先需要创建一个 Ludwig 配置。配置指定了输入特征、输出特征、预处理、模型架构、训练循环、超参数搜索以及后端基础设施——构建、训练和评估模型所需的一切。
至少,配置必须指定模型的输入和输出特征。
现在,让我们使用一个基本配置,它只指定输入和输出,其余留给 Ludwig 处理
rotten_tomatoes.yaml
input_features:
- name: genres
type: set
preprocessing:
tokenizer: comma
- name: content_rating
type: category
- name: top_critic
type: binary
- name: runtime
type: number
- name: review_content
type: text
encoder:
type: embed
output_features:
- name: recommended
type: binary
此配置文件告诉 Ludwig,我们希望训练一个使用以下 输入特征 的模型
- 与电影相关的 流派 将用作 集合特征
- 电影的 内容分级 将用作 类别特征
- 评论是否由 顶级评论家 完成将用作 二元特征
- 电影的 运行时长 将用作 数值特征
- 评论内容 将用作 文本特征
此配置文件还告诉 Ludwig,我们希望模型具有以下 输出特征
- 关于是否观看电影的推荐将输出为 二元特征
创建包含上述内容的 rotten_tomatoes.yaml
文件后,您就可以训练您的第一个模型了
ludwig train --config rotten_tomatoes.yaml --dataset rotten_tomatoes.csv
from ludwig.api import LudwigModel
import pandas
df = pandas.read_csv('rotten_tomatoes.csv')
model = LudwigModel(config='rotten_tomatoes.yaml')
results = model.train(dataset=df)
mkdir rotten_tomatoes_data
mv rotten_tomatoes.yaml ./rotten_tomatoes_data
mv rotten_tomatoes.csv ./rotten_tomatoes_data
docker run -t -i --mount type=bind,source={absolute/path/to/rotten_tomatoes_data},target=/rotten_tomatoes_data ludwigai/ludwig train --config /rotten_tomatoes_data/rotten_tomatoes.yaml --dataset /rotten_tomatoes_data/rotten_tomatoes.csv --output_directory /rotten_tomatoes_data
注意
在此示例中,我们使用 embed
编码器对文本特征进行编码,该编码器为每个单词分配一个嵌入并将其求和。Ludwig 提供了许多用于 分词 和 嵌入 文本的选项,例如使用 CNN、RNN、Transformer 以及 BERT 或 GPT-2 等预训练模型(通过 huggingface 提供)。使用不同的文本编码器就像在配置中将编码器选项从 embed
更改为 bert
一样简单。试试看吧!
input_features:
- name: genres
type: set
preprocessing:
tokenizer: comma
- name: content_rating
type: category
- name: top_critic
type: binary
- name: runtime
type: number
- name: review_content
type: text
encoder:
type: bert
output_features:
- name: recommended
type: binary
Ludwig 非常灵活。用户可以直接从配置中配置模型的几乎所有参数,包括训练参数、预处理参数等等。查看 配置文档 以获取配置中可用参数的完整列表。