提问人:user8259971408 提问时间:11/9/2023 更新时间:11/9/2023 访问量:29
我怎样才能使它们具有相同的水平?
How can I make these have the same levels?
问:
我在cm.glm行上遇到了以下错误:
错误:应该是具有相同水平的因子。data
reference
# Predict using Logistic Regression
pred.glm <- ifelse(predict(fit.glm, irisTest) > 0.5, "setosa", "other")
cm.glm <- confusionMatrix(pred.glm, (irisTest$Species))
acc.glm <- cm.glm$overall['Accuracy']
prec.glm <- cm.glm$byClass['Pos Pred Value']
rec.glm <- cm.glm$byClass['Sensitivity']
# Load libraries
library(MASS)
library(caret)
library(nnet)
# Loading iris dataset
data(iris)
# Convert it into a binary class dataset
iris$Species <- ifelse(iris$Species == "setosa", "setosa", "other")
# Split the dataset
set.seed(123)
trainIndex <- createDataPartition(iris$Species, p = .8,
list = FALSE,
times = 1)
irisTrain <- iris[ trainIndex,]
irisTest <- iris[-trainIndex,]
# Fit Logistic Regression
fit.glm <- multinom(Species ~ ., data = iris)
# Predict using Logistic Regression
pred.glm <- ifelse(predict(fit.glm, irisTest) > 0.5, "setosa", "other")
cm.glm <- confusionMatrix(pred.glm, (irisTest$Species))
acc.glm <- cm.glm$overall['Accuracy']
prec.glm <- cm.glm$byClass['Pos Pred Value']
rec.glm <- cm.glm$byClass['Sensitivity']
答:
1赞
snaut
11/9/2023
#1
您的代码有两个问题。
首先,默认情况下会给出最有可能的类,以与必须用作参数的链接函数的截止值进行比较。predict
type="probs"
其次,预计这两个参数是具有相同水平的因子。只需将向量转换为因子即可。如果其中一个集合没有两个因子水平(其他种子可能会发生这种情况),请显式指定因子水平。confusionMatrix
然后,您的两行代码应如下所示:
pred.glm <- ifelse(predict(fit.glm, irisTest, type="probs") > 0.5, "setosa", "other")
cm.glm <- confusionMatrix(
factor(pred.glm, levels = c("setosa", "other")),
factor(irisTest$Species, levels = c("setosa", "other"))
)
评论
multinom