/
PRE724.py
145 lines (127 loc) · 4.76 KB
/
PRE724.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
from corpus import filtered_corpus
from gensim import corpora, models, similarities
import nltk
from collections import Counter
import re
import csv
import scipy
import scipy.io
import numpy as np
from sklearn import metrics
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import LinearSVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
import pdb
def preprocess_docs():
match_most_numbers_re = re.compile("^([0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?|\.[0-9]+)$")
match_fractional_numbers_re = re.compile("^[0-9]{1,3}(,[0-9]{3})*\.[0-9]+$")
match_year_re = re.compile("^19(7|8)[0-9]$")
stopwords = nltk.corpus.stopwords.words('english')
for train, topic, title, text in filtered_corpus():
textbuf = []
for sentence in nltk.sent_tokenize(text):
for word in nltk.word_tokenize(sentence):
if word != '.':
textbuf.append(word)
text = textbuf
title = [i for i in nltk.word_tokenize(title) if i.lower() not in stopwords]
text = text + title
for i, t in enumerate(text):
if match_most_numbers_re.search(t) is not None:
if match_year_re.search(t) is not None:
text[i] = "YEARTOKEN"
elif match_fractional_numbers_re.search(t) is not None:
text[i] = "FRACTIONTOKEN"
else:
count = t.count(",") # Thouusands separator
text[i] = "".join(["NUM" for _ in range(count+1)])+"TOKEN"
yield train, topic, text + title
def get_features(attributes=None, topics=None):
# Read preprocessed text
corpus = [(topic, text) for train, topic, text in preprocess_docs()]
# Create attributes
if attributes is None:
attributes = set([])
attr_counter = Counter([])
for topic, title in corpus:
prev = None
for word in title:
attr_counter.update([word])
if prev is not None:
bigram = "%s|%s" % (prev, word)
attr_counter.update([bigram])
prev = word
most_common = set([word for word, count in attr_counter.most_common(50)])
for topic, title in corpus:
prev = None
for word in title:
regexp = re.compile(r'[^a-zA-Z\.]')
if regexp.search(word) is not None:
print word
continue
if attr_counter[word] < 3:
continue
if word in most_common:
continue
attributes.add(word)
if prev is not None:
bigram = "%s|%s" % (prev, word)
if bigram in most_common:
continue
if attr_counter[word] < 3:
continue
attributes.add(bigram)
prev = word
# Construct a columnar mapping
attributes = sorted(attributes)
attributes_dict = {}
counter = 0
for a in attributes:
attributes_dict[a] = counter
counter += 1
attributes = attributes_dict
# Construct binary matrix
# X = np.zeros((len(corpus), len(attributes)), dtype='bool')
X = scipy.sparse.dok_matrix((len(corpus), len(attributes)), dtype='bool')
Y = [0 for _ in range(len(corpus))]
if topics is None:
topics = set([])
for topic, _ in corpus:
topics.add(topic)
# Construct a topic mapping
topics = dict([(j, i) for i, j in enumerate(topics)])
#metrics.classification_report
# Build the features matrix
for row, (topic, title) in enumerate(corpus):
if topic not in topics:
pdb.set_trace()
continue
prev = None
for word in title:
if word in attributes:
offset = attributes[word]
X[(row, offset)] = 1
if prev is not None:
bigram = "%s|%s" % (prev, word)
if bigram in attributes:
offset = attributes[bigram]
X[(row, offset)] = 1
prev = word
Y[row] = topics[topic]
return X.tocoo(), Y, attributes, topics
def save_sparse_matrix(filename,x):
x_coo=x.tocoo()
row=x_coo.row
col=x_coo.col
data=x_coo.data
shape=x_coo.shape
np.savez(filename,row=row,col=col,data=data,shape=shape)
if __name__ == "__main__":
print "Creating input..."
Xtrain, Ytrain, attributes, topics = get_features()
print "Saving features..."
save_sparse_matrix("features.npy", Xtrain)
print "Saving labels..."
np.save("labels.npy",Ytrain)
np.save("topics.npy",topics)