You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用mlogit模型时,传入by数据框至predictions函数报错求助

解决mlogit模型调用marginaleffects::predictions()的报错问题

问题场景

复现联合分析案例时,已构建mlogit模型:

model_chocolate_mlogit

Call:
mlogit(formula = choice ~ dark + soft + nuts | 0 | 0, data = chocolate_idx,     method = "nr")


  Coefficients:
    darkDark  softSoft  nutsNuts  
      1.3863   -2.1972    0.8473  

创建by数据框后调用predictions():

by <- data.frame(dark = c("Milk", "Dark"), by = c("Milk", "Dark"))

preds_chocolate_mlogit <- predictions(
  model_chocolate_mlogit,
  by = by
)

触发报错:

Error: Unable to compute predicted values with this model. You can try to supply a different dataset to the `newdata` argument. This error was
  also raised:
  
  <text>:2:0: unexpected end of input
1: . ~   . |  . |  . |  
   ^
  
  Bug Tracker: https://github.com/vincentarelbundock/marginaleffects/issues

报错原因

marginaleffects对mlogit模型的by参数用法有特殊要求,直接传入自定义by数据框会导致模型公式解析失败;同时mlogit模型依赖长格式数据(包含chid和alt列),需要明确指定预测数据集的特征组合。

解决方法

方法1:使用datagrid()生成规范的预测数据集

先构造包含目标特征组合的预测数据集,再传入predictions():

library(marginaleffects)

# 生成预测数据集:固定soft、nuts为基准水平,仅vary dark的取值
newdata <- datagrid(
  model = model_chocolate_mlogit,
  dark = c("Milk", "Dark"),
  soft = "Hard",  # 替换为你数据中soft的基准水平(如原始数据的参考组)
  nuts = "No"     # 替换为你数据中nuts的基准水平
)

# 计算预测概率
preds_chocolate_mlogit <- predictions(
  model_chocolate_mlogit,
  newdata = newdata,
  type = "probs"  # 明确指定预测类型为概率,适配mlogit模型
)

方法2:直接用特征列名作为by参数

如果只需按dark分组计算平均预测值,可直接传入列名,无需自定义by数据框:

preds_chocolate_mlogit <- predictions(
  model_chocolate_mlogit,
  by = "dark",
  type = "probs"
)

额外注意事项

  1. 确保你的chocolate_idx数据是mlogit要求的长格式,包含chid(案例ID)和alt(备选方案ID)列。
  2. 升级marginaleffects到最新版本,避免旧版本对mlogit的兼容问题:
update.packages("marginaleffects")

内容的提问来源于stack exchange,提问作者jonas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 06:55:05