梯度下降不适用于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)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...