非常简单的回归任务。我有三个变量x1, x2, x3
和一些随机噪声。我知道目标方程:y = q1*x1 + q2*x2 + q3*x3
。现在我想找到目标coef:q1, q2, q3
使用平均相对平方误差(RSE) (Prediction/Real - 1)^2
评估性能来评估我们预测方法的性能。
在研究中,我看到这是一个普通的最小二乘问题。但是我不能从互联网上的例子中得到如何用Python解决这个特殊问题。假设我有数据:
import numpy as np
sourceData = np.random.rand(1000, 3)
koefs = np.array([1, 2, 3])
target = np.dot(sourceData, koefs)
(在现实生活中,数据是有噪声的,而且不是正态分布。)如何在python中使用最小二乘法找到这个koefs?任何lib用法。
发布于 2017-06-16 21:23:00
除了@lhk的答案之外,我还发现了很棒的scipy Least Squares function。使用它可以很容易地获得所请求的行为。
这样,我们可以提供一个自定义函数,返回残差并形成相对平方误差,而不是绝对平方差:
import numpy as np
from scipy.optimize import least_squares
data = np.random.rand(1000,3)
true_theta = np.array([1,2,3])
true_measurements = np.dot(data, true_theta)
noise = np.random.rand(1000) * 1
noisy_measurements = true_measurements + noise
#noisy_measurements[-1] = data[-1] @ (1000 * true_theta) - uncoment this outliner to see how much Relative Squared Error esimator works better then default abs diff for this case.
def my_func(params, x, y):
res = (x @ params) / y - 1 # If we change this line to: (x @ params) - y - we will got the same result as np.linalg.lstsq
return res
res = least_squares(my_func, x0, args=(data, noisy_measurements) )
estimated_theta = res.x
此外,我们还可以提供自定义损失与loss
参数函数,该函数将处理残差并形成最终损失。
https://stackoverflow.com/questions/44587923
复制相似问题