Tensorflow.js 的非线性指数回归

Nonlinear Exponential Regression with Tensorflow.js

我正在尝试使用 tensorflow.js 将指数数据拟合到指数回归,例如:

y(x) = c0e^(kx)

我遵循了一些例子,其中他们只用几个时期拟合了线性回归,比如 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}`);
});

这与使用的优化器和可能不收敛的初始值集有关。如果它们设置不正确,模型可能会发散。

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.1;
const optimizer = tf.train.adagrad(learning_rate);

// Train the model.
for (let i = 0; i < 500; i++) {
    optimizer.minimize(() => cost(fun(x), y));
}

console.log(`c0: ${c0.dataSync()}, k: ${k.dataSync()}`);
fun(x).print()

// [2.4752154, 2.899802, 3.3972201, 3.9799631, 4.6626663, 5.4624777, 6.3994851, 7.4972224, 8.7832594, 10.289897, 12.0549774, 14.1228304, 16.545393, 19.3835087, 22.7084637]

使用tf.train.adagrad,看来收敛的很好。对于初始值,我们也可以只对随机值使用 Math.Random(),对随机值使用 运行 多次模拟,直到找到导致更好预测的值集。同样可以微调learning_rate和使用的epochs数量

此外,可以使用多个优化器,看看哪个优化器总体上表现最好