-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfake_preprocess.py
More file actions
133 lines (93 loc) · 3.73 KB
/
fake_preprocess.py
File metadata and controls
133 lines (93 loc) · 3.73 KB
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
# -*- coding: utf-8 -*-
"""NLP_BERT_on_fake_news_detection.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1iyNDJE9Q59OUihSeee1wts0d1RBtYtI-
PyTorch version | torchtext version
1.6 0.7
"""
#from google.colab import drive
#drive.mount('/content/drive')
"""# preprocess"""
import json
import pandas as pd
import numpy as np
import re
'''read data'''
path = './pubilc_data_0522'
train_str = ''
with open(path+'/train.json','r',encoding = 'utf-8')as f:
train_str = f.read()
#print(train_str)
f.close()
train = json.loads(train_str)
''' filter '''
#hashmap = {} # save item which is unique.
data = []
for dic in train:
#if not dic['idx'] in hashmap:
text = dic['text']+' '+dic['reply']
#replace tag user
#httpre = r'https:\/\/?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b\/?[-a-zA-Z0-9@:%._\+~#=]{1,256}'
#text = re.sub(httpre, " ", text)
#replace tag user
#tagere = '@[-a-zA-Z0-9:%._\+~#=]{1,256}'
#text = re.sub(tagere, "taguser", text)
# leave a-z and space
#text = re.sub(r'[^A-Za-z\s]', " ", text)
label = 0
if dic['label'] =='fake': # real
label = 1
# hashmap[dic['idx']] = {'idx':dic['idx'],
# 'context_idx':dic['context_idx'],
# 'text':text,
# 'label':label}
data.append( {'idx':dic['idx'],
'context_idx':dic['context_idx'],
'text':text,
'label':label})
#data = list(hashmap.values())
df = pd.DataFrame(data)
df
#raw_data_path = '/content/drive/My Drive/transformers/Data/news.csv'
destination_folder = './pubilc_data_0522'
train_test_ratio = 0.95
train_valid_ratio = 0.945
first_n_words = 512
import pandas as pd
from sklearn.model_selection import train_test_split
def trim_string(x):
x = x.split(maxsplit=first_n_words)
x = ' '.join(x[:first_n_words])
return x
# Read raw data
df_raw = df
# Prepare columns
# df_raw['label'] = (df_raw['label'] == 'FAKE').astype('int')
# df_raw['titletext'] = df_raw['title'] + ". " + df_raw['text']
# df_raw = df_raw.reindex(columns=['label', 'title', 'text', 'titletext'])
# Drop rows with empty text
df_raw.drop( df_raw[df_raw.text.str.len() < 5].index, inplace=True)
# Trim text and titletext to first_n_words
#df_raw['text'] = df_raw['text'].apply(trim_string)
# Split according to label
df_real = df_raw[df_raw['label'] == 0]
df_fake = df_raw[df_raw['label'] == 1]
# Train-test split
df_real_full_train, df_real_test = train_test_split(df_real, train_size = train_test_ratio, random_state = 1)
df_fake_full_train, df_fake_test = train_test_split(df_fake, train_size = train_test_ratio, random_state = 1)
# Train-valid split
df_real_train, df_real_valid = train_test_split(df_real_full_train, train_size = train_valid_ratio, random_state = 1)
df_fake_train, df_fake_valid = train_test_split(df_fake_full_train, train_size = train_valid_ratio, random_state = 1)
# Concatenate splits of different labels
df_train = pd.concat([df_real_train, df_fake_train], ignore_index=True, sort=False)
df_valid = pd.concat([df_real_valid, df_fake_valid], ignore_index=True, sort=False)
df_test = pd.concat([df_real_test, df_fake_test], ignore_index=True, sort=False)
print('\t real \t fake')
print('train',len(df_real_train),len(df_fake_train))
print('valid',len(df_real_valid),len(df_fake_valid))
print('test',len(df_real_test),len(df_fake_test))
# Write preprocessed data
df_train.to_csv(destination_folder + '/train_mr.csv', index=False)
df_valid.to_csv(destination_folder + '/valid_mr.csv', index=False)
df_test.to_csv(destination_folder + '/test_mr.csv', index=False)