-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstructured-perceptron.py
167 lines (151 loc) · 5.12 KB
/
structured-perceptron.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
from pystruct.learners import StructuredPerceptron
from pystruct.models import GridCRF
#from pystruct.datasets import generate_blocks
#from pystruct.inference import get_installed
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import app.parser.getData as importArticles
import app.parser.articleRetrieval.getArticles as getContent
import app.parser.sentences as sent
import app.parser.getChunks as gc
import app.analytics.tag as tag
import app.parser.articleRetrieval.wikipediaParse as wp
import app.analytics.features as fe
from sklearn import tree, feature_extraction, svm, linear_model
from sklearn.feature_extraction.text import CountVectorizer
from multiprocessing import Pool
import numpy as np
import datetime
import app.analytics.filterSentences as fl
import networkx as nx
import matplotlib.pyplot as plt
G=nx.DiGraph()
np.seterr(divide='ignore',invalid='ignore')
trainArticles= open('data/singleShort.txt','r').readlines()#=importArticles.getData('train')
testArticles = open('data/singleShortTest.txt','r').readlines()#= importArticles.getData('test')
print len(trainArticles)
print len(testArticles)
listOfYears = []
#X, Y = generate_blocks(n_samples=10)
#inference_method = get_installed(['qpbo', 'ad3', 'lp'])[0]
#crf = GridCRF(inference_method=inference_method)
clf = StructuredPerceptron(model=GridCRF, max_iter=120)
probs = []
titles = []
#A
def getArticle(article):
singleSets = []
try:
chunks = gc.getChunks(article[1])
tags = tag.getTags(article[1],chunks)
#if tags == []:
# continue # check this is right. go to next itteration
"""The Stanford Open IE tags"""
subject = tags['subject']
relation = tags['relation']
objects = tags['object']
objects = objects.split()
content = wp.getArticle(subject)
rawSentences = sent.getSentences(content)
sentences = []
for sentence in rawSentences:
if(hd.hasDate(sentence) != []):
sentences.append(sentence)
listOfYears.append(article[0])
SS = {'title':article[1], 'sentences':sentences, 'year':article[0]}
singleSets.append(SS)
except:
pass
return singleSets
#B
def generateTrainDataPoints(tpl):
X = tpl[0]
Y = tpl[1]
doubleSets = []
I = eval(trainArticles[X])
J = eval(trainArticles[Y])
sentencesI = fl.filter(I['sentences'],I['title'])
sentencesJ = fl.filter(J['sentences'],J['title'])
if(I['year'] < J['year']):
b = 1
else:
b = 0
val = ({'title1':I['title'],'sentences1':I['sentences'],\
'title2':J['title'],'sentences2': J['sentences'],\
'year':b, 'vocab':set(sentencesI + sentencesJ)})
return val
def generateTestDataPoints(tpl):
X = tpl[0]
Y = tpl[1]
doubleSets = []
I = eval(testArticles[X])
J = eval(testArticles[Y])
sentencesI = fl.filter(I['sentences'],I['title'])
sentencesJ = fl.filter(J['sentences'],J['title'])
if(I['year'] < J['year']):
b = 1
else:
b = 0
val = ({'title1':I['title'],'sentences1':I['sentences'],\
'title2':J['title'],'sentences2': J['sentences'],\
'year':b, 'vocab':set(sentencesI + sentencesJ)})
return val
def getFeature(item):
yr = item['year']
vec = fe.get(item['sentences1'],item['sentences2'])
titles = ([item['title1'],item['title2']])
return ([vec,titles,yr])
#C
def train(features):
print features[0]
X = [item[0] for item in features]
Y = [item[2] for item in features]
clf.fit(X,Y)
def test(features):
correct = 0
probs = []
for feature in features:
temp = np.array(feature[0]).reshape((1, -1))
predict = clf.predict(temp)
#prob = max(clf.predict_proba(temp)[0])
#probs.append([predict,prob, feature[2]])
G.add_node(feature[1][0])
G.add_node(feature[1][0])
if(predict == 1):
#if(float(prob) > float(0.6)):
G.add_edge(feature[1][0],feature[1][1])#, weight= prob)
else:
#if(float(prob) > float(0.6)):
G.add_edge(feature[1][1],feature[1][0])#, weight= prob)
if(feature[2] == predict):
correct +=1
print "Accuracy = " + str(correct) + '/' + str(len(features))
print datetime.datetime.now()
p = Pool(50)
#Used to get Article Content
#articles = (p.map(getArticle,trainData))
mapping = []
for i in range(len(trainArticles)):
for j in range(i+1,len(trainArticles)):
mapping.append([i,j])
print datetime.datetime.now()
doubleSets = p.map(generateTrainDataPoints,mapping)
print datetime.datetime.now()
trainFeatures = p.map(getFeature,doubleSets)
print datetime.datetime.now()
train(trainFeatures)
print datetime.datetime.now()
#train(generateDataPoints(trainArticles))
print "Training Complere. Now For Testing"
mapping = []
for i in range(len(testArticles)):
for j in range(i+1,len(testArticles)):
mapping.append([i,j])
print datetime.datetime.now()
doubleSets = p.map(generateTestDataPoints,mapping)
print datetime.datetime.now()
testFeatures = p.map(getFeature,doubleSets)
print datetime.datetime.now()
test(testFeatures)
print datetime.datetime.now()