-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNewsDetector.py
114 lines (61 loc) · 2.54 KB
/
NewsDetector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python
# coding: utf-8
# In[14]:
#Necessary imports
import numpy as np
import pandas as pd
import itertools
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
# In[15]:
#Reading the data
df=pd.read_csv('Desktop/news.csv')
#Get shape and head
df.shape
df.head()
# In[16]:
#Get the labels
labels=df.label
labels.head()
# In[17]:
#Split the dataset into training and testing sets
x_train,x_test,y_train,y_test=train_test_split(df['text'], labels, test_size=0.2, random_state=7)
# In[18]:
#Initialize a TfidfVectorizer with stop words from the English language and a maximum document
#frequency of 0.7 (terms with a higher document frequency will be discarded). Stop words are
#the most common words in a language that are to be filtered out before processing the natural
#language data. And a TfidfVectorizer turns a collection of raw documents into a matrix of TF-IDF features.
# In[19]:
#Initialize a TfidfVectorizer
tfidf_vectorizer=TfidfVectorizer(stop_words='english', max_df=0.7)
#Fit and transform train set, transform test set
tfidf_train=tfidf_vectorizer.fit_transform(x_train)
tfidf_test=tfidf_vectorizer.transform(x_test)
# In[20]:
#Next, initialize a PassiveAggressiveClassifier. This is. We’ll fit this on tfidf_train and y_train.
#Then, we’ll predict on the test set from the TfidfVectorizer and calculate the accuracy with
#accuracy_score() from sklearn.metrics.
# In[21]:
#Initialize a PassiveAggressiveClassifier
pac=PassiveAggressiveClassifier(max_iter=50)
pac.fit(tfidf_train,y_train)
#Predict on the test set and calculate accuracy
y_pred=pac.predict(tfidf_test)
score=accuracy_score(y_test,y_pred)
print(f'Accuracy: {round(score*100,2)}%')
# In[22]:
#Recieved an accuracy of 92.74% with this model. Finally, let’s print out a confusion matrix to gain
#insight into the number of false and true negatives and positives.
# In[23]:
#Build confusion matrix
confusion_matrix(y_test,y_pred, labels=['FAKE','REAL'])
# In[24]:
#So with this model, we have 588 true positives, 587 true negatives, 50 false positives, and 42 false negatives.
#SUMMARY:
#Goal was to detect fake news with Python. We took a political dataset,
#implemented a TfidfVectorizer, initialized a
#PassiveAggressiveClassifier, and fit our model. We ended
#up obtaining an accuracy of 92.74% in magnitude.
# In[ ]: