我有一个混合效应逻辑回归模型:
quietly melogit y i.x1 i.x2 || x3:
变量 x1 编码为 0/1。我为 x1 的两个值创建预测概率:
margins x1
然后我获得模型中包含的每个观测值的预测概率:
predict probhat if e(sample)
summarize probhat
为了进行样本外预测,我使用相同的变量加载第二个数据集:
use "C:\file path\newdata.dta", clear
现在我可以获得新数据集中每个观测值的预测概率:
predict probhat_new
summarize probhat_new
我的问题是:如何获取“margins”命令为原始数据集创建的内容,但为新数据集创建的内容?
margins x1
Stata 返回:
e(sample) does not identify the estimation sample
我还尝试通过计算 x1 每个值的概率平均值来重新创建基于“利润”的原始输出,希望我可以使用相同的方法来获得样本外子组预测概率:
summarize probhat if x1== 0, meanonly
scalar mean_probhat_x1_0 = r(mean)
gen mean_probhat=.
replace mean_probhat = mean_probhat_x1_0 if x1== 0
summarize mean_probhat
但是,基于此代码的平均值与基于“margins”命令的 x1==0 的平均值不同。
我还尝试了另一种方法:
egen mean_probhat = mean(probhat), by(x1)
tab mean_probhat
但这也不会产生正确的结果。
您可以使用
estimates esample:
重置估计样本;参见help estimates esample
。正如帮助文件所解释的,您可以轻松修改命令来指定子样本(例如,特定变量中具有非缺失值的子样本),但在这里我只是将整个数据集设置为估计样本。
最小可重现示例:
webuse bangladesh, clear
qui: melogit c_use i.urban age i.children || district:
margins urban
webuse bangladesh, clear // clears the estimation sample: e(sample) == 0 for all obs
estimates esample: // resets estimation sample: e(sample) == 1 for all obs
margins urban