我想使用scipy minimize
对形式
y = a * x^b
假设错误通常分布在预测周围。目前,真正的参数根本无法恢复(见下文)。
def loglik(param, data):
mu = 0.0
logLikelihood = 0.0
resid = 0.0
for i in range(data.shape[0]):
mu = param[0] * (data[i][0] ** param[1])
resid = float(data[i][1] - mu) / param[2]
logLikelihood += -0.5 * resid * resid
return -(-data.shape[0] * np.log(param[2]) + logLikelihood)
这是我到目前为止使用的代码,但正如您所见,收敛后的参数远非真实的。
def generate(param, x):
pred = [(param[0] * (x ** param[1])) for x in x]
return np.array([sum(x) for x in zip(pred, np.random.normal(0, param[2], len(x)))])
x = np.linspace(1, 50, num=100)
true_param = [15, 1.1, 5]
data = np.vstack((x, generate(true_param, x))).T
from scipy.optimize import minimize
initParams = [1,1,1]
result = minimize(loglik, method='Nelder-Mead', x0=initParams,args=data)
print(result.x) # should be 15, 1.1, 5