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

使用e1071的svm预测时忽略quanteda生成的dfm新输入问题

问题:e1071的SVM模型预测quanteda DFM时忽略newx参数

问题现象

使用e1071包的svm()训练quanteda生成的文档特征矩阵(DFM)后,调用predict()传入验证集DFM时,函数会忽略newx参数,返回训练集的预测结果而非验证集的。即便已经用dfm_match()确保训练集和验证集特征完全一致,问题依然存在。

复现代码

library("textdata")
library("quanteda")
library("e1071")
d <- dataset_ag_news()
d_train <- d[1:1000,]
d_val <- d[1001:2000,]
dfm_train <- dfm(tokens(d_train$description))
y_train <- as.factor(d_train$class)
dfm_val <- dfm(tokens(d_val$description))
dfm_val <- dfm_match(dfm_val, features = featnames(dfm_train))
svm_fit <- svm(x=dfm_train, y=y_train, kernel="radial", cost=10)
predictions_val <- predict(svm_fit, newx=dfm_val, type="class")
predictions_train <- predict(svm_fit, type="class")
# 输出结果会显示两者完全相同
table(predictions_val)
table(predictions_train)

问题原因

quanteda的DFM是S4类对象,e1071包的predict.svm()函数对这类对象的newx参数处理存在兼容性问题,无法正确识别验证集的DFM输入,因此默认调用训练阶段的数据集进行预测。而glmnet包对S4对象的兼容性更好,所以相同流程可以正常运行。

解决方案

将DFM转换为普通矩阵后再进行训练和预测,e1071的SVM可以正常处理矩阵格式的数据:

修改后的训练代码

# 将DFM转换为矩阵
svm_fit <- svm(x=as.matrix(dfm_train), y=y_train, kernel="radial", cost=10)

修改后的预测代码

# 同样将验证集DFM转换为矩阵
predictions_val <- predict(svm_fit, newx=as.matrix(dfm_val), type="class")

修改后重新运行代码,predictions_val会正确输出验证集的预测结果,与predictions_train不再一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:42:48