Javascript¶
YDF 提供两个不同的 npm 包,可在 Web 上运行
- ydf-inference 仅用于使用现有模型生成预测。模型可以使用 ydf-training(见下文)、YDF Python 或任何其他 YDF API 进行训练。如果只需要模型预测,请使用此包而不是 ydf-training,以减小二进制文件大小。
- ydf-training 用于训练模型和生成预测。
这两个包都与 NodeJS+CommonJS、NodeJS+ES6 和 Browser JS 兼容。
ydf-inference¶
ydf-inference
是 YDF 在 Web 上进行模型推理的接口。有关下载和测试包的信息,请参阅 npmjs.com 上的 Readme 文件。
以下示例展示了如何下载 YDF 模型并在 Javascript 数组字典上进行预测。
<script src="./node_modules/ydf-inference/dist/inference.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js"></script>
<script>
YDFInference()
.then(ydf => ydf.loadModelFromUrl("http://localhost:3000/model.zip"))
.then(model => {
let examples = {
"age": [39, 40, 40, 35],
"workclass": ["State-gov", "Private", "Private", "Federal-gov"],
"fnlwgt": [77516, 121772, 193524, 76845],
"education": ["Bachelors", "Assoc-voc", "Doctorate", "9th"],
"education_num": ["13", "11", "16", "5"],
"marital_status": ["Never-married", "Married-civ-spouse", "Married-civ-spouse", "Married-civ-spouse"],
"occupation": ["Adm-clerical", "Craft-repair", "Prof-specialty", "Farming-fishing"],
"relationship": ["Not-in-family", "Husband", "Husband", "Husband"],
"race": ["White", "Asian-Pac-Islander", "White", "Black"],
"sex": ["Male", "Male", "Male", "Male"],
"capital_gain": [2174, 0, 0, 0],
"capital_loss": [0, 0, 0, 0],
"hours_per_week": [40, 40, 60, 40],
"native_country": ["United-States", null, "United-States", "United-States"]
};
predictions = model.predict(examples);
model.unload();
});
</script>
ydf-training¶
ydf-training
是 YDF 在 Javascript 中训练和检查模型的接口。它使用 Javascript 和 WebAssembly 实现。有关下载和测试包的信息,请参阅 npmjs.com 上的 Readme 文件。
以下示例展示了如何在一个 csv 数据集上训练一个梯度提升树模型,然后使用该模型在第二个 csv 数据集上进行预测。
<script src="./node_modules/ydf-training/dist/training.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js"></script>
<script>
YDFTraining()
.then( async (ydf) => {
// Download the datasets.
const rawTrain = await fetch("http://localhost:3000/train.csv");
const train = await rawTrain.text();
const rawTest = await fetch("http://localhost:3000/test.csv");
const test = await rawTest.text();
// Prepare the training configuration.
const task = "CLASSIFICATION";
const label = "label";
// Train the model.
const model = new ydf.GradientBoostedTreesLearner(label, task).train(data);
// Make predictions.
const predictions = model.predict(data);
// Print the description of the model.
console.log(model.describe());
// Save the model to later. This model can also be run with ydf-inference
// or Python YDF.
const modelAsZipBlob = await model.save();
model.unload();
});
</script>
已知限制¶
ydf-training
目前仅支持 YDF Python 接口功能的一个子集,即使用随机森林和梯度提升树进行监督学习。暂不支持超参数配置。此外,暂不支持模型评估和模型分析。
如需功能请求,请在 GitHub 上提交 issue。