R e1071 SVM模型twitter分类

R e1071 SVM model twitter classification

我一直在使用 e1071 库对文本进行分类。我已经能够使用 NB 算法,但很难应用 SVM。 我一直在关注 Cran website

的指南

网站有一段代码没有解释对象类型以及我如何为自己的代码获取它。

> svm
> svm.model <- svm(Type ~ ., data = trainset, cost = 100, gamma = 1)
> svm.pred <- predict(svm.model, testset[,-10])

我的代码:

library(e1071)
library(dplyr)
library(caret)
library(rpart)



df<- read.csv("C:/Users/Suki/Projects/RProject/tweets.csv", stringsAsFactors = FALSE)


trainSVM <- apply(dtm.train.svm, 2, convert_count)
testSVM <- apply(dtm.test.svm, 2, convert_count)

svm.model <- svm(Type~., data = trainSVM, cost = 100, gamma = 1)
svm.pred <- predict(svm.model, testSVM)

我没能找到解释,但看到了另一个类似的例子。我是否相信 'Type' 是我希望 SVM 模型预测的结果?正如我到目前为止所做的那样,我不确定我如何能够为 SVM 模型提供该信息。

感谢您的宝贵时间和帮助。

Type ~ . 是将模型定义为 "Values in column Type are dependent on values in all other columns" 的公式。我们无权访问您的数据文件,因此让我们考虑内置数据集 iris:

head( iris )   ## Look at the first few rows of the data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# ...

假设我想根据所有其他列中的值预测列 Species 中的值。我可以定义对应的模型为Species ~ .。或者,如果我只想使用某些列,我会将它们放在 ~ 的右侧。例如,Species ~ Sepal.Length + Petal.Length 将仅使用 *Length 列。

现在我有了我的数据集和公式,我可以使用您在答案中提供的代码训练我的 SVM

myModel <- e1071::svm( Species ~ ., data = iris )

出于演示目的,我们可以将模型应用回训练数据以检索预测

predict( myModel, iris )
#           1          2          3          4          5          6          7
#      setosa     setosa     setosa     setosa     setosa     setosa     setosa
#           8          9         10         11         12         13         14
#      setosa     setosa     setosa     setosa     setosa     setosa     setosa
# ...

最后,请注意 svm 函数有另一种方法来提供数据/标签(查看 ?e1071::svm)。以下是训练模型的等效方法:

e1071::svm( iris[,1:4], iris[,5] )  # Predict Column 5 values from Column 1:4 values