javascript - Tensorflow.js 在运行线性回归模型时返回“NaN”值
问题描述
我正在尝试运行这个线性回归模型,它基本上会给我一个输出,const prediction = model.predict((tf.tensor2d([20], [1,1])));
但不幸的是,每次我运行代码以接收预测时,我都会得到 NaN 值。
解决问题的最佳方法是什么?还有其他方法吗?
谢谢!
下面是代码:
async function learnLinear() {
const fontSize = document.getElementById("count").innerHTML;
const parsed = parseInt(fontSize);
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
const learningRate = 0.0001;
const optimizer = tf.train.sgd(learningRate);
model.compile({
loss: "meanSquaredError",
optimizer: "sgd",
});
const xs = tf.tensor2d(
[
54,
20,
22,
34,
18,
47,
28,
54,
36,
51,
44,
31,
39,
19,
45,
48,
32,
27,
25,
54,
27,
38,
25,
38,
57,
49,
28,
19,
59,
28,
27,
55,
60,
49,
40,
45,
35,
45,
39,
25,
50,
58,
28,
59,
21,
37,
47,
31,
46,
18,
],
[50, 1]
);
const ys = tf.tensor2d(
[
14,
15,
15,
15,
16,
17,
15,
16,
15,
17,
17,
15,
16,
15,
15,
16,
17,
17,
17,
14,
16,
15,
15,
16,
17,
15,
16,
14,
15,
16,
14,
17,
15,
14,
14,
17,
15,
14,
14,
16,
16,
14,
14,
17,
17,
14,
17,
14,
14,
17,
],
[50, 1]
);
await model.fit(xs, ys, { epochs: 500 });
const prediction = model.predict(tf.tensor2d([20], [1, 1]));
const value = prediction.dataSync()[0];
console.log("Prediction", value);
}
解决方案
您忘记指定模型应该跟踪的指标。
const batchSize = 32;
const epochs = 500;
model.compile({
loss: "meanSquaredError",
optimizer: "sgd",
metrics: ["mse"],
});
await model.fit(xs, ys, batchSize, epochs);
const prediction = model.predict(tf.tensor2d([20], [1, 1]));
推荐阅读
- python - 我如何检查 Python 是不是我的 Flask 应用程序已经在后台运行
- sockets - 在 Django 频道中使用 RedisChannelLayer 时,长 URL(包括密钥)会导致 unicode idna 编解码器解码错误
- java - Spring Config Server - 属性覆盖
- azure - 在 Azure 持久函数中设置 MaxOrchestrationActions
- python - 为什么在 Python3 中发生列表索引超出范围
- excel - VBA Excel - 取几列的范围
- php - Laravel 6.x PostgreSQL 插入问题?SQLSTATE[22P02]:无效的文本表示:7 错误
- mysql - 需要从两个 MySQL 表创建一个动态矩阵
- python - 如何在两列之间创建转换矩阵?
- python - 我正在尝试使用 if 语句基于不同的数据框创建一个新的数据框