如何解决用xtable合并几个混淆矩阵
我已经训练了几种模型,并希望用三个混淆矩阵来总结它们的性能。 我要做的是使用xtable
将三个不同的混淆矩阵组合到一个表中。我想合并表1、2和3。使用XGBoost参见下面的示例。
require(xgboost)
require(xtable)
require(caTools)
require(tidyverse)
set.seed(1234)
# Loading data
x1 = c(rnorm(10000,1),rnorm(10000,3,1))
x2 = rnorm(1000)
x3 = rnorm(1000)
class= factor(rep(0:1,each=10000))
df <- as.data.frame(cbind(x1,x2,x3,class))
# Preparing target variable
df$class <- as.numeric(df$class)
df$class <- df$class -1
# Creating a hold-out data
train <- sample.split(df$class,SplitRatio = 0.70)
train.df <- subset(df,train == TRUE)
test.df <- subset(df,train == FALSE)
#Labels.
labels.train <- train.df[c('class')]
labels.test <- test.df[c('class')]
# Dropping target variable.
train.df <- train.df %>%
dplyr::select(-class)
test.df <- test.df %>%
dplyr::select(-class)
# Converting to appropiate format.
train <- xgb.DMatrix(as.matrix(train.df),label = as.matrix(labels.train))
test <- xgb.DMatrix(as.matrix(test.df),label = as.matrix(labels.test))
watchlist <- list(eval = test,train = train)
# Running the model
model <- xgb.train(data=train,watchlist = watchlist,nround = 1000,early_stopping_rounds = 25,objective = "binary:logistic")
# Predictions
pred <- predict(model,test)
# Evaluating the p-distribution.
hist(pred)
# Confusion matrix
table1 <- table(pred > 0.5,labels.test$class)
table2 <- table(pred > 0.25,labels.test$class)
table3 <- table(pred > 0.75,labels.test$class)
print(xtable(table1,caption = 'Threshhold = 50%'))
print(xtable(table2,caption = 'Threshhold = 25%'))
print(xtable(table3,caption = 'Threshhold = 75%'))
结果现在看起来像这样
但是我希望它看起来像这样
解决方法
接下来是使用kable()
中的knitr
,add_header_above()
中的kable_styling()
和kableExtra
的可能解决方案。创建混淆矩阵后,添加以下代码:
#Format table
t1 <- as.data.frame.matrix(table1)
t2 <- as.data.frame.matrix(table2)
t3 <- as.data.frame.matrix(table3)
#Bind
tm <- cbind(t1,t2,t3)
然后下一个代码将生成所需的输出:
kable(tm,"latex",longtable =T,booktabs =T,caption ="Longtable")%>%
add_header_above(c(" ","p=50%"=2,"p=25%"=2,"p=75%"=2))%>%
kable_styling(latex_options =c("repeat_header"))
我已经在rmarkdown
文档中运行了先前的代码,结果为下一个:
还必须将库knitr
和kableExtra
添加到代码中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。