计算预测值
在实际应用中,我们常常希望使用拟合好的逻辑回归来估计概率,并为这些估计构建置信区间。基于 wells 数据集和模型 'switch ~ arsenic',假设您有一些新的观测 wells_test,它们不属于训练样本,您希望预测切换到最近安全水井的概率。
您将使用 .predict() 方法来完成这一任务。
请注意,.predict() 接受以下参数:
exog—— 新的观测(测试数据集)。transform = True—— 将拟合时的公式y ~ x应用于数据。
如果未定义 exog,则会对训练数据集计算概率。
模型 wells_fit 以及数据集 wells 和 wells_test 已预加载到工作区。
本练习是课程的一部分
Python 中的广义线性模型
练习说明
- 使用已拟合的模型
wells_fit,在测试数据wells_test上计算预测值,并保存为prediction。 - 将
prediction添加到已有的数据框wells_test中,并将列名设为prediction。 - 使用
print()显示wells_test的前 5 行,只包含switch、arsenic和prediction列。使用 pandas 的head()函数仅查看前 5 行。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Compute predictions for the test sample wells_test and save as prediction
prediction = ____.predict(exog = ____)
# Add prediction to the existing data frame wells_test and assign column name prediction
____[____] = ____
# Examine the first 5 computed predictions
print(____[[____, ____, ____]].head())