SVM情感分类python
时间: 2023-10-14 20:26:39 浏览: 91
python情感分类
5星 · 资源好评率100%
以下是使用Python实现SVM情感分类的示例代码:
1. 导入必要的库和数据
```python
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklearn.metrics import classification_report
# 读取数据
data = pd.read_csv("sentiment_data.csv")
```
2. 数据预处理
```python
# 分割数据集
train_data = data[:5000]
test_data = data[5000:]
# 提取特征
tfidf = TfidfVectorizer(stop_words='english')
train_features = tfidf.fit_transform(train_data['text'])
test_features = tfidf.transform(test_data['text'])
# 提取标签
train_labels = train_data['label']
test_labels = test_data['label']
```
3. 训练SVM模型并进行预测
```python
# 训练SVM模型
clf = svm.SVC(kernel='linear')
clf.fit(train_features, train_labels)
# 进行预测
predicted_labels = clf.predict(test_features)
```
4. 评估模型性能
```python
# 输出分类报告
print(classification_report(test_labels, predicted_labels))
```
完整代码:
```python
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklearn.metrics import classification_report
# 读取数据
data = pd.read_csv("sentiment_data.csv")
# 分割数据集
train_data = data[:5000]
test_data = data[5000:]
# 提取特征
tfidf = TfidfVectorizer(stop_words='english')
train_features = tfidf.fit_transform(train_data['text'])
test_features = tfidf.transform(test_data['text'])
# 提取标签
train_labels = train_data['label']
test_labels = test_data['label']
# 训练SVM模型
clf = svm.SVC(kernel='linear')
clf.fit(train_features, train_labels)
# 进行预测
predicted_labels = clf.predict(test_features)
# 输出分类报告
print(classification_report(test_labels, predicted_labels))
```
其中,"sentiment_data.csv"是包含文本和标签的数据集文件。可以根据实际情况替换成其他数据集文件。
阅读全文