【发布时间】:2018-07-09 06:57:43
【问题描述】:
我想为多项逻辑回归和比例优势模型创建混淆矩阵,但我坚持使用 R 中的实现。我在下面的尝试似乎没有给出所需的输出。
这是我目前的代码:
CH <- read.table("http://data.princeton.edu/wws509/datasets/copen.dat", header=TRUE)
CH$housing <- factor(CH$housing)
CH$influence <- factor(CH$influence)
CH$satisfaction <- factor(CH$satisfaction)
CH$contact <- factor(CH$contact)
CH$satisfaction <- factor(CH$satisfaction,levels=c("low","medium","high"))
CH$housing <- factor(CH$housing,levels=c("tower","apartments","atrium","terraced"))
CH$influence <- factor(CH$influence,levels=c("low","medium","high"))
CH$contact <- relevel(CH$contact,ref=2)
model <- multinom(satisfaction ~ housing + influence + contact, weights=n, data=CH)
summary(model)
preds <- predict(model)
table(preds,CH$satisfaction)
omodel <- polr(satisfaction ~ housing + influence + contact, weights=n, data=CH, Hess=TRUE)
preds2 <- predict(omodel)
table(preds2,CH$satisfaction)
我非常感谢一些关于如何为我的 2 个模型正确生成混淆矩阵的建议!
【问题讨论】:
-
table(preds,CH$satisfaction)为您提供混淆矩阵。如果您想为您的预测提供更多统计信息,您可以使用caret包中的confusionMatrix函数。 -
我相信 table(preds,CH$satisfaction) 很遗憾没有考虑权重。所以总数只是行数,而不是总观察数。有没有办法合并权重?
-
那么也许你可以重塑你的数据集而不是权重列,以将
n作为行数。在这种情况下,每一行都是一个观察结果,而不是观察结果的集合。您可以像这样创建重构的数据集:CH %>% rowwise() %>% mutate(id = list(seq(1:n))) %>% unnest(id) %>% select(-n)并使用它构建模型。
标签: r statistics logistic-regression confusion-matrix multinomial