问题描述
我正在绘制使用caret
训练的年度模型的重采样准确性得分的箱线图。
这些模型以其引用的年份命名:2000、2001、2002,...,2010。
我希望模型以年份(即模型名称)为基础,以升序显示在方框图中。
fit.year.res <- resamples(fit.year)
summary(fit.year.res)
看起来像这样:
但是,箱形图中不同的年度模型未排序:
scales <- list(x=list(relation="free"),y=list(relation="free"))
bwplot(fit.year.res,scales=scales)
我曾尝试将重采样fit.year.res$models
的models元素转换为角色特征,但这没什么区别。
解决方法
我不知道使用插入符号包中的bwplot
方法的简单解决方案。也许只有一种,但是我缺乏格子技巧。我建议使用ggplot2手动绘制方框图。这样,您将可以更好地控制最终情节。
由于您没有发布带有数据的示例,因此我将使用?caret:::bwplot.resamples
library(caret)
library(party)
library(RWeka)
load(url("http://topepo.github.io/caret/exampleModels.RData"))
resamps <- resamples(list(CART = rpartFit,CondInfTree = ctreeFit,MARS = earthFit))
bwplot(resamps,metric = "RMSE")
产生:
要使用ggplot手动制作图,您将需要一些数据操作:
library(tidyverse)
resamps$values %>% #extract the values
select(1,ends_with("RMSE")) %>% #select the first column and all columns with a name ending with "RMSE"
gather(model,RMSE,-1) %>% #convert to long table
mutate(model = sub("~RMSE","",model)) %>% #leave just the model names
ggplot()+ #call ggplot
geom_boxplot(aes(x = RMSE,y = model)) -> p1 #and plot the box plot
p1
要在y轴上设置特定顺序:
p1 +
scale_y_discrete(limits = c("MARS","CART","CondInfTree"))
如果您喜欢晶格
library(lattice)
resamps$values %>%
select(1,ends_with("RMSE")) %>%
gather(model,-1) %>%
mutate(model = sub("~RMSE",model)) %>%
{bwplot(model ~ RMSE,data = .)}
更改顺序可更改模型级别(此方法也适用于ggplot2):
resamps$values %>%
select(1,model),model = factor(model,levels = c("MARS","CondInfTree"))) %>%
{bwplot(model ~ RMSE,data = .)}
,
函数bwplot.resamples
用于生成该图,如果您查看underlying code,变量将根据它们在关注指标下的平均性能进行分解。
下面有执行分解的相关代码:
bwplot.resamples <- function (x,data = NULL,models = x$models,metric = x$metric,...)
{
....
avPerf <- ddply(subset(plotData,Metric == metric[1]),.(Model),function(x) c(Median = median(x$value,na.rm = TRUE)))
avPerf <- avPerf[order(avPerf$Median),]
......
}
我想您需要做的是手动绘制情节:
data(BloodBrain)
gbmFit <- train(bbbDescr[,-3],logBBB,"gbm",tuneLength=6,trControl = trainControl(method = "cv"),verbose=FALSE)
glmnetFit <- train(bbbDescr[,"glmnet",trControl = trainControl(method = "cv"))
rfFit <- train(bbbDescr[,"rf",trControl = trainControl(method = "cv"))
knnFit <- train(bbbDescr[,"knn",trControl = trainControl(method = "cv"))
resamps <- resamples(list(gbm = gbmFit,glmnet=glmnetFit,knn=knnFit,rf=rfFit))
如果进行绘图,您会看到它们根据中位数(实心点)进行了排序:
bwplot(resamps,metric="MAE")
您可以访问$ values下的值并制作一个函数来绘制它,如下所示:
plotMet = function(obj,metric,var_order){
mat = obj$values
mat = mat[,grep(metric,colnames(mat))]
colnames(mat) = gsub("[~][^ ]*",colnames(mat))
boxplot(mat[,var_order],horizontal=TRUE,las=2,xlab=metric)
}
plotMet(resamps,"MAE",c("rf","glmnet"))
用数字命名模型也不是一个好主意。尝试使用诸如model_2000,model_2001等