对spam数据集进行tfidf处理实现代码
时间: 2024-04-29 17:25:19 浏览: 80
很高兴回答你的问题!以下是对spam数据集进行tfidf处理的代码:
```python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
# 读取数据集
with open('spam.txt', 'r') as f:
data = f.readlines()
# 分割数据集
X = [d.split('\t')[1].strip() for d in data]
y = [d.split('\t')[0] for d in data]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# tfidf处理
vectorizer = TfidfVectorizer()
X_train_tfidf = vectorizer.fit_transform(X_train)
X_test_tfidf = vectorizer.transform(X_test)
# 训练模型
clf = MultinomialNB()
clf.fit(X_train_tfidf, y_train)
# 预测并计算准确率
y_pred = clf.predict(X_test_tfidf)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
希望这个代码能够帮到你,如果你还有其他问题,欢迎继续提问!
阅读全文