一、原始数据介绍
数据集描述
本次课程设计使用的数据集来自《赫芬顿邮报》2012年至2022年的新闻标题,包含约210k条新闻记录。该数据集是最大的新闻数据集之一,适用于多种自然语言处理任务。数据集可在Kaggle上获取。
数据字段
category : 新闻的类别,数据集中包含42个类别。
headline : 新闻标题。
authors : 文章作者列表。
link : 原始新闻文章的链接。
short_description : 新闻摘要。
date : 文章发布日期。
数据分布
通过对类别进行统计分析,发现“POLITICS”类别的文章数量最多。以下是类别分布的直方图代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import matplotlib.pyplot as pltimport pandas as pdplt.rcParams['font.sans-serif' ] = ['SimHei' ] plt.rcParams['axes.unicode_minus' ] = False plt.figure(figsize=(25 , 15 )) cmapper = plt.cm.tab20.colors ax = df['category' ].value_counts().sort_values(ascending=False ).plot.bar(color=cmapper, legend=True ) for i, v in enumerate (ax.patches): ax.text(i, v.get_height(), str (v.get_height()), ha='center' , va='bottom' ) plt.xticks(rotation=50 ) plt.xlabel("新闻种类" ) plt.ylabel("文章数量" ) plt.title("新闻种类与文章数量分布图" ) plt.grid(True ) plt.show()
选择标题和简介作为文本内容以及文本新闻标题作为最后的数据集,用文本内容来分类文章分类。
词云展示
为了进一步分析各类新闻的文本特征,生成了词云。以下是词云的代码:
1 2 3 4 5 6 7 8 9 10 from wordcloud import WordCloudimport matplotlib.pyplot as pltplt.figure(figsize=(12 , 12 )) wc = WordCloud(max_words=1000 , background_color='white' , colormap='viridis' , stopwords=STOPWORDS).generate(' ' .join(final_df['category' ])) plt.imshow(wc, interpolation="bilinear" ) plt.axis('off' ) plt.title("41个文章类型的词云" , size=20 , weight='bold' , color='black' , y=1.05 ) plt.show()
二、数据预处理
数据清洗
在数据预处理阶段,我们首先检查数据的完整性,发现数据集中并无空值,因此无需进行补齐或删除操作。
接下来,我们对文本数据进行了清洗,去除了无关符号和停用词。以下是清洗代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import refrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerdef datacleaning (text ): whitespace = re.compile (r"\s+" ) user = re.compile (r"(?i)@[a-z0-9_]+" ) text = whitespace.sub(' ' , text) text = user.sub('' , text) text = re.sub(r"\[[^()]*\]" , "" , text) text = re.sub("\d+" , "" , text) text = re.sub(r'[^\w\s]' , '' , text) text = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)" , "" , text) text = text.lower() text = [word for word in text.split() if word not in stopwords.words('english' )] sentence = [] lemmatizer = WordNetLemmatizer() for word in text: sentence.append(lemmatizer.lemmatize(word, 'v' )) return ' ' .join(sentence)
文本向量化
为了将文本数据转换为模型可处理的格式,我们选择了TF-IDF向量化方法。TF-IDF能够反映单词在文档集合中的重要性,适用于文本分类任务。以下是向量化代码:
1 2 3 4 from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer(min_df=0.0 , max_df=1.0 , ngram_range=(1 , 2 ), sublinear_tf=True ) X = vectorizer.fit_transform(summary_df['length_of_news' ])
数据集划分
我们将数据集划分为训练集和测试集,测试集占比为20%。以下是划分代码:
1 2 3 from sklearn.model_selection import train_test_splitlength_of_news_train, length_of_news_test, category_train, category_test = train_test_split(length_of_news, category, test_size=0.2 , random_state=41 )
三、模型评估标准
在模型评估中,我们引入了混淆矩阵(Confusion Matrix)作为主要评估工具。混淆矩阵通过展示模型预测结果与实际标签之间的关系,能够直观地反映模型的分类性能。主对角线上的值表示正确分类的样本数量,非对角线上的值表示错误分类的样本数量。
四、模型训练
支持向量机(SVM)
我们使用SVM作为分类模型,并尝试了三种不同的核函数:线性核、多项式核和高斯核(RBF核)。以下是模型训练代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from sklearn.svm import SVCimport picklewith open ('tv_X_train.pkl' , 'rb' ) as f: X_train = pickle.load(f) with open ('tv_y_train.pkl' , 'rb' ) as f: y_train = pickle.load(f) with open ('tv_X_test.pkl' , 'rb' ) as f: X_test = pickle.load(f) with open ('tv_y_test.pkl' , 'rb' ) as f: y_test = pickle.load(f) classifier = SVC(kernel='rbf' , gamma='scale' , probability=True ) classifier.fit(X_train, y_train)
模型性能分析
线性核SVM :适用于线性可分的数据集。测试结果显示,该数据集具有一定的非线性特征。
多项式核SVM :能够处理非线性数据,通过调整多项式核的阶数和系数,性能有所提升。
高斯核SVM :通过调整γ参数,能够更好地适应数据的复杂性。测试结果显示,相比于多项式核,性能有所提升,但提升幅度有限。
五、模型结果与分析
分类效果
在所有类别中,“QUEER VOICES”类别的分类效果最好,而“WELLNESS”类别的分类效果最差,其与“HEALTHY LIVING”类别的误判率较高。这可能是因为“QUEER VOICES”具有较为独特的特征,而“WELLNESS”和“HEALTHY LIVING”在特征空间中较为接近,难以区分。
核函数与参数优化
核函数的选择及其参数对模型性能有显著影响。多项式核和高斯核的参数优化是提升模型性能的关键。例如,γ参数在高斯核中控制决策边界的复杂度,过高或过低的γ值都会影响模型性能。
未来工作
未来,我们将探索深度学习技术,如循环神经网络(RNN)和卷积神经网络(CNN),以进一步提升新闻分类的准确率。同时,提高模型的可解释性也是我们的研究重点,这将帮助我们更好地理解模型的决策机制。
此外,我们的模型可以应用于新闻内容推荐系统,通过自动化的新闻分类提高推荐的准确性和相关性。
六、总结
本次课程设计成功实现了新闻分类的目标,并深入分析了核函数选择和参数优化对模型性能的影响。未来,我们将继续探索深度学习技术,推动新闻分类技术的进步。