KoichiYasuoka commited on
Commit
33127b8
·
1 Parent(s): 8c1a347
Files changed (1) hide show
  1. ud.py +19 -18
ud.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from transformers import TokenClassificationPipeline
2
 
3
  class UniversalDependenciesPipeline(TokenClassificationPipeline):
@@ -13,17 +14,17 @@ class UniversalDependenciesPipeline(TokenClassificationPipeline):
13
  else:
14
  t.append((k,(s,e)))
15
  m=[(0,0)]+[j for i,j in t]+[(0,0)]
16
- r=super().preprocess(sentence=" ".join(i for i,j in t))
17
- w=self.tokenizer.convert_ids_to_tokens(r["input_ids"][0])
18
  if len(m)!=len(w):
19
  for i,j in enumerate(w):
20
  if j.endswith("@@"):
21
  s,e=m[i]
22
  m.insert(i+1,(s+len(j)-2,e))
23
  m[i]=(s,s+len(j)-2)
24
- r["offset_mapping"]=torch.tensor([m],device=self.device)
25
- r["sentence"]=sentence
26
- return r
27
  def _forward(self,model_inputs):
28
  import torch
29
  v=model_inputs["input_ids"][0].tolist()
@@ -31,23 +32,24 @@ class UniversalDependenciesPipeline(TokenClassificationPipeline):
31
  e=self.model(input_ids=torch.tensor([v[0:i]+[self.tokenizer.mask_token_id]+v[i+1:]+[j] for i,j in enumerate(v[1:-1],1)],device=self.device))
32
  return {"logits":e.logits[:,1:-2,:],**model_inputs}
33
  def postprocess(self,model_outputs,**kwargs):
34
- import numpy
35
  if "logits" not in model_outputs:
36
  return "".join(self.postprocess(x,**kwargs) for x in model_outputs)
37
  e=model_outputs["logits"].numpy()
38
  r=[1 if i==0 else -1 if j.endswith("|root") else 0 for i,j in sorted(self.model.config.id2label.items())]
39
- e+=numpy.where(numpy.add.outer(numpy.identity(e.shape[0]),r)==0,0,numpy.nan)
40
  g=self.model.config.label2id["X|_|goeswith"]
41
- r=numpy.tri(e.shape[0])
42
  for i in range(e.shape[0]):
43
  for j in range(i+2,e.shape[1]):
44
- r[i,j]=r[i,j-1] if numpy.nanargmax(e[i,j-1])==g else 1
45
- e[:,:,g]+=numpy.where(r==0,0,numpy.nan)
46
- m,p=numpy.nanmax(e,axis=2),numpy.nanargmax(e,axis=2)
 
 
47
  h=self.chu_liu_edmonds(m)
48
  z=[i for i,j in enumerate(h) if i==j]
49
  if len(z)>1:
50
- k,h=z[numpy.nanargmax(m[z,z])],numpy.nanmin(m)-numpy.nanmax(m)
51
  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])]
52
  h=self.chu_liu_edmonds(m)
53
  v=[(s,e) for s,e in model_outputs["offset_mapping"][0].tolist() if s<e]
@@ -65,8 +67,7 @@ class UniversalDependenciesPipeline(TokenClassificationPipeline):
65
  u+="\t".join([str(i+1),t[s:e],t[s:e] if g else "_",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"
66
  return u+"\n"
67
  def chu_liu_edmonds(self,matrix):
68
- import numpy
69
- h=numpy.nanargmax(matrix,axis=0)
70
  x=[-1 if i==j else j for i,j in enumerate(h)]
71
  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]]:
72
  y=[]
@@ -77,10 +78,10 @@ class UniversalDependenciesPipeline(TokenClassificationPipeline):
77
  if max(x)<0:
78
  return h
79
  y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
80
- z=matrix-numpy.nanmax(matrix,axis=0)
81
- 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])]])
82
- 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))]
83
  h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
84
- i=y[numpy.nanargmax(z[x[k[-1]],y] if k[-1]<len(x) else z[y,y])]
85
  h[i]=x[k[-1]] if k[-1]<len(x) else i
86
  return h
 
1
+ import numpy
2
  from transformers import TokenClassificationPipeline
3
 
4
  class UniversalDependenciesPipeline(TokenClassificationPipeline):
 
14
  else:
15
  t.append((k,(s,e)))
16
  m=[(0,0)]+[j for i,j in t]+[(0,0)]
17
+ r=list(super().preprocess(sentence=" ".join(i for i,j in t)))
18
+ w=self.tokenizer.convert_ids_to_tokens(r[0]["input_ids"][0])
19
  if len(m)!=len(w):
20
  for i,j in enumerate(w):
21
  if j.endswith("@@"):
22
  s,e=m[i]
23
  m.insert(i+1,(s+len(j)-2,e))
24
  m[i]=(s,s+len(j)-2)
25
+ r[0]["offset_mapping"]=torch.tensor([m]).to(self.device)
26
+ r[0]["sentence"]=sentence
27
+ return iter(r)
28
  def _forward(self,model_inputs):
29
  import torch
30
  v=model_inputs["input_ids"][0].tolist()
 
32
  e=self.model(input_ids=torch.tensor([v[0:i]+[self.tokenizer.mask_token_id]+v[i+1:]+[j] for i,j in enumerate(v[1:-1],1)],device=self.device))
33
  return {"logits":e.logits[:,1:-2,:],**model_inputs}
34
  def postprocess(self,model_outputs,**kwargs):
 
35
  if "logits" not in model_outputs:
36
  return "".join(self.postprocess(x,**kwargs) for x in model_outputs)
37
  e=model_outputs["logits"].numpy()
38
  r=[1 if i==0 else -1 if j.endswith("|root") else 0 for i,j in sorted(self.model.config.id2label.items())]
39
+ e+=numpy.where(numpy.add.outer(numpy.identity(e.shape[0]),r)==0,0,-numpy.inf)
40
  g=self.model.config.label2id["X|_|goeswith"]
41
+ m,r=numpy.max(e,axis=2),numpy.tri(e.shape[0])
42
  for i in range(e.shape[0]):
43
  for j in range(i+2,e.shape[1]):
44
+ r[i,j]=1
45
+ if numpy.argmax(e[i,j-1])==g and numpy.argmax(m[:,j-1])==i:
46
+ r[i,j]=r[i,j-1]
47
+ e[:,:,g]+=numpy.where(r==0,0,-numpy.inf)
48
+ m,p=numpy.max(e,axis=2),numpy.argmax(e,axis=2)
49
  h=self.chu_liu_edmonds(m)
50
  z=[i for i,j in enumerate(h) if i==j]
51
  if len(z)>1:
52
+ k,h=z[numpy.argmax(m[z,z])],numpy.min(m)-numpy.max(m)
53
  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])]
54
  h=self.chu_liu_edmonds(m)
55
  v=[(s,e) for s,e in model_outputs["offset_mapping"][0].tolist() if s<e]
 
67
  u+="\t".join([str(i+1),t[s:e],t[s:e] if g else "_",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"
68
  return u+"\n"
69
  def chu_liu_edmonds(self,matrix):
70
+ h=numpy.argmax(matrix,axis=0)
 
71
  x=[-1 if i==j else j for i,j in enumerate(h)]
72
  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]]:
73
  y=[]
 
78
  if max(x)<0:
79
  return h
80
  y,x=[i for i,j in enumerate(x) if j==max(x)],[i for i,j in enumerate(x) if j<max(x)]
81
+ z=matrix-numpy.max(matrix,axis=0)
82
+ 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])]])
83
+ 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))]
84
  h=[j if i in y else k[x.index(i)] for i,j in enumerate(h)]
85
+ i=y[numpy.argmax(z[x[k[-1]],y] if k[-1]<len(x) else z[y,y])]
86
  h[i]=x[k[-1]] if k[-1]<len(x) else i
87
  return h