-
Notifications
You must be signed in to change notification settings - Fork 2
/
features_basic.py
391 lines (324 loc) · 16.3 KB
/
features_basic.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
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
# trash
'''
class FeatureManager(object):
def __init__(self, entity):
self.entity = entity
self.features = []
self._feature_keys = None
def features_filtered(self):
return sorted([i for i in self.features if i.value], key=lambda f: f.order())
return [i for i in self.features if i.value]
def add(self, feature):
self.features.append(feature)
def feature_keys(self):
if not self._feature_keys:
self._feature_keys = set([i.key() for i in self.features])
return self._feature_keys
def getVector(self, retrieve=None):
vector = []
def getValue(featureN, label="Class", default='?'):
feature_name = '%s-%s' % (featureN.__name__, label)
# values = [i for i in self.features if i.__class__==featureN and (not label or i.label==label)]
values = [i for i in self.features if i.name() == feature_name]
if not values:
vector.append((feature_name, default))
return
if featureN.is_numeric:
value = sum([i.value for i in values]) / len(values)
else:
value = reduce(featureN.merge, values)
value = value.value
if featureN == FeatureLabeledList:
s = ';'.join(value)
vector.append((feature_name, (s if s else '-')))
else:
vector.append((feature_name, value))
# if value.value > 0: vector.append('1')
# elif value.value < 0: vector.append('0')
# else: vector.append('?')
def getValueList(feature, label=None):
values = [i for i in self.features if i.__class__ == feature and (not label or i.label == label)]
if not values:
return []
value = reduce(feature.merge, values)
return value.value
# FeatureLabel
current_features = []
# FeatureProperNames
current_features += [FeatureProperNamesMale, FeatureProperNamesFemale]
# FeatureCommonNames
current_features += [FeatureVerbSubject, FeatureVerbObject]
# current_features+=[FeatureVerbSubject,FeatureVerbObject,FeatureVerbSubjectObject]
for i in current_features:
getValue(i)
for i in dep_list:
getValue(FeatureLabel, 'dep_head_' + i, '0')
getValue(FeatureLabel, 'dep_dep_' + i, '0')
vsubject = getValueList(FeatureLabeledList, 'v-subject')
vobject = getValueList(FeatureLabeledList, 'v-object')
global wn
if not wn:
from nltk.corpus import wordnet as wn
cloud_s = []
for i in vsubject:
synsets = wn.synsets(i, pos=wn.VERB)
if synsets:
cloud_s.append(synsets[0])
cloud_o = []
for i in vobject:
synsets = wn.synsets(i, pos=wn.VERB)
if synsets:
cloud_o.append(synsets[0])
for group in verbs_groups:
cloud_a = []
for j in group:
synsets = wn.synsets(j, pos=wn.VERB)
if synsets:
cloud_a.append(synsets[0])
if not cloud_s or not cloud_a:
vector.append(('v-subject-g-' + group[0], 0))
else:
similarity = max([max([i.wup_similarity(j) for j in cloud_s]) for i in cloud_a])
vector.append(('v-subject-g-' + group[0], similarity))
if not cloud_o or not cloud_a:
vector.append(('v-object-g-' + group[0], 0))
else:
similarity = max([max([i.wup_similarity(j) for j in cloud_o]) for i in cloud_a])
vector.append(('v-object-g-' + group[0], similarity))
for i in verbs_list:
vector.append(('v-subject-' + i, ('1' if i in vsubject else '0')))
for i in verbs_list:
vector.append(('v-object-' + i, ('1' if i in vobject else '0')))
if not retrieve:
return vector
def getVerbs(self, slot):
return self.entity.verbs(slot)
def getVectorNew(self, get_labels_too=False):
vector = []
def getValue(featureN, label="Class", default='?'):
feature_name = '%s-%s' % (featureN.__name__, label)
values = [i for i in self.features if i.name() == feature_name]
if not values:
vector.append((feature_name, default))
return
if featureN.is_numeric:
value = sum([i.value for i in values]) / len(values)
else:
value = reduce(featureN.merge, values)
value = value.value
if featureN == FeatureLabeledList:
s = ';'.join(value)
vector.append((feature_name, (s if s else '-')))
else:
vector.append((feature_name, value))
# FeatureLabel
for i in ['hasPRP', 'hasNN', 'hasNNP', 'relAnimal', 'relRoyal', 'relMagic', 'relHuman', 'relPerson',
'relPersonMale', 'relPersonFemale', 'relHumanCapabilities', 'relHumanProperty']:
getValue(FeatureLabel, i)
for i in ['hasPOS', 'hasEX', 'hasDT', 'hasJJ', 'hasIt', 'hasWDT', 'hasRB', 'hasSingularFirstPerson ',
'hasPluralFirstPerson', 'hasSingularSecondPerson ', 'hasPluralSecondPerson ',
'hasSingularThirdPersonMales', 'hasSingularThirdPersonFemale ', 'hasSingularThirdPersonNeuter ',
'hasSingularThirdPersonGeneric ', 'hasPluralThirdPerson', 'hasPluralThirdPersonGeneric']:
getValue(FeatureLabel, i)
for i in ['S', 'VP', 'NP', 'ADJP', 'PP', 'ADVP', 'NP-TMP', 'SQ', 'SBAR', 'SINV', 'SBARQ']:
getValue(FeatureLabel, 'fromNode' + i)
for i in ['--', 'ADJP', 'ADVP', 'CC', 'CD', 'DT', 'EX', 'IN', 'JJ', 'JJR', 'JJS', 'NN', 'NNP', 'NNS', 'NP',
'PDT', 'POS', 'PP', 'PRP', 'PRP$', 'QP', 'RB', 'VBG', 'VBN', 'WDT', 'WP']:
getValue(FeatureLabel, 'hasNode' + i)
current_features = []
# FeatureConceptSimilarity
current_features += [FeatureAgeYoung, FeatureAgeOld, FeatureVillian, FeatureAnimal, FeaturePerson,
FeatureLocation, FeatureVehicle, FeatureCreature]
# FeatureProperNames
current_features += [FeatureProperNamesMale, FeatureProperNamesFemale]
# FeatureCommonNames
current_features += [FeatureCommonNamesMale, FeatureCommonNamesFemale, FeatureCommonNamesPersons,
FeatureCommonNamesTitles]
current_features += [FeatureVerbSubject, FeatureVerbObject]
# current_features+=[FeatureVerbSubject,FeatureVerbObject,FeatureVerbSubjectObject]
for i in current_features:
getValue(i)
for i in ['prep_to', 'prep_from', 'prep_of', 'prep_with', 'prep_for', 'prep_in_on_at', 'prep_other'] + ['poss',
'appos'] + [
'det_the', 'det_other'] + ['dobj', 'iobj', 'pobj']:
getValue(FeatureLabel, 'dep_head_' + i, '0')
getValue(FeatureLabel, 'dep_dep_' + i, '0')
vsubject = self.getVerbs(0)
vobject = self.getVerbs(1)
verbs_groups = [
['do', 'act', 'get'],
['be', 'can', 'want', 'have', 'live'],
['think', 'love', 'hate'],
['talk', 'communicate', 'say', 'tell', 'order', 'command'],
['answer', 'reply', 'respond'],
['ask', 'inquire', 'test', 'judge', 'try'],
['punish', 'kill', 'kidnap', 'pursue'],
['help', 'rescue', 'save', 'hide'],
['reward', 'pay', 'give'],
['move', 'go', 'transport', 'arrive', 'carry'],
]
global wn
if not wn:
from nltk.corpus import wordnet as wn
cloud_s = []
for i in vsubject:
synsets = wn.synsets(i, pos=wn.VERB)
if synsets:
cloud_s.append(synsets[0])
cloud_o = []
for i in vobject:
synsets = wn.synsets(i, pos=wn.VERB)
if synsets:
cloud_o.append(synsets[0])
for group in verbs_groups:
cloud_a = []
for j in group:
synsets = wn.synsets(j, pos=wn.VERB)
if synsets:
cloud_a.append(synsets[0])
if not cloud_s or not cloud_a:
vector.append(('v-subject-g-' + group[0], 0))
else:
similarity = max([max([i.wup_similarity(j) for j in cloud_s]) for i in cloud_a])
vector.append(('v-subject-g-' + group[0], similarity))
if not cloud_o or not cloud_a:
vector.append(('v-object-g-' + group[0], 0))
else:
similarity = max([max([i.wup_similarity(j) for j in cloud_o]) for i in cloud_a])
vector.append(('v-object-g-' + group[0], similarity))
verbs_list = ['be', 'have', 'do', 'go', 'want', 'make', 'give', 'call', 'take', 'tell', 'get', 'know', 'ask',
'come', 'look', 'happen', 'put', 'say', 'leave', 'become', 'think', 'run', 'sit', 'fall', 'bring',
'see', 'hear', 'stand', 'pass', 'seem', 'find']
for i in verbs_list:
vector.append(('v-subject-' + i, ('1' if i in vsubject else '0')))
for i in verbs_list:
vector.append(('v-object-' + i, ('1' if i in vobject else '0')))
if get_labels_too:
return vector
else:
return [i[1] for i in vector]
################################################################################
class FeatureProviderSentiWordnet(FeatureProvider):
@classmethod
def ready(self, feature_manager):
return 'sentiwordnet' in datamanager.__dict__
def features(self):
return [FeatureSentimentPosNeg]
def features_from_tokens(self, tokens):
features = []
for feature_class in self.features():
sentiment = sum(
[datamanager.sentiwordnet.query(leaf.lemma, leaf.pos) * leaf.weight for leaf in tokens]) / len(tokens)
sentiment = util.clamp(-1, 1, sentiment)
features.append(feature_class(sentiment, 1.0, self.__class__.__name__))
return features
class FeatureProviderFromVerbs(FeatureProvider):
@classmethod
# FIXME feature_manager is None for some entities, probably related to hierarchies
def features_from_verbs(cls, verb):
if settings.DISABLE_FEATURES_HIERARCHICAL_PROPAGATION_VERBS:
if verb.subject and verb.subject.feature_manager:
verb.subject.feature_manager.add(FeatureVerbSubjectObject(1.0, 1.0, cls.__name__))
verb.subject.feature_manager.add(FeatureVerbSubject(1.0, 1.0, cls.__name__))
verb.subject.feature_manager.add(FeatureLabeledList('v-subject', [verb.verb], cls.__name__))
if verb.object and verb.object.feature_manager:
verb.object.feature_manager.add(FeatureVerbSubjectObject(-1.0, 1.0, cls.__name__))
verb.object.feature_manager.add(FeatureVerbObject(1.0, 1.0, cls.__name__))
verb.object.feature_manager.add(FeatureLabeledList('v-object', [verb.verb], cls.__name__))
else:
if verb.subject:
for e in verb.subject.entity_manager.entities_independent(verb.subject):
if e and e.feature_manager: # FIXME: when is there no feature_manager???
e.feature_manager.add(FeatureVerbSubjectObject(1.0, 1.0, cls.__name__))
e.feature_manager.add(FeatureVerbSubject(1.0, 1.0, cls.__name__))
e.feature_manager.add(FeatureLabeledList('v-subject', [verb.verb], cls.__name__))
if verb.object:
for e in verb.object.entity_manager.entities_independent(verb.object):
if e and e.feature_manager:
e.feature_manager.add(FeatureVerbSubjectObject(-1.0, 1.0, cls.__name__))
e.feature_manager.add(FeatureVerbObject(1.0, 1.0, cls.__name__))
e.feature_manager.add(FeatureLabeledList('v-object', [verb.verb], cls.__name__))
################################################################################
class Feature(object):
def __init__(self, value=None, confidence=0.0, provider=None):
self.value, self.confidence, self.provider = value, confidence, provider
def __repr__(self):
return 'Feature %s: %s (%s %s)' % (self.__class__.__name__, self.value, self.confidence, self.provider)
def name(self):
return '%s-%s' % (self.__class__.__name__, "Class")
def key(self):
return '%s-%s' % (self.__class__.__name__, self.provider)
def html(self):
return '<em>%s:</em> %s <small>(%.2f %s)</small>' % (
self.__class__.__name__, '%.2f' % self.value if self.value else 'N/A', self.confidence, self.provider)
@staticmethod
def is_numeric():
return True
@staticmethod
def merge(self, other):
if self.value == other.value:
# TODO if not self.provider == other.provider: new feature with unknown or merging provider
return self
else:
return Feature(0.0)
class FeatureLabeledList(FeatureLabel):
def __init__(self, label=None, value=[], confidence=1.0, provider=None):
self.label, self.value, self.confidence, self.provider = label, value, confidence, provider
def html(self):
return '<em>%s:</em> %s' % (self.label, '; '.join([str(i) for i in self.value]))
@staticmethod
def is_numeric():
return False
@staticmethod
def merge(self, other):
self.value = list(set(self.value) | set(other.value))
return self
class FeatureSentimentPosNeg(Feature):
pass
class FeatureEnum(object):
PERSON = 'person'
NUMBER = 'number'
GENDER = 'gender'
class FeatureTokenLabel(Feature):
def __init__(self, label=None, token=None, confidence=1.0, provider=None):
self.label, self.token, self.confidence, self.provider = label, token, confidence, provider
self.value = self.token.lemma
def html(self):
return '<em>%s:</em> %s' % (self.label, self.token.lemma) + (
'<small> %.2f</small>' % self.token.weight if self.token.weight < 0 else '')
class FeatureTokenLabelValue(FeatureTokenLabel):
def __init__(self, label=None, value=None, token=None, confidence=1.0, provider=None):
self.label, self.value, self.token, self.confidence, self.provider = label, value, token, confidence, provider
def html(self):
return '<em>%s:</em> %s' % (self.label, self.value) + (
'<small> %.2f</small>' % self.token.weight if self.token.weight < 0 else '')
# This class is only used for information purposes DISABLE_FEATURES_INFORMATION
class FeatureWN(FeatureTokenLabelValue):
@classmethod
def attributes(cls, tokens, provider):
attributes = []
for token in tokens:
for attribute in datamanager.nltk_wordnet.query_expand(token):
if attribute[0] == 'desc':
attributes.append(FeatureTokenLabelValue(attribute[0], attribute[1], token, confidence=1.0,
provider=provider) if isinstance(attribute[1],
str) else cls(
attribute[0], attribute[1], token))
else:
attributes.append(
cls(attribute[0], attribute[1], token, confidence=1.0, provider=provider) if isinstance(
attribute[1], str) else cls(attribute[0], attribute[1], token))
return attributes
def html(self):
return '<em>%s:</em> [%s]' % (self.label, ', '.join(self.value.lemma_names)) + (
'<small> %.2f</small>' % self.token.weight if self.token.weight < 0 else '')
# This class is only used for information purposes DISABLE_FEATURES_INFORMATION
class FeatureCN(FeatureTokenLabelValue):
@classmethod
def attributes(cls, tokens, provider):
attributes = []
for token in tokens:
for attribute in datamanager.conceptnet.query_expand(token):
attributes.append(cls(attribute[0], attribute[1], token, confidence=1.0, provider=provider))
return attributes
'''