在 Python 中使用 statsmodels.api 和 R 语法的逻辑回归
Logistic Regression Using statsmodels.api with R syntax in Python
我正在尝试 运行 一个简单的逻辑回归函数。我有 4 个列,分别命名为 x1、x2、x3 和 x4。 x4 有一列只有零和一。所以,我用它作为我的因变量。为了预测因变量,我使用了自变量 x1、x2 和 x3。我的语法是否关闭或如何在保持 Statsmodels.api 提供的 R 语法的同时正确完成数据的逻辑回归?
以下是我的代码:
import pandas as pd
import statsmodels.formula.api as smf
df = pd.DataFrame({'x1': [10, 11, 0, 14],
'x2': [12, 0, 1, 24],
'x3': [0, 65, 3, 2],
'x4': [0, 0, 1, 0]})
model = smf.logit(formula='x4 ~ x1 + x2 + x3', data=df).fit()
print(model)
以下是我的错误:
statsmodels.tools.sm_exceptions.PerfectSeparationError: Perfect separation detected, results not available
我明白这是什么意思,但我不明白如何避免这个问题。确认逻辑回归算法成功需要哪些值,我的语法是否正确,是否有更好的方法来解决我所做的(使用 R 语法)?
我可能误解了这个问题,但语法似乎没问题——虽然我认为你想要 print(model.summary())
而不是 print(model)
。问题是你的样本量太小了。
例如,这个有效:
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
np.random.seed(2)
n=100
df = pd.DataFrame({'x1':np.random.randn(n),
'x2': np.random.randn(n),
'x3': np.random.randn(n),
'x4': np.random.randint(0,2,n)})
model = smf.logit(formula='x4 ~ x1 + x2 + x3', data=df).fit()
print(model.summary())
更改为 n=10
会在摘要 table 下产生以下消息:
Possibly complete quasi-separation: A fraction 0.40 of observations can be
perfectly predicted. This might indicate that there is complete
quasi-separation. In this case some parameters will not be identified.
更改为 n=5
会产生
PerfectSeparationError: Perfect separation detected, results not available
我正在尝试 运行 一个简单的逻辑回归函数。我有 4 个列,分别命名为 x1、x2、x3 和 x4。 x4 有一列只有零和一。所以,我用它作为我的因变量。为了预测因变量,我使用了自变量 x1、x2 和 x3。我的语法是否关闭或如何在保持 Statsmodels.api 提供的 R 语法的同时正确完成数据的逻辑回归?
以下是我的代码:
import pandas as pd
import statsmodels.formula.api as smf
df = pd.DataFrame({'x1': [10, 11, 0, 14],
'x2': [12, 0, 1, 24],
'x3': [0, 65, 3, 2],
'x4': [0, 0, 1, 0]})
model = smf.logit(formula='x4 ~ x1 + x2 + x3', data=df).fit()
print(model)
以下是我的错误:
statsmodels.tools.sm_exceptions.PerfectSeparationError: Perfect separation detected, results not available
我明白这是什么意思,但我不明白如何避免这个问题。确认逻辑回归算法成功需要哪些值,我的语法是否正确,是否有更好的方法来解决我所做的(使用 R 语法)?
我可能误解了这个问题,但语法似乎没问题——虽然我认为你想要 print(model.summary())
而不是 print(model)
。问题是你的样本量太小了。
例如,这个有效:
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
np.random.seed(2)
n=100
df = pd.DataFrame({'x1':np.random.randn(n),
'x2': np.random.randn(n),
'x3': np.random.randn(n),
'x4': np.random.randint(0,2,n)})
model = smf.logit(formula='x4 ~ x1 + x2 + x3', data=df).fit()
print(model.summary())
更改为 n=10
会在摘要 table 下产生以下消息:
Possibly complete quasi-separation: A fraction 0.40 of observations can be perfectly predicted. This might indicate that there is complete quasi-separation. In this case some parameters will not be identified.
更改为 n=5
会产生
PerfectSeparationError: Perfect separation detected, results not available