用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%'))

结果现在看起来像这样

enter image description here

但是我希望它看起来像这样

enter image description here

解决方法

接下来是使用kable()中的knitradd_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文档中运行了先前的代码,结果为下一个:

enter image description here

还必须将库knitrkableExtra添加到代码中。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...