给我一个svm对文本三分类的代码
时间: 2024-05-12 16:12:56 浏览: 15
以下是一个简单的 SVM 对文本三分类的 Python 代码示例:
```python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
# 生成训练数据
train_data = ['This is the first document', 'This is the second document', 'This is the third document', 'This is the fourth document']
train_labels = [0, 1, 2, 0]
# 将文本转换成向量
vectorizer = TfidfVectorizer()
train_vectors = vectorizer.fit_transform(train_data)
# 训练 SVM 模型
svm_model = svm.SVC(kernel='linear')
svm_model.fit(train_vectors, train_labels)
# 测试数据
test_data = ['This is the fifth document', 'This is the sixth document', 'This is the seventh document']
test_vectors = vectorizer.transform(test_data)
# 预测结果
pred_labels = svm_model.predict(test_vectors)
# 输出预测结果
print(pred_labels)
```
在这个示例中,我们使用 TfidfVectorizer 将文本转换成向量,并使用 SVM 模型进行分类。训练数据包含四个文本,每个文本都有一个标签,分别为 0、1、2、0。我们使用 fit_transform 函数将训练数据转换成向量,然后使用 svm.SVC 函数训练 SVM 模型。测试数据包含三个文本,我们使用 transform 函数将其转换成向量,并使用 predict 函数预测其标签。最后,我们输出预测结果。