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

R-Markdown编译PDF时机器学习代码块运行缓慢且报错求助

问题解决思路

1. 修复LaTeX编译错误

错误信息明确指向\(X_\min\)这一行,LaTeX中下标包含多个字符或命令时必须用大括号{}包裹,否则会触发解析错误。将该行修改为:

\(X_{\min}\) is the minimum value of the feature across the dataset

即可解决"Missing { inserted}"的编译失败问题。

2. 解决机器学习代码块运行过慢的问题

R Markdown默认每次编译都会重新执行所有代码块,KNN、随机森林这类计算密集型模型的训练过程会大幅拉长编译时间,可通过以下方式优化:

  • 启用代码块缓存:给机器学习代码块添加cache=TRUE参数,第一次运行后会自动缓存结果,后续编译直接调用缓存,无需重复训练模型。修改后的KNN代码块示例:
    {r knn, include=FALSE, cache=TRUE}
    
    library(class)  # Load the class library for KNN
    
    # Define the number of neighbors
    k <- 5  # You can adjust this value based on your preference or cross-validation results
    
    # Train the KNN model
    knn_model <- knn(train = x_train_final, test = x_test_final, cl = y_train, k = k)
    
    # Make predictions using the test set
    knn_predictions <- as.factor(knn_model)
    
    # Check the performance with respect to y_test
    knn_accuracy <- mean(knn_predictions == y_test)
    print(paste("Accuracy of KNN model:", knn_accuracy))
    
    # You can also calculate other performance metrics like confusion matrix, precision, recall, F1-score, etc. based on your requirement
    
    # To calculate AUC for KNN, you can use the pROC package
    library(pROC)
    knn_auc <- auc(roc(as.numeric(y_test) - 1, as.numeric(knn_predictions) - 1))
    print(paste("AUC of KNN model:", knn_auc))
    
  • 数据集与参数优化:若数据集规模过大,可尝试特征降维(如PCA)、采样缩小数据集,或调整模型参数(如KNN调小k值、随机森林减少树的数量)来降低计算量。

额外提示

关于TinyTeX版本更新提示,若当前LaTeX编译未受包缺失影响,可暂时忽略;后续若出现包依赖问题,再执行tinytex::reinstall_tinytex(repository = "illinois")升级即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 04:43:38