how can I do a maximum likelihood regression using scipy.optimize.minimize

前端 未结 1 1582
不知归路
不知归路 2021-02-06 06:58

How can I do a maximum likelihood regression using scipy.optimize.minimize? I specifically want to use the minimize function here, because I have a com

1条回答
  •  青春惊慌失措
    2021-02-06 07:20

    Thank you Aleksander. You were correct that my likelihood function was wrong, not the code. Using a formula I found on wikipedia I adjusted the code to:

    import numpy as np
    from scipy.optimize import minimize
    
    def lik(parameters):
        m = parameters[0]
        b = parameters[1]
        sigma = parameters[2]
        for i in np.arange(0, len(x)):
            y_exp = m * x + b
        L = (len(x)/2 * np.log(2 * np.pi) + len(x)/2 * np.log(sigma ** 2) + 1 /
             (2 * sigma ** 2) * sum((y - y_exp) ** 2))
        return L
    
    x = np.array([1,2,3,4,5])
    y = np.array([2,5,8,11,14])
    lik_model = minimize(lik, np.array([1,1,1]), method='L-BFGS-B')
    plt.scatter(x,y)
    plt.plot(x, lik_model['x'][0] * x + lik_model['x'][1])
    plt.show()
    

    Now it seems to be working.

    maximum likelihood regression

    Thanks for the help!

    0 讨论(0)
提交回复
热议问题