KoichiYasuoka commited on
Commit
2e5b5f5
1 Parent(s): 83685bc

chu_liu_edmonds

Browse files
Files changed (2) hide show
  1. README.md +3 -3
  2. ud.py +33 -18
README.md CHANGED
@@ -64,12 +64,12 @@ nlp=UDgoeswith("KoichiYasuoka/roberta-base-japanese-aozora-ud-goeswith")
64
  print(nlp("全学年にわたって小学校の国語の教科書に挿し絵が用いられている"))
65
  ```
66
 
67
- or
 
68
 
69
  ```
70
  from transformers import pipeline
71
- nlp=pipeline("universal-dependencies","KoichiYasuoka/roberta-base-japanese-aozora-ud-goeswith",trust_remote_code=True)
72
  print(nlp("全学年にわたって小学校の国語の教科書に挿し絵が用いられている"))
73
  ```
74
 
75
- [ufal.chu-liu-edmonds](https://pypi.org/project/ufal.chu-liu-edmonds/) is required.
64
  print(nlp("全学年にわたって小学校の国語の教科書に挿し絵が用いられている"))
65
  ```
66
 
67
+ with [ufal.chu-liu-edmonds](https://pypi.org/project/ufal.chu-liu-edmonds/).
68
+ Or without ufal.chu-liu-edmonds:
69
 
70
  ```
71
  from transformers import pipeline
72
+ nlp=pipeline("universal-dependencies","KoichiYasuoka/roberta-base-japanese-aozora-ud-goeswith",trust_remote_code=True,aggregation_strategy="simple")
73
  print(nlp("全学年にわたって小学校の国語の教科書に挿し絵が用いられている"))
74
  ```
75
 
 
ud.py CHANGED
@@ -9,7 +9,6 @@ class UniversalDependenciesPipeline(TokenClassificationPipeline):
9
  return {"logits":e.logits[:,1:-2,:],**model_input}
10
  def postprocess(self,model_output,**kwargs):
11
  import numpy
12
- import ufal.chu_liu_edmonds
13
  e=model_output["logits"].numpy()
14
  r=[1 if i==0 else -1 if j.endswith("|root") else 0 for i,j in sorted(self.model.config.id2label.items())]
15
  e+=numpy.where(numpy.add.outer(numpy.identity(e.shape[0]),r)==0,0,numpy.nan)
@@ -19,27 +18,43 @@ class UniversalDependenciesPipeline(TokenClassificationPipeline):
19
  for j in range(i+2,e.shape[1]):
20
  r[i,j]=r[i,j-1] if numpy.nanargmax(e[i,j-1])==g else 1
21
  e[:,:,g]+=numpy.where(r==0,0,numpy.nan)
22
- m=numpy.full((e.shape[0]+1,e.shape[1]+1),numpy.nan)
23
- m[1:,1:]=numpy.nanmax(e,axis=2).transpose()
24
- p=numpy.zeros(m.shape)
25
- p[1:,1:]=numpy.nanargmax(e,axis=2).transpose()
26
- for i in range(1,m.shape[0]):
27
- m[i,0],m[i,i],p[i,0]=m[i,i],numpy.nan,p[i,i]
28
- h=ufal.chu_liu_edmonds.chu_liu_edmonds(m)[0]
29
- if [0 for i in h if i==0]!=[0]:
30
- m[:,0]+=numpy.where(m[:,0]==numpy.nanmax(m[[i for i,j in enumerate(h) if j==0],0]),0,numpy.nan)
31
- m[[i for i,j in enumerate(h) if j==0]]+=[0 if i==0 or j==0 else numpy.nan for i,j in enumerate(h)]
32
- h=ufal.chu_liu_edmonds.chu_liu_edmonds(m)[0]
33
  v=[(s,e) for s,e in model_output["offset_mapping"][0].tolist() if s<e]
34
- q=[self.model.config.id2label[p[i,j]].split("|") for i,j in enumerate(h)]
35
  if "aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none":
36
- for i,j in reversed(list(enumerate(q[2:],2))):
37
- if j[-1]=="goeswith":
38
  h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a]
39
- v[i-2]=(v[i-2][0],v.pop(i-1)[1])
40
  q.pop(i)
41
  t=model_output["sentence"].replace("\n"," ")
42
  u="# text = "+t+"\n"
43
- for i,(s,e) in enumerate(v,1):
44
- u+="\t".join([str(i),t[s:e],"_",q[i][0],"_","|".join(q[i][1:-1]),str(h[i]),q[i][-1],"_","_" if i<len(v) and e<v[i][0] else "SpaceAfter=No"])+"\n"
45
  return u+"\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  return {"logits":e.logits[:,1:-2,:],**model_input}
10
  def postprocess(self,model_output,**kwargs):
11
  import numpy
 
12
  e=model_output["logits"].numpy()
13
  r=[1 if i==0 else -1 if j.endswith("|root") else 0 for i,j in sorted(self.model.config.id2label.items())]
14
  e+=numpy.where(numpy.add.outer(numpy.identity(e.shape[0]),r)==0,0,numpy.nan)
18
  for j in range(i+2,e.shape[1]):
19
  r[i,j]=r[i,j-1] if numpy.nanargmax(e[i,j-1])==g else 1
20
  e[:,:,g]+=numpy.where(r==0,0,numpy.nan)
21
+ m,p=numpy.nanmax(e,axis=2),numpy.nanargmax(e,axis=2)
22
+ h=self.chu_liu_edmonds(m)
23
+ z=[i for i,j in enumerate(h) if i==j]
24
+ if len(z)>1:
25
+ k,h=z[numpy.nanargmax(m[z,z])],numpy.nanmin(m)-numpy.nanmax(m)
26
+ 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])]
27
+ h=self.chu_liu_edmonds(m)
 
 
 
 
28
  v=[(s,e) for s,e in model_output["offset_mapping"][0].tolist() if s<e]
29
+ q=[self.model.config.id2label[p[j,i]].split("|") for i,j in enumerate(h)]
30
  if "aggregation_strategy" in kwargs and kwargs["aggregation_strategy"]!="none":
31
+ for i,j in reversed(list(enumerate(q[1:],1))):
32
+ if j[-1]=="goeswith" and set([t[-1] for t in q[h[i]+1:i+1]])=={"goeswith"}:
33
  h=[b if i>b else b-1 for a,b in enumerate(h) if i!=a]
34
+ v[i-1]=(v[i-1][0],v.pop(i)[1])
35
  q.pop(i)
36
  t=model_output["sentence"].replace("\n"," ")
37
  u="# text = "+t+"\n"
38
+ for i,(s,e) in enumerate(v):
39
+ u+="\t".join([str(i+1),t[s:e],"_",q[i][0],"_","|".join(q[i][1:-1]),str(0 if h[i]==i else h[i]+1),q[i][-1],"_","_" if i+1<len(v) and e<v[i+1][0] else "SpaceAfter=No"])+"\n"
40
  return u+"\n"
41
+ def chu_liu_edmonds(self,matrix):
42
+ import numpy
43
+ h=numpy.nanargmax(matrix,axis=0)
44
+ x=[-1 if i==j else j for i,j in enumerate(h)]
45
+ 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]]:
46
+ y=[]
47
+ while x!=y:
48
+ y=list(x)
49
+ for i,j in enumerate(x):
50
+ x[i]=b(x,i,j)
51
+ if max(x)<0:
52
+ return h
53
+ y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
54
+ z=matrix-numpy.nanmax(matrix,axis=0)
55
+ m=numpy.block([[z[x,:][:,x],numpy.nanmax(z[x,:][:,y],axis=1).reshape(len(x),1)],[numpy.nanmax(z[y,:][:,x],axis=0),numpy.nanmax(z[y,y])]])
56
+ k=[j if i==len(x) else x[j] if j<len(x) else y[numpy.nanargmax(z[y,x[i]])] for i,j in enumerate(self.chu_liu_edmonds(m))]
57
+ h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
58
+ i=y[numpy.nanargmax(z[x[k[-1]],y] if k[-1]<len(x) else z[y,y])]
59
+ h[i]=x[k[-1]] if k[-1]<len(x) else i
60
+ return h