Forums

Fake News Detection

Hello, I'm working on a code that detect fake news and am having the error below. Can i see any assistance here. The aspect of the code producing the error is:

mlc = MLPClassifier(hidden_layer_sizes=3) mlc.fit(fake_news_train_tfidf,label_train) mlc_pred = mlc.predict(fake_news_test_tfidf) print(accuracy_score(label_test,mlc_pred))

The Error stack is: TypeError Traceback (most recent call last) <ipython-input-118-0374c264f5e4> in <module> 1 gbc = GradientBoostingClassifier() ----> 2 gbc.fit(fake_news_train_tfidf,label_train) 3 gbc_pred = gbc.predict(fake_news_test_tfidf) 4 print(accuracy_score(label_test,gbc_pred))

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\ensemble\gradient_boosting.py in fit(self, X, y, sample_weight, monitor) 1402 check_consistent_length(X, y, sample_weight) 1403 -> 1404 y = self._validate_y(y, sample_weight) 1405 1406 if self.n_iter_no_change is not None:

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\ensemble\gradient_boosting.py in validate_y(self, y, sample_weight) 1960 1961 def _validate_y(self, y, sample_weight): -> 1962 check_classification_targets(y) 1963 self.classes, y = np.unique(y, return_inverse=True) 1964 n_trim_classes = np.count_nonzero(np.bincount(y, sample_weight))

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y) 166 y : array-like 167 """ --> 168 y_type = type_of_target(y) 169 if y_type not in ['binary', 'multiclass', 'multiclass-multioutput', 170 'multilabel-indicator', 'multilabel-sequences']:

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\multiclass.py in type_of_target(y) 285 return 'continuous' + suffix 286 --> 287 if (len(np.unique(y)) > 2) or (y.ndim >= 2 and len(y[0]) > 1): 288 return 'multiclass' + suffix # [1, 2, 3] or [[1., 2., 3]] or [[1, 2]] 289 else:

C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\arraysetops.py in unique(ar, return_index, return_inverse, return_counts, axis) 262 ar = np.asanyarray(ar) 263 if axis is None: --> 264 ret = _unique1d(ar, return_index, return_inverse, return_counts) 265 return _unpack_tuple(ret) 266

C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\arraysetops.py in unique1d(ar, return_index, return_inverse, return_counts) 310 aux = ar[perm] 311 else: --> 312 ar.sort() 313 aux = ar 314 mask = np.empty(aux.shape, dtype=np.bool)

TypeError: '<' not supported between instances of 'float' and 'str'

I'm guessing that you have some sort of array that needs to be sorted as part of the predict step, but you have mixed data types in it so you get the error. Check the data that you're using to make the prediction. I'm guessing again, but I'd suspect fake_news_test_tfidf would be the culprit.

hi, first, if you are fitting your data as string, use something like tfidfVectorizer (you can use them in pipelines by calling sklearn.pipeline.make_pipeline and passing them in parameters one by one) another solution is to use word vectors (spacy has support for it) but if you are using scikit-learn and you are a newbie in ml, this is your better option at first but if you want better accuracy use word vectors.

I dont know how to apply what you guys are saying. I dont have much knowledge about Machine Learning. This is my complete source code. Please help me.

  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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
#!/usr/bin/env python
# coding: utf-8

# In[16]:


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from wordcloud import WordCloud, STOPWORDS
import re
import string
import nltk
from collections import Counter
from nltk.probability import FreqDist
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer,PorterStemmer
from nltk.tokenize import word_tokenize, wordpunct_tokenize
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier
from sklearn.neural_network.multilayer_perceptron import MLPClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix,mean_absolute_error,mean_squared_error


# In[17]:


fn_df = pd.read_csv('train.csv')


# In[ ]:


fn_df.shape


# In[ ]:


fn_df.head()


# In[ ]:


fn_df.tail()


# In[ ]:


fn_df['title'].iloc[1]


# In[ ]:


fn_df['text'].iloc[1]


# In[ ]:


fn_df['text'].iloc[1]


# In[ ]:


fn_df.info()


# In[ ]:


fn_df['label'].value_counts()


# In[ ]:


fn_df.isnull().any()


# In[ ]:


fn_df.isnull().sum()


# # EDA

# In[ ]:


def word_count(text):
    return len(str(text).split())


# In[ ]:


fn_df['word_count'] = fn_df['text'].apply(word_count)


# In[ ]:


fn_df['char_count'] = fn_df['text'].str.len()


# In[ ]:


def upper_count(text):
    is_upper_len = len([word for word in word_tokenize(str(text)) if word.isupper()])
    return is_upper_len


# In[ ]:


fn_df['is_upper'] = fn_df['text'].apply(upper_count)


# In[ ]:


def stop_words_count(text):
    stop_words = stopwords.words('english')
    stopwords_len = len([word for word in word_tokenize(str(text)) if word in stop_words])
    return stopwords_len


# In[22]:


fn_df['stopword_presence'] = fn_df['text'].apply(stop_words_count)


# In[23]:


def check_punctuation(text):
    punct_len = len([punct for punct in word_tokenize(str(text)) if punct in string.punctuation])
    if punct_len < 0:
        return 'False'
    else:
        return 'True'


# In[24]:


fn_df['punct check'] = fn_df['text'].apply(check_punctuation)


# In[25]:


fn_df.head()


# In[26]:


fn_df.describe()


# # VISUALIZATION

# In[27]:


fn_df['text'] = fn_df['text'].apply(lambda text: str(text).lower())


# In[28]:


sns.countplot(x='label',data=fn_df)


# In[29]:


real_tag = ''.join(news for news in fn_df['text'][fn_df['label']==1])


# In[30]:


fake_tag = ''.join(news for news in fn_df['text'][fn_df['label']==0])


# In[54]:


real_tag_most_word = pd.Series(Counter(str(real_tag).split()).most_common(25))


# In[55]:


word_list =[]
freq_list =[]
for word, freq in real_tag_most_word:
    word_list.append(word)
    freq_list.append(freq)

real_dict = {'Word':word_list,'Frequency':freq_list}
real_tag_most_word_df = pd.DataFrame(real_dict)
real_tag_most_word_df.head(25)



# In[56]:


plt.figure(figsize=(12,12))
plt.bar(x=real_tag_most_word_df['Word'],height= real_tag_most_word_df['Frequency'])
plt.xticks(rotation=55)
plt.show()


# In[31]:


fake_tag_most_word = pd.Series(Counter(str(fake_tag).split()).most_common())


# In[32]:


wordcloud = WordCloud(background_color='white',stopwords=STOPWORDS,max_words=50)


# In[33]:


# wc = wordcloud.generate(fake_tag)
# plt.figure(figsize=(6,4))
# plt.axis('off')
# plt.title('fake news word cloud')
# plt.imshow(wc)


# In[34]:


# wc = wordcloud.generate(real_tag)
# plt.figure(figsize=(6,4))
# plt.axis('off')
# plt.title('real news word cloud')
# # plt.imshow(wc)


# # cleaning

# In[36]:


fn_df['text'].head()


# In[50]:


def remove_punctuation(text,keep_apostrophes=True):
    text = text.strip()
    if keep_apostrophes:
        PATTERN = r'[?|$|&|*|.|,|!|"|#|\|+|-|/|:|–|;|<|=|>|[|^|_|{|”|“|—|’|`|%|@|(|)|~]'
        #'[?|$|&|*|.|,|!|"|#|\|+|-|/|:|;|<|=|>|[|^|_|{|`|%|@|(|)|~]' 
        filtered_text = re.sub(PATTERN, r'', text)
    else:
        PATTERN = r'[^a-zA-Z0-9 ]'
        filtered_text = re.sub(PATTERN, r'', text)
    return filtered_text


# In[51]:


fn_df['text'] = fn_df['text'].apply(remove_punctuation)


# In[38]:


fn_df.head()


# In[39]:


fn_df.tail()


# In[40]:


def remove_stopwords(text):
    stop_words = stopwords.words('english')
    clean_text = [word for word in word_tokenize(text) if 
                    word not in stop_words]
    return ' '.join(clean_text)


# In[41]:


fn_df['text'] = fn_df['text'].apply(remove_stopwords)


# In[39]:


fn_df.head()


# In[34]:


def stemming(text):
    steming = PorterStemmer()
    stem = [steming.stem(word) for word in word_tokenize(text)]
    return ' '.join(stem)


# In[35]:


fn_df['text'] = fn_df['text'].apply(stemming)


# In[36]:


fn_df.head()


# In[37]:


fn_df.tail()


# In[38]:


fn_df.columns


# In[ ]:





# # splitting data into training and testing set

# In[52]:


fn_train,fn_test,label_train,label_test = train_test_split(fn_df['text'],fn_df['label'],test_size=0.3,shuffle=True)


# In[53]:


print(fn_train.shape, fn_test.shape,label_train.shape,label_test.shape)


# # FEATURE EXTRACTION

# In[54]:


cv = CountVectorizer()
tfidf = TfidfTransformer(sublinear_tf=True)


# In[55]:


fake_news_train_cv = cv.fit_transform(fn_train)
fake_news_test_cv = cv.transform(fn_test)


# In[56]:


fake_news_train_tfidf = tfidf.fit_transform(fake_news_train_cv)
fake_news_test_tfidf =  tfidf.transform(fake_news_test_cv)


# # DATA MODELLING

# In[57]:


rfc = RandomForestClassifier(random_state=42)
rfc.fit(fake_news_train_tfidf,label_train)
rfc_pred = rfc.predict(fake_news_test_tfidf)
print(accuracy_score(label_test,rfc_pred))


# In[58]:


gbc = GradientBoostingClassifier()
gbc.fit(fake_news_train_tfidf,label_train)
gbc_pred = gbc.predict(fake_news_test_tfidf)
print(accuracy_score(label_test,gbc_pred))


# In[59]:


mlc = MLPClassifier(hidden_layer_sizes=3)
mlc.fit(fake_news_train_tfidf,label_train)
mlc_pred = mlc.predict(fake_news_test_tfidf)
print(accuracy_score(label_test,mlc_pred))


# In[60]:


svc = SVC()
svc.fit(fake_news_train_tfidf,label_train)
svc_pred = svc.predict(fake_news_test_tfidf)
print(accuracy_score(label_test,svc_pred))


# In[61]:


mnb = MultinomialNB()
mnb.fit(fake_news_train_tfidf,label_train)
mnb_pred = mnb.predict(fake_news_test_tfidf)
print(accuracy_score(label_test,mnb_pred))


# In[62]:


dtc = DecisionTreeClassifier()
dtc.fit(fake_news_train_tfidf,label_train)
dtc_pred = dtc.predict(fake_news_test_tfidf)
print(accuracy_score(label_test,dtc_pred))


# # EVALUATING MODELS PERFORMANCE

# In[63]:


print('Classification report for RFC:')
print(classification_report(label_test,rfc_pred))
print('----------------------------------------')
print('Classification report for GBC:')
print(classification_report(label_test,gbc_pred))
print('----------------------------------------')
print('Classification report for MLP:')
print(classification_report(label_test,mlc_pred))
print('----------------------------------------')
print('Classification report for MNB:')
print(classification_report(label_test,mnb_pred))
print('----------------------------------------')
print('Classification report for DTC:')
print(classification_report(label_test,dtc_pred))
print('----------------------------------------')


# In[64]:


print('Confusion matrix for RFC:')
print(confusion_matrix(label_test,rfc_pred))
print('----------------------------------------')
print('Confusion matrix for GBC:')
print(confusion_matrix(label_test,gbc_pred))
print('----------------------------------------')
print('Confusion matrix for MLP:')
print(confusion_matrix(label_test,mlc_pred))
print('----------------------------------------')
print('Classification report for MNb:')
print(confusion_matrix(label_test,mnb_pred))
print('----------------------------------------')
print('Confusion matrix for DTC:')
print(confusion_matrix(label_test,dtc_pred))
print('----------------------------------------')


# In[ ]:





# In[65]:


# # tokenize document
# tokens = wpt.tokenize(doc)
# # filter stopwords out of document
# filtered_tokens = [token for token in tokens if token not in stop_words]
# # re-create document from filtered tokens
# doc = ' '.join(filtered_tokens


# In[66]:


# def rem(sentence,keep_apostrophes=False):
#     sentence = sentence.strip()
#     if keep_apostrophes:
#         PATTERN = r'[?|$|&|*|.|,|%|@|(|)|~]' # add other characters here to
#         #remove them
#         filtered_sentence = re.sub(PATTERN, r'', sentence)
#     else:
#         PATTERN = r'[^a-zA-Z0-9 ]' # only extract alpha-numeric characters
#         filtered_sentence = re.sub(PATTERN, r'', sentence)
#     return filtered_sentence



# In[98]:


ss= 'where.... atre; you "coming" from? youre t”her’e oo."...,,[[]]/'
remove_punctuation(ss)


# In[69]:


print("Random forest model accuracy",accuracy_score(label_test,rfc_pred)*100)
print("------------------------------------------------------------------")
print("Gradient Boosting model accuracy",accuracy_score(label_test,gbc_pred)*100)
print("------------------------------------------------------------------")
print("Multilayer perception model accuracy",accuracy_score(label_test,mlc_pred)*100)
print("------------------------------------------------------------------")
print("Support vector machine model accuracy",accuracy_score(label_test,svc_pred)*100)
print("------------------------------------------------------------------")
print("Naive Bayes model accuracy",accuracy_score(label_test,mnb_pred)*100)
print("------------------------------------------------------------------")
print("Decision Tree model accuracy",accuracy_score(label_test,dtc_pred)*100)