【问题标题】:how to correctly determine the parameters of the model?如何正确确定模型的参数?
【发布时间】:2021-08-18 04:56:23
【问题描述】:

如何找到模型的参数?

型号为:y = a * log(x + b) + c 我想找a, b , c.

当然xy 是一组数字(假设它是随机的,因为它不是我的全部解决方案)。

我正在考虑使用numpy.polyfit函数,但并没有过多考虑要输入哪些参数以及接下来要做什么。

有人能或多或少地告诉我应该怎么做吗?

【问题讨论】:

标签: python numpy matplotlib math scipy


【解决方案1】:

为了谈论寻找模型的参数,您需要某种损失函数(您想要最小化的函数)。否则你的参数可以是任何东西,你可以说你已经成功找到了模型的参数。

一旦你有了这个损失函数,你就可以使用像梯度下降这样的算法。我建议为此使用 TensorFlow。您首先需要使用 TensorFlow 的操作定义模型(他们几乎拥有一切),以便他们的算法找到如何最小化损失函数。以下是你的做法:

import tensorflow as tf

# I need to use Layer to be able to add parameters by hand
class CustomModel(tf.keras.layers.Layer):
    def __init__(self):
        super(CustomModel, self).__init__()
        
        self.b = self.add_weight(name="b", shape=[1], dtype=tf.float32, trainable=True)
        self.c = self.add_weight(name="c", shape=[1], dtype=tf.float32, trainable=True)
     
     def call(self, x):
         return tf.math.log(x + self.b) + self.c

model = CustomModel()

然后您可以使用损失函数编译模型并在 (x, y) 对上进行训练。

model.compile(loss=SOME_LOSS_FUNCTION, optimizer="adam")
model.fit(x=x, y=y, batch_size=SOME_BATCH_SIZE, epochs=SOME_EPOCHS)

值得一提的是,如果您的问题只是某种形式的回归,您可以将损失设置为 tf.keras.losses.MeanSquaredError()。

在简单情况下可能更好的替代方法是手动计算导数,然后实现它们。这将允许您继续使用 numpy 操作。但是 TensorFlow 可以让您利用 GPU 或 TPU,因此可以说您应该使用它或任何其他流行的 ML 框架。

【讨论】:

    【解决方案2】:

    scipy.optimize.curve_fit 是您所需要的 - 您将要拟合的函数、自变量向量和观察向量传递给它,该函数返回观察参数向量和协方差矩阵。

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    
    a0, b0, c0 = 3, 2, 7
    x = np.linspace(0,10,1001)
    y0 = a0 * np.log(x+b0) + c0
    y1 = y0 + np.random.randn(1001)/5
    
    (a1, b1, c1), cov = curve_fit(lambda x, a, b, c: a*np.log(x+b)+c, x, y1)
    
    fig, (ax1, ax2) = plt.subplots(2,1)
    ax1.plot(x, y1, label='Measured')
    ax2.plot(x, y0, label='"True", a=%.3f, b=%.3f, c=%.3f'%(a0,b0,c0))
    ax2.plot(x, a1*np.log(x+b1)+c1, label='Recovered, a=%.3f, b=%.3f, c=%.3f'%(a1,b1,c1))
    ax1.legend()
    ax2.legend()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 2015-09-19
      • 2020-12-04
      相关资源
      最近更新 更多