4.1 广义线性模型之Possion回归模型的SGA实现(与statsmodels中的Possion对比)

在2.3节中,我们从广义线性模型推导出了Possion回归模型,这个模型在sklearn.linear_model中并没有实现,由此,我认为有实现的必要。在Github上浏览的时候,发现在statsmodels.discrete.discrete_model中实现了此模型,因此,在这里,我给出自己实现的Possion回归模型实现代码并与其进行效果对比。

import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons

def hypothesis(x):
    return np.exp(x)
def SGA(X,y,a=0.001):
    theta=np.zeros(3).T
    for times in range(1000):
        for i in range(100):
            theta+=a*(y[i] - hypothesis(X[i].dot(theta)) )*X[i].T
    return theta
#生成数据
np.random.seed(0)
X,y=make_moons(n_samples=100)
X=np.insert(X,0,1,axis=1)
#梯度上升获得参数,预测
theta=SGA(X,y)
predVals1=hypothesis(np.dot(X,theta))

pModel=sm.Poisson(y,X).fit()
predVals2=pModel.predict(X)

fig,axes=plt.subplots(nrows=1,ncols=2,sharey=True)
axes[0].plot(y, 'r*-', range(len(y)), predVals1, 'bo-.'
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值