【发布时间】:2023-03-08 10:28:01
【问题描述】:
我正在尝试使用 tensorflow.js 将指数数据拟合到指数回归中,例如:
y(x) = c0e^(kx)
我遵循了一些示例,他们仅用几个 epoch 拟合了线性回归,例如 here。
问题在于,当我将张量方程更改为指数函数时,即使我增加到 500-5000 个时期并提供接近的初始值,它也不能正确拟合。学习率大时,变量会达到非常高的值,而学习率低时,变量不会发生实质性变化。
我在代码中做错了什么吗?是因为优化不适合指数函数吗?有没有其他方法可以在不使用 tf.js 的情况下在浏览器中实现这一点?
我使用的代码是:
const x = tf.tensor1d([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
const y = tf.tensor1d([2.5879,3.1153,3.7041,4.6216,5.2307,5.6205,6.9904,7.8416,9.0201,10.5586,12.1638,14.1438,16.5961,19.2497,22.3430]);
const c0 = tf.scalar(2).variable();
const k = tf.scalar(0.10).variable();
// y = c0*e^(k*x)
const fun = (x) => x.mul(k).exp().mul(c0);
const cost = (pred, label) => pred.sub(label).square().mean();
const learning_rate = 0.001;
const optimizer = tf.train.sgd(learning_rate);
// Train the model.
for (let i = 0; i < 20; i++) {
optimizer.minimize(() => cost(fun(x), y));
}
console.log(`c0: ${c0.dataSync()}, k: ${k.dataSync()}`);
const preds = fun(x).dataSync();
preds.forEach((pred, i) => {
console.log(`x: ${i}, pred: ${pred}`);
});
【问题讨论】:
标签: javascript tensorflow machine-learning tensorflow.js exponential