机器学习项目一:虚假新闻检测
目录
一、导入相关包
二、加载数据
二、文本预处理
处理流程:
三、数据预处理
1.数据分割
四、建立模型
1.创建管道
五、模型训练与评估
六、模型保存
一、导入相关包
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.metrics import accuracy_score,confusion_matrix,classification_report
from sklearn.pipeline import Pipeline
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
关键点:导入了完整的文本处理和分析工具链,包括:
TfidfVectorizer:将文本转换为数值特征
PassiveAggressiveClassifier:适合文本分类的在线学习算法
WordNetLemmatizer:比词干提取更高级的词汇归一化方法
二、加载数据
下载数据
nltk.download(['stopwords','wordnet']) # 首次使用nltk包需要下载
1.数据加载函数
def load_data(filepath):
df=pd.read_csv(filepath)
assert 'text' in df.columns, "数据必须包含text列
assert 'label' in df.columns, "数据必须包含label列"
returndf
二、文本预处理
class TextPreprocessor:
def __init__(self):
self.stop_words=set(stopwords.words('english'))
self.lemmatizer =WordNetLemmatizer()
def clean_text(self,text):
text=text.lower()
text=re.sub(r'[^\w\s]', '',text)
text=re.sub(r'\d+','',text)
words=text.split()
words=[self.lemmatizer.lemmatize(w) for w in words
if w not in self.stop_words and len(w)>2]
return ' '.join(words)
处理流程:
1.转为小写(降低大小写敏感性)
2.移除标点符号(保留字母数字和空格)
3.删除数字(新闻分类中数字通常无意义)
4.词形还原(将单词还原为词典形式)
5.过滤短词和停用词
三、数据预处理
先将数据中的text文本每一条都经过上面的文本预处理阶段
preprocessor=TextPreprocessor()
df['cleaned_text']=df['text'].apply(preprocessor.clean_text)
1.数据分割
x_train,x_text,y_train,y_test=train_test_split(
df['cleaned_text'],
df['label'],
test_size=0.2,
random_state=39,
stratify=df['label']
)
四、建立模型
1.创建管道
model=Pipeline([
('tfidf',TfidfVectorizer(
stop_words='english',
max_df=0.7,
min_df=0.001,
ngram_range=(1,2),
sublinear_tf=True
)),
('classifier',PassiveAggressiveClassifier(
max_iter=100,
early_stopping=True,
validation_fraction=0.2,
random_state=39
))
])
TF-IDF参数:
ngram_range=(1,2):同时考虑单词和双词组合
sublinear_tf=True:使用1+log(tf)平滑词频
分类器参数:
early_stopping:防止过拟合
validation_fraction:早停验证集比例
五、模型训练与评估
model.fit(x_train,y_train)
y_pred=model.predict(x_test) # 修正变量名x_text为x_test
print('\n评估结果:')
print(f"准确率:{accuracy_score(y_test,y_pred):.2%}")
print("\n分类报告")
print(classification_report(y_test,y_pred,target_names=['FAKE','REAL']))
print("\n混淆矩阵")
print(confusion_matrix(y_test,y_pred,labels=['FAKE','REAL']))
评估指标:
准确率:整体分类正确率
分类报告:包含精确率、召回率、F1值
混淆矩阵:显示具体分类情况
六、模型保存
import joblib
joblib.dump(model,'news_classifier.pkl')