Tensorflow.js 是 Google 开发的一个开源库,让我们能够在浏览器或 Node 环境中运行机器学习模型和深度学习神经网络。
.compile() 函数用于配置模型,使其准备好进行训练和评估。通过调用 .compile() 函数,我们利用优化器、损失函数 和指标 来准备模型。.compile() 函数接收一个参数对象作为输入。
注意: 如果我们在一个尚未编译的模型上调用 .fit() 或 .evaluate() 函数,程序将会抛出错误。
语法
tf.model.compile({optimizer, loss}, metrics=[])
参数
- optimizer (优化器): 这是一个必填参数。它接受一个 tf.train.Optimizer 对象,或者一个表示优化器的字符串名称。以下是常用的优化器字符串名称 — "sgd", "adam", "adamax", "adadelta", "adagrad", "rmsprop", "momentum"。
- loss (损失): 这是一个必填参数。它接受一个字符串值或字符串数组来表示损失函数的类型。如果我们的模型有多个输出,我们可以通过传递一个损失数组来为每个输出指定不同的损失。模型将最小化的总损失值将是所有单个损失的总和。以下是常用的损失函数字符串名称 — "meanSquaredError", "meanAbsoluteError" 等。
- metrics (指标): 这是一个可选参数。它接受一个列表,包含模型在训练和测试阶段需要评估的指标。通常,我们会使用 metrics=[‘accuracy‘]。对于多输出模型,如果要为不同的输出指定不同的指标,我们也可以传递一个字典。
返回值
由于该函数的作用是为训练准备模型,因此它不返回任何内容。(即返回类型为 void)。
示例 1
在这个例子中,我们将创建一个简单的模型,并为 optimizer 和 loss 参数传递数值。在这里,我们使用的 optimizer 是 "adam",而 loss 是 "meanSquaredError"。
// Importing the tensorflow.js library
const tf = require("@tensorflow/tfjs");
// define the model
const model = tf.sequential({
layers: [tf.layers.dense({ units: 1, inputShape: [10] })],
});
// compile the model
// using "adam" optimizer and "meanSquaredError" loss
model.compile({ optimizer: "adam", loss: "meanSquaredError" });
// evaluate the model which was compiled above
// computation is done in batches of size 4
const result = model.evaluate(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
});
// print the result
result.print();
输出:
Tensor
2.6806342601776123
示例 2
在这个例子中,我们将创建一个简单的模型,并为 optimizer、loss 和 metrics 参数传递数值。在这里,我们使用的 optimizer 是 "sgd",loss 是 "meanAbsoluteError",并且使用 "accuracy" 作为指标。
// Importing the tensorflow.js library
const tf = require("@tensorflow/tfjs");
// define the model
const model = tf.sequential({
layers: [tf.layers.dense({ units: 1, inputShape: [10] })],
});
// compile the model
// using "adam" optimizer, "meanSquaredError" loss and "accuracy" metrics
model.compile(
{ optimizer: "adam", loss: "meanSquaredError" },
(metrics = ["accuracy"])
);
// evaluate the model which was compiled above
// computation is done in batches of size 4
const result = model.evaluate(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
});
// print the result
result.print();
输出:
Tensor
1.4847172498703003
示例 3
在这个例子中,我们将创建一个简单的模型,并为 optimizer、loss 和 metrics 参数传递数值。在这里,我们使用的 optimizer 是 "sgd",loss 是 "meanAbsoluteError",并且使用 "precision" 作为指标。
// Importing the tensorflow.js library
const tf = require("@tensorflow/tfjs");
// define the model
const model = tf.sequential({
layers: [tf.layers.dense({ units: 1, inputShape: [10] })],
});
// compile the model
// using "adam" optimizer, "meanSquaredError" loss and "accuracy" metrics
model.compile(
{ optimizer: "sgd", loss: "meanAbsoluteError" },
(metrics = ["precision"])
);
// evaluate the model which was compiled above
// computation is done in batches of size 4
const result = model.evaluate(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
});
// print the result
result.print();
输出:
Tensor
1.507279634475708