You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中循环训练模型并手动计算Precision、Recall、F1值报错求助

问题与解决方案

问题描述

需要在R中循环运行模型,手动计算Precision、Recall和F1值并存储到表格中,禁止使用caret包的confusionMatrix函数。原代码运行时出现错误:

Error in posPredValue.default(predictions, testing) :  inputs must be factors

错误原因

  1. posPredValue和sensitivity函数的第二个参数需要传入真实分类标签(即testing$class),而非整个测试数据集testing;
  2. 需确保预测值与真实标签的因子水平一致;
  3. 原代码中用模型名称字符串i作为results_table的行索引,会导致赋值错误(results_table的行名默认是数字索引);
  4. 若依赖caret的指标函数,需显式指定正类别,避免因类别顺序导致计算偏差。

修改后的代码(手动计算指标)

完全手动计算混淆矩阵及三个指标,不依赖caret的posPredValue/sensitivity函数,更符合要求:

library(MASS)
library(caret)
data("biopsy")

# 数据预处理
biopsy$ID <- NULL
names(biopsy) <- c('clump thickness','uniformity cell size','uniformity cell shape',
                   'marginal adhesion','single epithelial cell size','bare nuclei',
                   'bland chromatin','normal nuclei','mitosis','class')
biopsy <- na.omit(biopsy)

# 划分训练集测试集
set.seed(123)
inTraining <- createDataPartition(biopsy$class, p = .75, list = FALSE)
training <- biopsy[inTraining,]
testing <- biopsy[-inTraining,]

# 交叉验证控制
control <- trainControl(method="repeatedcv", number=10, repeats=5, verboseIter=F, classProbs=T)

# 定义模型列表
models <- c("svmRadial","rf")
results_table <- data.frame(
  Model = models,
  Precision = numeric(length(models)),
  Recall = numeric(length(models)),
  F1score = numeric(length(models)),
  stringsAsFactors = F
)

# 循环训练模型并计算指标
for (idx in seq_along(models)) {
  model_name <- models[idx]
  # 训练模型
  model_train <- train(class~., data=training, method=model_name,
                       trControl=control, metric="Accuracy")
  # 生成预测
  predictions <- predict(model_train, newdata=testing)
  true_labels <- testing$class
  
  # 手动计算混淆矩阵
  conf_mat <- table(Predicted = predictions, True = true_labels)
  # 提取TN, FP, FN, TP(假设正类别为"malignant",可根据数据集类别调整)
  TN <- conf_mat[1,1]
  FP <- conf_mat[1,2]
  FN <- conf_mat[2,1]
  TP <- conf_mat[2,2]
  
  # 计算指标
  precision <- TP / (TP + FP)
  recall <- TP / (TP + FN)
  f1 <- 2 * precision * recall / (precision + recall)
  
  # 存入结果表
  results_table[idx, "Precision"] <- precision
  results_table[idx, "Recall"] <- recall
  results_table[idx, "F1score"] <- f1
}

# 查看结果
print(results_table)

代码说明

  • 手动构建混淆矩阵,明确提取TP(真阳性)、FP(假阳性)、FN(假阴性)、TN(真阴性);
  • 根据指标公式直接计算Precision、Recall、F1,避免依赖caret的内置函数;
  • 使用位置索引idx遍历模型列表,确保结果表赋值正确;
  • 显式指定正类别(这里biopsy的class水平为benign和malignant,默认将malignant作为正类别,可根据需求调整混淆矩阵的索引)。

内容的提问来源于stack exchange,提问作者thole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 01:20:17