KoichiYasuoka
commited on
Commit
·
fd3aa4f
1
Parent(s):
b2e4dd0
algorithm improved
Browse files
ud.py
CHANGED
@@ -6,7 +6,7 @@ class BellmanFordTokenClassificationPipeline(TokenClassificationPipeline):
|
|
6 |
super().__init__(**kwargs)
|
7 |
x=self.model.config.label2id
|
8 |
y=[k for k in x if k.startswith("B-") or not (k.startswith("I-") or k.endswith("|root") or k.find("|l-")>0 or k.find("|r-")>0)]
|
9 |
-
self.transition=numpy.full((len(x),len(x))
|
10 |
for k,v in x.items():
|
11 |
for j in ["I-"+k[2:]] if k.startswith("B-") else [k]+y if k.startswith("I-") else y:
|
12 |
self.transition[v,x[j]]=0
|
@@ -19,10 +19,10 @@ class BellmanFordTokenClassificationPipeline(TokenClassificationPipeline):
|
|
19 |
e=numpy.exp(m-numpy.max(m,axis=-1,keepdims=True))
|
20 |
z=e/e.sum(axis=-1,keepdims=True)
|
21 |
for i in range(m.shape[0]-1,0,-1):
|
22 |
-
m[i-1]+=numpy.
|
23 |
-
k=[numpy.
|
24 |
for i in range(1,m.shape[0]):
|
25 |
-
k.append(numpy.
|
26 |
w=[{"entity":self.model.config.id2label[j],"start":s,"end":e,"score":z[i,j]} for i,((s,e),j) in enumerate(zip(model_outputs["offset_mapping"][0].tolist(),k)) if s<e]
|
27 |
if "aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none":
|
28 |
for i,t in reversed(list(enumerate(w))):
|
@@ -43,9 +43,9 @@ class UniversalDependenciesCausalPipeline(BellmanFordTokenClassificationPipeline
|
|
43 |
kwargs["aggregation_strategy"]="simple"
|
44 |
super().__init__(**kwargs)
|
45 |
x=self.model.config.label2id
|
46 |
-
self.root=numpy.full((len(x))
|
47 |
-
self.left_arc=numpy.full((len(x))
|
48 |
-
self.right_arc=numpy.full((len(x))
|
49 |
for k,v in x.items():
|
50 |
if k.endswith("|root"):
|
51 |
self.root[v]=0
|
@@ -59,10 +59,10 @@ class UniversalDependenciesCausalPipeline(BellmanFordTokenClassificationPipeline
|
|
59 |
return self.postprocess(model_outputs[0],**kwargs)
|
60 |
m=model_outputs["logits"][0].numpy()
|
61 |
for i in range(m.shape[0]-1,0,-1):
|
62 |
-
m[i-1]+=numpy.
|
63 |
-
k=[numpy.
|
64 |
for i in range(1,m.shape[0]):
|
65 |
-
k.append(numpy.
|
66 |
w=[{"entity":self.model.config.id2label[j],"start":s,"end":e} for i,((s,e),j) in enumerate(zip(model_outputs["offset_mapping"][0].tolist(),k)) if s<e]
|
67 |
for i,t in reversed(list(enumerate(w))):
|
68 |
p=t.pop("entity")
|
@@ -108,11 +108,11 @@ class UniversalDependenciesCausalPipeline(BellmanFordTokenClassificationPipeline
|
|
108 |
for j in range(i):
|
109 |
e[-j-1,-i-1],e[-i-1,-j-1]=e[-i-1,i-j]+self.left_arc,e[-i-1,i-j]+self.right_arc
|
110 |
e[-i-1,-i-1]=e[-i-1,0]+self.root
|
111 |
-
m,p=numpy.
|
112 |
h=self.chu_liu_edmonds(m)
|
113 |
z=[i for i,j in enumerate(h) if i==j]
|
114 |
if len(z)>1:
|
115 |
-
k,h=z[numpy.
|
116 |
m[:,z]+=[[0 if j in z and (i!=j or i==k) else h for i in z] for j in range(m.shape[0])]
|
117 |
h=self.chu_liu_edmonds(m)
|
118 |
q=[self.model.config.id2label[p[j,i]].split("|") for i,j in enumerate(h)]
|
@@ -122,7 +122,7 @@ class UniversalDependenciesCausalPipeline(BellmanFordTokenClassificationPipeline
|
|
122 |
u+="\t".join([str(i+1),j,"_",q[i][0],"_","_" if len(q[i])<3 else "|".join(q[i][1:-1]),str(0 if h[i]==i else h[i]+1),"root" if q[i][-1]=="root" else q[i][-1][2:],"_","_" if i+1<len(d) and w[i]["end"]<w[i+1]["start"] else "SpaceAfter=No"])+"\n"
|
123 |
return u+"\n"
|
124 |
def chu_liu_edmonds(self,matrix):
|
125 |
-
h=numpy.
|
126 |
x=[-1 if i==j else j for i,j in enumerate(h)]
|
127 |
for b in [lambda x,i,j:-1 if i not in x else x[i],lambda x,i,j:-1 if j<0 else x[j]]:
|
128 |
y=[]
|
@@ -133,10 +133,10 @@ class UniversalDependenciesCausalPipeline(BellmanFordTokenClassificationPipeline
|
|
133 |
if max(x)<0:
|
134 |
return h
|
135 |
y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
|
136 |
-
z=matrix-numpy.
|
137 |
-
m=numpy.block([[z[x,:][:,x],numpy.
|
138 |
-
k=[j if i==len(x) else x[j] if j<len(x) else y[numpy.
|
139 |
h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
|
140 |
-
i=y[numpy.
|
141 |
h[i]=x[k[-1]] if k[-1]<len(x) else i
|
142 |
return h
|
|
|
6 |
super().__init__(**kwargs)
|
7 |
x=self.model.config.label2id
|
8 |
y=[k for k in x if k.startswith("B-") or not (k.startswith("I-") or k.endswith("|root") or k.find("|l-")>0 or k.find("|r-")>0)]
|
9 |
+
self.transition=numpy.full((len(x),len(x)),-numpy.inf)
|
10 |
for k,v in x.items():
|
11 |
for j in ["I-"+k[2:]] if k.startswith("B-") else [k]+y if k.startswith("I-") else y:
|
12 |
self.transition[v,x[j]]=0
|
|
|
19 |
e=numpy.exp(m-numpy.max(m,axis=-1,keepdims=True))
|
20 |
z=e/e.sum(axis=-1,keepdims=True)
|
21 |
for i in range(m.shape[0]-1,0,-1):
|
22 |
+
m[i-1]+=numpy.max(m[i]+self.transition,axis=1)
|
23 |
+
k=[numpy.argmax(m[0]+self.transition[0])]
|
24 |
for i in range(1,m.shape[0]):
|
25 |
+
k.append(numpy.argmax(m[i]+self.transition[k[-1]]))
|
26 |
w=[{"entity":self.model.config.id2label[j],"start":s,"end":e,"score":z[i,j]} for i,((s,e),j) in enumerate(zip(model_outputs["offset_mapping"][0].tolist(),k)) if s<e]
|
27 |
if "aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none":
|
28 |
for i,t in reversed(list(enumerate(w))):
|
|
|
43 |
kwargs["aggregation_strategy"]="simple"
|
44 |
super().__init__(**kwargs)
|
45 |
x=self.model.config.label2id
|
46 |
+
self.root=numpy.full((len(x)),-numpy.inf)
|
47 |
+
self.left_arc=numpy.full((len(x)),-numpy.inf)
|
48 |
+
self.right_arc=numpy.full((len(x)),-numpy.inf)
|
49 |
for k,v in x.items():
|
50 |
if k.endswith("|root"):
|
51 |
self.root[v]=0
|
|
|
59 |
return self.postprocess(model_outputs[0],**kwargs)
|
60 |
m=model_outputs["logits"][0].numpy()
|
61 |
for i in range(m.shape[0]-1,0,-1):
|
62 |
+
m[i-1]+=numpy.max(m[i]+self.transition,axis=1)
|
63 |
+
k=[numpy.argmax(m[0]+self.transition[0])]
|
64 |
for i in range(1,m.shape[0]):
|
65 |
+
k.append(numpy.argmax(m[i]+self.transition[k[-1]]))
|
66 |
w=[{"entity":self.model.config.id2label[j],"start":s,"end":e} for i,((s,e),j) in enumerate(zip(model_outputs["offset_mapping"][0].tolist(),k)) if s<e]
|
67 |
for i,t in reversed(list(enumerate(w))):
|
68 |
p=t.pop("entity")
|
|
|
108 |
for j in range(i):
|
109 |
e[-j-1,-i-1],e[-i-1,-j-1]=e[-i-1,i-j]+self.left_arc,e[-i-1,i-j]+self.right_arc
|
110 |
e[-i-1,-i-1]=e[-i-1,0]+self.root
|
111 |
+
m,p=numpy.max(e,axis=2),numpy.argmax(e,axis=2)
|
112 |
h=self.chu_liu_edmonds(m)
|
113 |
z=[i for i,j in enumerate(h) if i==j]
|
114 |
if len(z)>1:
|
115 |
+
k,h=z[numpy.argmax(m[z,z])],numpy.min(m)-numpy.max(m)
|
116 |
m[:,z]+=[[0 if j in z and (i!=j or i==k) else h for i in z] for j in range(m.shape[0])]
|
117 |
h=self.chu_liu_edmonds(m)
|
118 |
q=[self.model.config.id2label[p[j,i]].split("|") for i,j in enumerate(h)]
|
|
|
122 |
u+="\t".join([str(i+1),j,"_",q[i][0],"_","_" if len(q[i])<3 else "|".join(q[i][1:-1]),str(0 if h[i]==i else h[i]+1),"root" if q[i][-1]=="root" else q[i][-1][2:],"_","_" if i+1<len(d) and w[i]["end"]<w[i+1]["start"] else "SpaceAfter=No"])+"\n"
|
123 |
return u+"\n"
|
124 |
def chu_liu_edmonds(self,matrix):
|
125 |
+
h=numpy.argmax(matrix,axis=0)
|
126 |
x=[-1 if i==j else j for i,j in enumerate(h)]
|
127 |
for b in [lambda x,i,j:-1 if i not in x else x[i],lambda x,i,j:-1 if j<0 else x[j]]:
|
128 |
y=[]
|
|
|
133 |
if max(x)<0:
|
134 |
return h
|
135 |
y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
|
136 |
+
z=matrix-numpy.max(matrix,axis=0)
|
137 |
+
m=numpy.block([[z[x,:][:,x],numpy.max(z[x,:][:,y],axis=1).reshape(len(x),1)],[numpy.max(z[y,:][:,x],axis=0),numpy.max(z[y,y])]])
|
138 |
+
k=[j if i==len(x) else x[j] if j<len(x) else y[numpy.argmax(z[y,x[i]])] for i,j in enumerate(self.chu_liu_edmonds(m))]
|
139 |
h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
|
140 |
+
i=y[numpy.argmax(z[x[k[-1]],y] if k[-1]<len(x) else z[y,y])]
|
141 |
h[i]=x[k[-1]] if k[-1]<len(x) else i
|
142 |
return h
|