我一直在尝试寻找一种在Python的OLS / GLS回归中指定预定义系数的方法。我可以使用public interface UnitStackTranslation<F extends UnitStack, T extends UnitStack, FV extends ValuePair, TV extends ValuePair> {
TV translateFrom(FV value, F from, T to);
FV translateTo(TV value, T to, F from);
}
在R中做到这一点,但是Python中似乎没有类似的东西。
R当量:
offset
因此,在此示例中,x和z是我们的自变量,并且x是由模型预测的,但我们已指定z的影响为0.2
答案 0 :(得分:1)
使用statsmodels,您可以 在Python中使用style similar to R进行回归分析。在回归函数的 some 中,您会发现offset
作为自变量。一个示例是GLM。
具有这样的数据集:
import statsmodels.formula.api as smf
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(8, 3), columns=list('yxz'))
df
# y x z
# 0 0.091761 -1.987569 -0.219672
# 1 0.357113 1.477894 -0.518270
# 2 -0.808494 -0.501757 0.915402
# 3 0.328751 -0.529760 0.513267
# 4 0.097078 0.968645 -0.702053
# 5 -0.327662 -0.392108 -1.463515
# 6 0.296120 0.261055 0.005113
# 7 -0.234587 -1.415371 -0.420645
您可以这样做:
known = 0.2
res1 = smf.glm('y ~ x', data = df, offset=known*df['z']).fit()
print(res1.summary())
# ==============================================================================
# Dep. Variable: y No. Observations: 8
# Model: GLM Df Residuals: 6
# .
# .
# ==============================================================================
# coef std err z P>|z| [0.025 0.975]
# ------------------------------------------------------------------------------
# Intercept 0.0614 0.165 0.373 0.709 -0.261 0.384
# x 0.1478 0.148 0.995 0.320 -0.143 0.439
# ==============================================================================
您还可以通过手动执行相同的操作来运行健全性检查。您可以这样创建一个偏移量:
offset = known*df['z']
y_offset = df['y']-offset
df2 = pd.concat([pd.Series(y_diff), df['x']], axis = 1)
df2.columns = ['y_diff', 'x']
res2 = smf.glm('y_offset ~ x', data = df2).fit()
print(res2.summary())
# ==============================================================================
# Dep. Variable: y_offset No. Observations: 8
# Model: GLM Df Residuals: 6
# .
# .
# ==============================================================================
# coef std err z P>|z| [0.025 0.975]
# ------------------------------------------------------------------------------
# Intercept 0.0614 0.165 0.373 0.709 -0.261 0.384
# x 0.1478 0.148 0.995 0.320 -0.143 0.439
# ==============================================================================