gpt4 book ai didi

r - 插入符号包自定义指标

转载 作者:行者123 更新时间:2023-12-04 05:11:53 25 4
gpt4 key购买 nike

我在我的一个项目中使用插入符号函数“train()”,我想添加
“自定义指标”F1 分数。我看了这个网址 caret package
但我无法理解如何使用可用参数构建此分数。

有一个自定义指标的示例,如下所示:

## Example with a custom metric
madSummary <- function (data,
lev = NULL,
model = NULL) {
out <- mad(data$obs - data$pred,
na.rm = TRUE)
names(out) <- "MAD"
out
}
robustControl <- trainControl(summaryFunction = madSummary)
marsGrid <- expand.grid(degree = 1, nprune = (1:10) * 2)
earthFit <- train(medv ~ .,
data = BostonHousing,
method = "earth",
tuneGrid = marsGrid,
metric = "MAD",
maximize = FALSE,
trControl = robustControl)

更新:

我试过你的代码,但问题是它不能像下面的代码一样处理多个类(显示 F1 分数,但很奇怪)我不确定,但我认为函数 F1_score 只适用于二进制类
library(caret)
library(MLmetrics)

set.seed(346)
dat <- iris

## See http://topepo.github.io/caret/training.html#metrics
f1 <- function(data, lev = NULL, model = NULL) {

print(data)
f1_val <- F1_Score(y_pred = data$pred, y_true = data$obs)
c(F1 = f1_val)
}

# Split the Data into .75 input
in_train <- createDataPartition(dat$Species, p = .70, list = FALSE)

trainClass <- dat[in_train,]
testClass <- dat[-in_train,]



set.seed(35)
mod <- train(Species ~ ., data = trainClass ,
method = "rpart",
metric = "F1",
trControl = trainControl(summaryFunction = f1,
classProbs = TRUE))

print(mod)

我也编写了一个手动 F1 分数,其中一个输入是混淆矩阵:(我不确定我们是否可以在“summaryFunction”中有一个混淆矩阵
F1_score <- function(mat, algoName){

##
## Compute F1-score
##


# Remark: left column = prediction // top = real values
recall <- matrix(1:nrow(mat), ncol = nrow(mat))
precision <- matrix(1:nrow(mat), ncol = nrow(mat))
F1_score <- matrix(1:nrow(mat), ncol = nrow(mat))


for(i in 1:nrow(mat)){
recall[i] <- mat[i,i]/rowSums(mat)[i]
precision[i] <- mat[i,i]/colSums(mat)[i]
}

for(i in 1:ncol(recall)){
F1_score[i] <- 2 * ( precision[i] * recall[i] ) / ( precision[i] + recall[i])
}

# We display the matrix labels
colnames(F1_score) <- colnames(mat)
rownames(F1_score) <- algoName

# Display the F1_score for each class
F1_score

# Display the average F1_score
mean(F1_score[1,])
}

最佳答案

你应该看看The caret Package - Alternate Performance Metrics详情。一个工作示例:

library(caret)
library(MLmetrics)

set.seed(346)
dat <- twoClassSim(200)

## See https://topepo.github.io/caret/model-training-and-tuning.html#metrics
f1 <- function(data, lev = NULL, model = NULL) {
f1_val <- F1_Score(y_pred = data$pred, y_true = data$obs, positive = lev[1])
c(F1 = f1_val)
}

set.seed(35)
mod <- train(Class ~ ., data = dat,
method = "rpart",
tuneLength = 5,
metric = "F1",
trControl = trainControl(summaryFunction = f1,
classProbs = TRUE))

关于r - 插入符号包自定义指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37666516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com