Los errores estándar de los coeficientes del modelo son las raíces cuadradas de las entradas diagonales de la matriz de covarianza. Considere lo siguiente:
X = [1x1,1…x1,p1x2,1…x2,p⋮⋮⋱⋮1xn,1…xn,p] donde xi,j es el valor del j ª predictor de la i Observaciones.
(NOTA: Esto supone un modelo con intercepción).
- V = [ˆπ1(1−ˆπ1)0…00ˆπ2(1−ˆπ2)…0⋮⋮⋱⋮00…ˆπn(1−ˆπn)] donde ˆπi representa la probabilidad prevista de pertenencia a una clase para la observación i .
La matriz de covarianza puede escribirse como:
(XTVX)−1
Esto se puede implementar con el siguiente código:
import numpy as np
from sklearn import linear_model
# Initiate logistic regression object
logit = linear_model.LogisticRegression()
# Fit model. Let X_train = matrix of predictors, y_train = matrix of variable.
# NOTE: Do not include a column for the intercept when fitting the model.
resLogit = logit.fit(X_train, y_train)
# Calculate matrix of predicted class probabilities.
# Check resLogit.classes_ to make sure that sklearn ordered your classes as expected
predProbs = resLogit.predict_proba(X_train)
# Design matrix -- add column of 1's at the beginning of your X_train matrix
X_design = np.hstack([np.ones((X_train.shape[0], 1)), X_train])
# Initiate matrix of 0's, fill diagonal with each predicted observation's variance
V = np.diagflat(np.product(predProbs, axis=1))
# Covariance matrix
# Note that the @-operater does matrix multiplication in Python 3.5+, so if you're running
# Python 3.5+, you can replace the covLogit-line below with the more readable:
# covLogit = np.linalg.inv(X_design.T @ V @ X_design)
covLogit = np.linalg.inv(np.dot(np.dot(X_design.T, V), X_design))
print("Covariance matrix: ", covLogit)
# Standard errors
print("Standard errors: ", np.sqrt(np.diag(covLogit)))
# Wald statistic (coefficient / s.e.) ^ 2
logitParams = np.insert(resLogit.coef_, 0, resLogit.intercept_)
print("Wald statistics: ", (logitParams / np.sqrt(np.diag(covLogit))) ** 2)
Dicho todo esto, statsmodels
será probablemente un mejor paquete para utilizar si desea acceder a una gran cantidad de diagnósticos "out-the-box".