微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

梯度下降不适用于Python中逻辑概率的最大可能性

如何解决梯度下降不适用于Python中逻辑概率的最大可能性

所以我一直在尝试使用python运行基于梯度的algorathim,但我没有得到收敛的结果。请为我要放入代码图片拍照:

enter image description here

我的代码如下:

#base packages
#import sympy as sp
#from sympy import *
import numpy as np 
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression

x = np.array([0,0.1,0.3,0.9,0.9])
y = np.array([0.,0.,1.,1.])


def f(b0,b1,x,y):
    vec = [y[i]*np.log(1/(1+np.exp(-b0-b1*x[i]))) + (1-y[i])*np.log(1 - (1/(1+np.exp(-b0-b1*x[i])))) for i in range(len(y))]
    return sum(vec)

def dervf0(b0,y):
    vec = [-y[i] + (1/(1+np.exp(-b0-b1*x[i]))) for i in range(len(x))]
    return np.sum(vec)
def dervf1(b0,y):
    vec = [-x[i]*(y[i]-(1/(1+np.exp(-b0-b1*x[i])))) for i in range(len(x))]
    return sum(vec)



def G(f1,f2,b0,y,tol,maxiter):
    v = np.array([b0,b1]) 
    theta_new  = v
    for i in range(maxiter):
        theta_new = v - 0.001*np.array([f1(b0,y),f2(b0,y)])
        if np.linalg.norm(theta_new - v) < tol: 
            break
        else:
            v = theta_new     
    return theta_new,i

结果应为向量[-0.009,1.263]'。我怎么没有得到收敛的结果。任何想法? 是

解决方法

我不明白为什么定义了f1f2。 问题是您没有在下一次迭代中使用更新的参数b0,b1。您正在更新v,而不是b0,b1 每次迭代都添加

b0 = v[0]
b1 = v[1]

尝试此向量化实现。 向量化的实现速度更快。 最终的theta_new是[-0.00923525 1.26245957]


import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression

x = np.array([0,0.1,0.3,0.9,0.9])
y = np.array([0.,0.,1.,1.])


def f(b0,b1,x,y):
    return np.sum(
        np.multiply(y,np.log(1 / (1 + np.exp(-b0 - b1 * x)))) +
        np.multiply(1 - y,np.log(1 - (1 / (1 + np.exp(-b0 - b1 * x))))))


def dervf0(b0,y):
    return np.sum(-1 * y + (1 / (1 + np.exp(-b0 - b1 * x))))


def dervf1(b0,y):
    return np.sum(np.multiply(-1 * x,y - (1 / (1 + np.exp(-b0 - b1 * x)))))


def G(v,y,tol,maxiter):
    theta_new = v
    for i in range(maxiter):
        theta_new = v - 0.001 * np.array(
            [dervf0(v[0],v[1],y),dervf1(v[0],y)])
        if np.linalg.norm(theta_new - v) < tol:
            break
        else:
            v = theta_new
        print('i\t{}\tv\t{}\ttheta_new\t{}'.format(i,v,theta_new))
    return theta_new,i


tol = 0.0000001
maxiter = 1000000
v = np.random.normal(0,1,2)
theta_new,i = G(v,maxiter)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。