-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathBIO_TAG_inference.py
163 lines (130 loc) · 6.01 KB
/
BIO_TAG_inference.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
# -*- coding: utf-8 -*-
#open('/Users/lmy/Dropbox/Personal/Coursework/CIS700-006/Project/POS_tagger_trained_on_Universal_Dependency_French_corpus/file.txt').read().decode('utf-8').split()
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import codecs
from sklearn.feature_extraction import DictVectorizer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
import argparse
parser = argparse.ArgumentParser(description='Logistic regression BIO.')
parser.add_argument('--train', help='Training file')
parser.add_argument('--test', help='Test file')
parser.add_argument('--embed', help='Character embedding file')
args = parser.parse_args()
train_path = args.train
test_path = args.test
#train_path = '/Users/lmy/Dropbox/Personal/Coursework/CIS700-006/Project/UD_CH/zh-ud-train.conllu'
#train_path = '/Users/lmy/Dropbox/Personal/Coursework/CIS700-006/Project/BIO_TAG/file.txt'
#test_path = '/Users/lmy/Dropbox/Personal/Coursework/CIS700-006/Project/UD_CH/zh-ud-dev.conllu'
Pu='~`!@#$%^&*()_-+={[}]|\:;"\'<,>.?/'
Universal_tag_set = set()
def features(sentence, index, tags_previous_index = None):
#""" sentence: [w1, w2, ...], index: the index of the word """
return {
'word': sentence[index],
'is_first': index == 0,
'is_last': index == len(sentence) - 1,
'prev_word': '<s>' if index == 0 else sentence[index - 1],
'C-2': '<s>' if index <= 1 else sentence[index - 1],
'next_word': '</s>' if index == len(sentence) - 1 else sentence[index + 1],
'C2': '</s>' if index >= len(sentence) - 2 else sentence[index + 2],
'C1C2': '</s>' if index >= len(sentence) - 2 else sentence[index+1]+sentence[index+2],
'C0C1': '</s>' if index == len(sentence) - 1 else sentence[index]+sentence[index+1],
'C-1C0': '</s>' if index == 0 else sentence[index-1]+sentence[index],
'C-2C-1': '</s>' if index <= 1 else sentence[index-2]+sentence[index-1],
'C-1C1': '</s>' if (index == 0 or index == len(sentence) - 1 ) else sentence[index-1]+sentence[index+1],
'Pu(C0)': (sentence[index - 1] in Pu) ,
'is_numeric': sentence[index].isdigit(),
'T-1': '<s>' if index == 0 else (None if tags_previous_index is None else tags_previous_index[index-1])
}
'''
def features(sentence, index):
#""" sentence: [w1, w2, ...], index: the index of the word """
return {
'word': sentence[index],
'is_first': index == 0,
'is_last': index == len(sentence) - 1,
'prev_word': '<s>' if index == 0 else sentence[index - 1],
'next_word': '</s>' if index == len(sentence) - 1 else sentence[index + 1],
'is_numeric': sentence[index].isdigit(),
}
'''
def untag(tagged_sentence):
return [w for w, t in tagged_sentence]
def gen_corpus(path):
doc = []
tagset = set()
file = codecs.open(path, encoding='utf-8')
#with open(path, encoding='utf-8') as file:
for line in file:
if line[0].isdigit():
features = line.split()
word, pos= features[1], features[3]
if pos != "_":
if(len(word)>1):
tagset.add('B'+pos)
if(not ('B'+pos) in Universal_tag_set):
Universal_tag_set.add('B'+pos)
tagset.add('I'+pos)
if(not ('I'+pos) in Universal_tag_set):
Universal_tag_set.add('I'+pos)
for order in range(len(word)):
if(order==0):
doc.append((word[order], 'B'+pos))
if(order!=0):
doc.append((word[order], 'I'+pos))
else:
tagset.add('B'+pos)
if(not ('B'+pos) in Universal_tag_set):
Universal_tag_set.add('B'+pos)
doc.append((word, 'B'+pos))
elif len(line.strip()) == 0:
if len(doc) > 0:
words, tags = zip(*doc)
yield (list(words), list(tags))
doc = []
def transform_to_dataset(tagged_sentences):
X, y = [], []
for words, tags in tagged_sentences:
for index, word in enumerate(words):
X.append(features(words, index, tags))
y.append(tags[index])
return X, y
def transform_to_dataset_inference(tagged_sentences):
X, y = [], []
for words, tags in tagged_sentences:
for index, word in enumerate(words):
X.append(features(words, index, tags))
y.append(tags[index])
return X, y
def evaluation(TEST_DATA):
y_pred, y_true = [], []
for words, tags in TEST_DATA:
for i, (word, pos) in enumerate(pos_tag(words)):
y_pred.append(pos)
y_true.append(tags[i])
return y_pred, y_true
def pos_tag(sentence):
feat = features(sentence, index)
tags = clf.predict([features(sentence, index) for index in range(len(sentence))])
return zip(sentence, tags)
training_sentences = list(gen_corpus(train_path))
X, y = transform_to_dataset(training_sentences)
clf = Pipeline([
('vectorizer', DictVectorizer(sparse=True)),
('classifier', LogisticRegression(n_jobs=4, max_iter=200, verbose=True))
])
clf.fit(X, y)
import pickle
pickle.dump((clf, list(Universal_tag_set)), open("log_regression.p", "wb"))
test_sentences = list(gen_corpus(test_path))
X_test, y_test = transform_to_dataset(test_sentences)
print( "Accuracy:", clf.score(X_test, y_test))
y_pred, y_true = evaluation(test_sentences)
for l in classification_report(y_true, y_pred).split('\n'):
print(l)
t = "今天天气非常好。"
print(list(pos_tag(t)))