/
preprocessing.py
193 lines (152 loc) · 5.24 KB
/
preprocessing.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
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
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as scn
import numpy as np
import spacy
nlp = spacy.load("en_core_web_lg")
from time import perf_counter
from concurrent.futures import ProcessPoolExecutor
MAX_LEN = 1000 # longest title is 54, longest text 9469
MAX_LEN_TITLE = 54
PADDING_CONST = -1e8
def max_len(sentence):
return len(nlp(sentence))
def to_npy(sentence):
"""Converts spacy array to numpy arrays
Args:
A (spacy.tokens.doc.doc): Array of word vector
Returns:
np.array(len(A), 300): Word vector as np array
"""
A = nlp(sentence)
arr = np.empty((MAX_LEN,300,), dtype=np.float32)
if len(A) < MAX_LEN:
for i in range(len(A)):
arr[i] = A[i].vector
for i in range(len(A), MAX_LEN):
arr[i] = MAX_LEN*np.ones((300))
else:
for i in range(MAX_LEN):
arr[i] = A[i].vector
return arr
def to_npy_2(sentence):
"""Converts spacy array to numpy arrays (for the titles)
Args:
A (spacy.tokens.doc.doc): Array of word vector
Returns:
np.array(len(A), 300): Word vector as np array
"""
A = nlp(sentence)
arr = np.empty((MAX_LEN_TITLE,300,), dtype=np.float32)
if len(A) < MAX_LEN_TITLE:
for i in range(len(A)):
arr[i] = A[i].vector
for i in range(len(A), MAX_LEN_TITLE):
arr[i] = MAX_LEN_TITLE*np.ones((300))
else:
for i in range(MAX_LEN_TITLE):
arr[i] = A[i].vector
return arr
# with ProcessPoolExecutor(max_workers=24) as executor:
# x_train = list(executor.map(max_len, fake["text"]))
# # Don't forget about the fake as well
# print(max(x_train))
# print(np.std(np.array(x_train)))
def generate_body(end=None):
"""Generate the word vectors for the body of real and fake news articles
Args:
end (int, optional): The number of elements of real and fake news. Defaults to None.
Returns:
(np.array, np.array): real, fake
"""
fake = pd.read_csv("data/Fake.csv")
real = pd.read_csv("data/True.csv")
fake.drop(columns=["date", "subject"], inplace=True)
real.drop(columns=["date", "subject"], inplace=True)
with ProcessPoolExecutor() as executor:
x_real = np.array(list(executor.map(to_npy, real["text"][:end])), dtype=np.float32)
x_fake = np.array(list(executor.map(to_npy, fake["text"][:end])), dtype=np.float32)
return x_real, x_fake
def generate_title(end=None):
"""Generate the word vectors for the titles of real and fake news articles
Args:
end (int, optional): The number of elements of real and fake news. Defaults to None.
Returns:
(np.array, np.array): real, fake
"""
fake = pd.read_csv("data/Fake.csv")
real = pd.read_csv("data/True.csv")
fake.drop(columns=["date", "subject"], inplace=True)
real.drop(columns=["date", "subject"], inplace=True)
with ProcessPoolExecutor(max_workers=24) as executor:
x_real = np.array(list(executor.map(to_npy_2, real["title"][:end])), dtype=np.float32)
x_fake = np.array(list(executor.map(to_npy_2, fake["title"][:end])), dtype=np.float32)
return x_real, x_fake
def get_dataset_2():
"""Generate the data for the second dataset
Returns:
np.array,np.array: X and Y
"""
df = pd.read_csv("data/news.csv")
df = df.dropna()
X = df["text"]
Y = df["label"]
with ProcessPoolExecutor() as executor:
X_t2 = np.array(list(executor.map(to_npy,X)),dtype=np.float32)
Y_t2 = np.zeros((len(X),2,),dtype=np.float32)
for i in range(len(Y)):
if Y[i]=="FAKE":
Y_t2[i,1] = 1.0
else:
Y_t2[i,0] = 1.0
return X_t2, Y_t2
def get_dataset_2t():
"""Generate the data for the second dataset
Returns:
np.array,np.array: X and Y
"""
df = pd.read_csv("data/news.csv")
df = df.dropna()
X = df["title"]
Y = df["label"]
with ProcessPoolExecutor() as executor:
X_t2 = np.array(list(executor.map(to_npy_2,X)),dtype=np.float32)
Y_t2 = np.zeros((len(X),2,),dtype=np.float32)
for i in range(len(Y)):
if Y[i]=="FAKE":
Y_t2[i,1] = 1.0
else:
Y_t2[i,0] = 1.0
return X_t2, Y_t2
def get_dataset_3():
df = pd.read_csv("data/train.csv")
df = df.dropna()
X = df["text"]
Y = list(df["label"])[:]
with ProcessPoolExecutor() as executor:
X_t2 = np.array(list(executor.map(to_npy,X)),dtype=np.float32)
Y_t2 = np.zeros((len(X),2,),dtype=np.float32)
for i in range(len(Y)):
if Y[i] == 1:
Y_t2[i,1] = 1.0
else:
Y_t2[i,0] = 1.0
return X_t2, Y_t2
def get_dataset_3t():
df = pd.read_csv("data/train.csv")
df = df.dropna()
X = df["text"]
Y = list(df["title"])[:]
with ProcessPoolExecutor() as executor:
X_t2 = np.array(list(executor.map(to_npy_2,X)),dtype=np.float32)
Y_t2 = np.zeros((len(X),2,),dtype=np.float32)
for i in range(len(Y)):
if Y[i] == 1:
Y_t2[i,1] = 1.0
else:
Y_t2[i,0] = 1.0
return X_t2, Y_t2
# arr = np.empty((48,-1,300,))
# for i in range(48):
# arr[i] = x_real[i]
# https://datascience.stackexchange.com/questions/48796/how-to-feed-lstm-with-different-input-array-sizes