【发布时间】:2019-08-31 16:17:17
【问题描述】:
我得到了由 X 和 Y 点组成的数据(x_1,...x_n; y1,...y_n)。
我想使用两个基函数将 X 拟合到 Y:max(x,mu_1) 和 min(x,mu_2)
换句话说,我想估计以下等式:
y_i = a_1*max(x_i,mu_1)+a_2*min(x_i,mu_2)
我想找到mu_1 和mu_2 以便最适合上面的情况。我的意思是 mu_1 和 mu_2 这样当我拟合 Y 到 X 时,残差平方和最小化。
或者我可以说我需要a_1、a_2、mu_1、mu_2 以使上述拟合的残差平方和最小化。
我尝试执行以下操作:
我创建了两个参数 (mu_1 and mu_2) 的函数,它返回 Y 与 X 的拟合质量。然后我尝试使用 scipy.optimize.minimize 优化此函数。这是代码:
import numpy as np
from scipy.optimize import minimize
from sklearn.linear_model import LinearRegression
###Create X and Y
X = np.random.normal(10,1,size = 10000)
Y = np.random.normal(20,1,size = 10000)
###Create function that estimates quality of fit
def func(mu_1,mu_2):
### basis functions
regressor_1 = np.maximum(X,mu_1).reshape(-1,1)
regressor_2 = np.minimum(X,mu_2).reshape(-1,1)
x_train = np.hstack((regressor_1,regressor_2))
model = LinearRegression().fit(x_train,Y)
###I didnt find how to extract sum of squared residual, but I can get R
squared, so I thought that minimizing SSR is the same as maximizing R
squared and it is the same as minimizing -R^2
objective = model.score(x_train,Y)
return -1*objective
### Now I want to find such mu_1 and mu_2 that minimize "func"
minimum = minimize(func,0,0)
minimum.x
它不起作用。我将非常感谢任何帮助。
【问题讨论】:
标签: python scikit-learn scipy linear-regression mathematical-optimization