基于机器学习的假新闻检测 -- 机器学习项目基础篇(14)

71 篇文章 5 订阅
35 篇文章 2 订阅

不同平台上的假新闻正在广泛传播,这是一个令人严重关切的问题,因为它导致社会稳定和人们之间建立的纽带的永久破裂。很多研究已经开始关注假新闻的分类。
在这里,我们将尝试在Python中的机器学习的帮助下解决这个问题。

主要步骤

  • 导入库和数据集
  • 数据预处理
  • 新闻栏目的预处理与分析
  • 将文本转换为矢量
  • 模型训练、评估和预测

1. 导入库和数据集

  • Pandas:用于导入数据集。
  • Seaborn/Matplotlib:用于数据可视化。
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = pd.read_csv('News.csv',index_col=0)
data.head()

在这里插入图片描述

2. 数据预处理

data.shape

输出:

(44919, 5)

由于标题、主题和日期栏对新闻的识别没有帮助。所以,我们可以删除这些列。

data = data.drop(["title", "subject","date"], axis = 1)

现在,我们必须检查是否有任何空值(我们将删除那些行)

data.isnull().sum()

输出:

text     0
class    0 

现在我们必须对数据集进行打乱,以防止模型出现偏差。之后我们将重置索引,然后删除它。因为索引列对我们没有用。

# Shuffling
data = data.sample(frac=1)
data.reset_index(inplace=True)
data.drop(["index"], axis=1, inplace=True)

让我们使用下面的代码来探索每个类别中的唯一值。

sns.countplot(data=data,
              x='class',
              order=data['class'].value_counts().index)

在这里插入图片描述

3. 新闻栏目的预处理与分析

首先,我们将从文本中删除所有的停用词,标点符号和任何不相关的空格。NLTK库是必需的,它的一些模块需要下载。因此,运行下面的代码。

from tqdm import tqdm
import re
import nltk
nltk.download('punkt')
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
from wordcloud import WordCloud

一旦我们有了所有需要的模块,我们就可以创建一个函数名预处理文本。此函数将预处理作为输入的所有数据。

def preprocess_text(text_data):
    preprocessed_text = []
      
    for sentence in tqdm(text_data):
        sentence = re.sub(r'[^\w\s]', '', sentence)
        preprocessed_text.append(' '.join(token.lower()
                                  for token in str(sentence).split()
                                  if token not in stopwords.words('english')))
  
    return preprocessed_text

要在文本列中的所有新闻中实现该函数,请运行以下命令。

preprocessed_review = preprocess_text(data['text'].values)
data['text'] = preprocessed_review

让我们分别为假新闻和真实的新闻可视化WordCloud。

# Real
consolidated = ' '.join(
    word for word in data['text'][data['class'] == 1].astype(str))
wordCloud = WordCloud(width=1600,
                      height=800,
                      random_state=21,
                      max_font_size=110,
                      collocations=False)
plt.figure(figsize=(15, 10))
plt.imshow(wordCloud.generate(consolidated), interpolation='bilinear')
plt.axis('off')
plt.show()

在这里插入图片描述

# Fake
consolidated = ' '.join(
    word for word in data['text'][data['class'] == 0].astype(str))
wordCloud = WordCloud(width=1600,
                      height=800,
                      random_state=21,
                      max_font_size=110,
                      collocations=False)
plt.figure(figsize=(15, 10))
plt.imshow(wordCloud.generate(consolidated), interpolation='bilinear')
plt.axis('off')
plt.show()

在这里插入图片描述
现在,让我们绘制前20个最常见单词的条形图。

from sklearn.feature_extraction.text import CountVectorizer
  
  
def get_top_n_words(corpus, n=None):
    vec = CountVectorizer().fit(corpus)
    bag_of_words = vec.transform(corpus)
    sum_words = bag_of_words.sum(axis=0)
    words_freq = [(word, sum_words[0, idx])
                  for word, idx in vec.vocabulary_.items()]
    words_freq = sorted(words_freq, key=lambda x: x[1],
                        reverse=True)
    return words_freq[:n]
  
  
common_words = get_top_n_words(data['text'], 20)
df1 = pd.DataFrame(common_words, columns=['Review', 'count'])
  
df1.groupby('Review').sum()['count'].sort_values(ascending=False).plot(
    kind='bar',
    figsize=(10, 6),
    xlabel="Top Words",
    ylabel="Count",
    title="Bar Chart of Top Words Frequency"
)

在这里插入图片描述

4. 将文本转换为矢量

在将数据转换为矢量之前,将其分为训练和测试。

from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
  
x_train, x_test, y_train, y_test = train_test_split(data['text'], 
                                                    data['class'], 
                                                    test_size=0.25)

现在我们可以使用TfidfVectorizer将训练数据转换为向量。

from sklearn.feature_extraction.text import TfidfVectorizer
  
vectorization = TfidfVectorizer()
x_train = vectorization.fit_transform(x_train)
x_test = vectorization.transform(x_test)

5. 模型训练、评估和预测

现在,数据集已经准备好可以训练模型。
对于训练,我们将使用Logistic回归并使用accuracy_score评估预测准确性。

from sklearn.linear_model import LogisticRegression
  
model = LogisticRegression()
model.fit(x_train, y_train)
  
# testing the model
print(accuracy_score(y_train, model.predict(x_train)))
print(accuracy_score(y_test, model.predict(x_test)))

输出:

0.993766511324171
0.9893143365983972

让我们使用决策树分类器进行训练。

from sklearn.tree import DecisionTreeClassifier
  
model = DecisionTreeClassifier()
model.fit(x_train, y_train)
  
# testing the model
print(accuracy_score(y_train, model.predict(x_train)))
print(accuracy_score(y_test, model.predict(x_test)))

输出:

0.9999703167205913
0.9951914514692787

决策树分类器的混淆矩阵可以用下面的代码实现。

# Confusion matrix of Results from Decision Tree classification
from sklearn import metrics
cm = metrics.confusion_matrix(y_test, model.predict(x_test))
  
cm_display = metrics.ConfusionMatrixDisplay(confusion_matrix=cm,
                                            display_labels=[False, True])
  
cm_display.plot()
plt.show()

在这里插入图片描述

总结

决策树分类器和Logistic回归表现良好。

  • 2
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
机器学习是一种研究和开发算法,让计算机能从数据中自动学习并进行预测和决策的技术。它是人工智能领域的重要分支,被广泛应用于各个领域,如图像识别、自然语言处理、推荐系统等。 机器学习的理论基础包括数据处理、模型选择和评估方法。在数据处理方面,机器学习需要对原始数据进行预处理和特征提取,以使数据更适合用来训练和测试模型。模型选择涉及选择合适的机器学习算法和参数设置,以及确定模型的结构和复杂度。评估方法用于评估模型的性能和泛化能力。 常见的机器学习算法包括监督学习和无监督学习。监督学习使用带有标签的训练数据来训练模型,以预测未知数据的标签。常见的监督学习算法有线性回归、决策树和支持向量机。无监督学习则使用不带标签的数据来发现数据中的结构和模式。常见的无监督学习算法有聚类和降维。 在机器学习中,还存在着模型的优化问题。模型的优化通过调整模型参数来最小化预测误差或最大化模型的性能指标。常见的优化算法有梯度下降和牛顿法。此外,还有一些特殊的机器学习技术,如集成学习、深度学习和强化学习,它们在特定的领域和问题中表现出色。 总之,机器学习理论涉及数据处理、模型选择和评估方法等方面,包括多种学习算法和优化技术。通过理解和应用这些理论,我们能够构建出能够从数据中学习和做出预测的智能系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值