【问题标题】:Nonlinear Exponential Regression with Tensorflow.js使用 Tensorflow.js 进行非线性指数回归
【发布时间】: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


    【解决方案1】:

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

    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_rateepochs 使用的数量

    另外,可能会使用几个优化器,看看哪一个总体上表现最好

    【讨论】:

    • 非常感谢!将优化器用于我在实现中使用的较大数组时,优化器的变化产生了巨大的差异。对于初始值,我使用线性化数据和方程后通过线性最小二乘法获得的参数。再次感谢,我会接受这个答案。
    猜你喜欢
    • 2021-03-11
    • 2019-03-27
    • 1970-01-01
    • 2018-07-31
    • 2022-01-11
    • 1970-01-01
    • 2016-07-21
    • 2023-03-05
    • 2021-12-20
    相关资源
    最近更新 更多