-
Notifications
You must be signed in to change notification settings - Fork 1
/
at_prep.py
1442 lines (1057 loc) · 46.5 KB
/
at_prep.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from data_prep import *
from sdt import *
import numpy as np
import math
import concurrent.futures
import itertools
import scipy
from scipy.spatial import distance
from scipy.stats.mstats_basic import rankdata
import scipy.sparse as sp
from scipy.optimize import linprog
from scipy import stats
from bert4keras.models import build_transformer_model
from bert4keras.tokenizers import SpTokenizer, Tokenizer
from tqdm import tqdm
import pickle
from multiprocessing import Process
allSegment, allAffect, allOtherFeelings, allPredLabel, allTrueLabel, allTestNum, allSubjectNum = load_data(
)
firstAffect, firstOtherFeelings, firstSafety, firstComfort, firstPredLabel, firstTrueLabel = load_data(
mode=1)
secondAffect, secondOtherFeelings, secondSafety, secondComfort, secondPredLabel, secondTrueLabel = load_data(
mode=2)
thirdAffect, thirdOtherFeelings, thirdSafety, thirdComfort, thirdPredLabel, thirdTrueLabel = load_data(
mode=3)
data2chn = {
(0, 0): '一点也没有快乐',
(0, 1): '较轻微快乐',
(0, 2): '较强烈快乐',
(0, 3): '非常强烈快乐',
(1, 0): '一点也没有兴趣',
(1, 1): '较轻微兴趣',
(1, 2): '较强烈兴趣',
(1, 3): '非常强烈兴趣',
(2, 0): '一点也没有惊奇',
(2, 1): '较轻微惊奇',
(2, 2): '较强烈惊奇',
(2, 3): '非常强烈惊奇',
(3, 0): '一点也没有恐惧',
(3, 1): '较轻微恐惧',
(3, 2): '较强烈恐惧',
(3, 3): '非常强烈恐惧',
(4, 0): '一点也没有紧张',
(4, 1): '较轻微紧张',
(4, 2): '较强烈紧张',
(4, 3): '非常强烈紧张',
(5, 0): '一点也没有满意',
(5, 1): '较轻微满意',
(5, 2): '较强烈满意',
(5, 3): '非常强烈满意'
}
chn2embeddings = {
'一点也没有快乐': 0,
'较轻微快乐': 0,
'较强烈快乐': 0,
'非常强烈快乐': 0,
'一点也没有兴趣': 0,
'较轻微兴趣': 0,
'较强烈兴趣': 0,
'非常强烈兴趣': 0,
'一点也没有惊奇': 0,
'较轻微惊奇': 0,
'较强烈惊奇': 0,
'非常强烈惊奇': 0,
'一点也没有恐惧': 0,
'较轻微恐惧': 0,
'较强烈恐惧': 0,
'非常强烈恐惧': 0,
'一点也没有紧张': 0,
'较轻微紧张': 0,
'较强烈紧张': 0,
'非常强烈紧张': 0,
'一点也没有满意': 0,
'较轻微满意': 0,
'较强烈满意': 0,
'非常强烈满意': 0
}
def convert(data):
return [data2chn[(int(i), int(j))] for i, j in enumerate(data)]
def n_component(length, wd=False):
s1 = [2**(i + 1) for i in range(10) if 2**(i + 1) <= length / 2]
s2 = [
s1[i] + s1[i + 1] for i in range(len(s1) - 1)
if s1[i] + s1[i + 1] <= length / 2
]
if wd:
return sorted(s1 + s2)
else:
return sorted([1] + s1 + s2)
def compute_kernel_bias(vecs):
vecs = np.array(vecs)
mu = vecs.mean(axis=0, keepdims=True)
cov = np.cov(vecs.T)
try:
u, s, vh = np.linalg.svd(cov)
except:
u, s, vh = scipy.linalg.svd(cov, lapack_driver='gesvd')
W = np.dot(u, np.diag(1 / np.sqrt(s)))
return W, -mu, cov
def transform(vecs, kernel=None, bias=None):
if not (kernel is None or bias is None):
return (vecs + bias).dot(kernel)
def abs_distance(x, y, n):
return abs(x - y) / n
def mean_distance(x, y, n):
return 1 - np.mean((x, y)) / n
def min_distance(x, y, n):
return 1 - min(x, y) / n
def am_distance(x, y, n):
return abs(x - y) * (1 - np.mean((x, y)) / n)
def max_distance(x, y, n):
return max(x, y) / n
def pearson_distance(x, y, n=None):
return distance.correlation(x, y)
def euclidean_distance(x, y, n=None):
return np.linalg.norm(x - y)
def mahalanobis_distance(x, y, cov, n=None):
return np.sqrt(np.dot(np.dot(x - y, cov), x - y))
def cosine_distance(x, y, n=None):
return 1 - np.sum(x * y) / (np.linalg.norm(x) * np.linalg.norm(y))
def manhattan_distance(x, y, n=None):
return np.sum(np.abs(x - y))
def wasserstein_distance(p, q, D):
A_eq = []
for i in range(len(p)):
A = np.zeros_like(D)
A[i, :] = 1
A_eq.append(A.reshape(-1))
for i in range(len(q)):
A = np.zeros_like(D)
A[:, i] = 1
A_eq.append(A.reshape(-1))
A_eq = np.array(A_eq)
b_eq = np.concatenate([p, q])
D = D.reshape(-1)
result = linprog(D, A_eq=A_eq[:-1], b_eq=b_eq[:-1])
return result.fun
def word_mover_distance(x, y):
p = np.ones(x.shape[0]) / x.shape[0]
q = np.ones(y.shape[0]) / y.shape[0]
D = np.sqrt(np.square(x[:, None] - y[None, :]).mean(axis=2))
return wasserstein_distance(p, q, D)
def word_rotator_distance(x, y):
x_norm = (x**2).sum(axis=1, keepdims=True)**0.5
y_norm = (y**2).sum(axis=1, keepdims=True)**0.5
p = x_norm[:, 0] / x_norm.sum()
q = y_norm[:, 0] / y_norm.sum()
D = 1 - np.dot(x / x_norm, (y / y_norm).T)
return wasserstein_distance(p, q, D)
def form_matrix(e1, e2):
max_e1 = np.max(e1, axis=0)
max_e2 = np.max(e2, axis=0)
mean_e1 = np.mean(e1, axis=0)
mean_e2 = np.mean(e2, axis=0)
min_e1 = np.min(e1, axis=0)
min_e2 = np.min(e2, axis=0)
return (max_e1, max_e2), (mean_e1, mean_e2), (min_e1, min_e2), \
(np.concatenate((max_e1, mean_e1)), np.concatenate((max_e2, mean_e2))), \
(np.concatenate((max_e1, min_e1)), np.concatenate((max_e2, min_e2))), \
(np.concatenate((mean_e1, min_e1)), np.concatenate((mean_e2, min_e2))), \
(np.concatenate((max_e1, mean_e1, min_e1)), np.concatenate((max_e2, mean_e2, min_e2)))
def explore_vector_av(e1, e2, wd=False, n=None, cov=None):
if wd:
score = []
try:
score.append(word_mover_distance(e1, e2))
except:
e1 = np.nan_to_num(e1, np.sum(e1[~np.isnan(e1)].reshape(-1)))
e2 = np.nan_to_num(e2, np.sum(e2[~np.isnan(e2)].reshape(-1)))
try:
score.append(word_mover_distance(e1, e2))
except:
score.append(word_mover_distance(e1+1e-20, e2+1e-20))
try:
score.append(word_rotator_distance(e1, e2))
except:
e1 = np.nan_to_num(e1, np.sum(e1[~np.isnan(e1)].reshape(-1)))
e2 = np.nan_to_num(e2, np.sum(e2[~np.isnan(e2)].reshape(-1)))
try:
score.append(word_rotator_distance(e1, e2))
except:
score.append(word_rotator_distance(e1+1e-20, e2+1e-20))
return score
else:
score = []
if n != None:
score.append(abs_distance(e1[0], e2[0], n))
score.append(mean_distance(e1[0], e2[0], n))
score.append(min_distance(e1[0], e2[0], n))
score.append(am_distance(e1[0], e2[0], n))
score.append(max_distance(e1[0], e2[0], n))
else:
score.append(pearson_distance(e1, e2))
score.append(euclidean_distance(e1, e2))
score.append(mahalanobis_distance(e1, e2, cov))
score.append(cosine_distance(e1, e2))
score.append(manhattan_distance(e1, e2))
return score
def explore_matrix_av(c, wd=False):
score = []
m1 = [i[0] for i in c]
m2 = [i[-1] for i in c]
n = len(m1)
if wd:
kernel, bias, _ = compute_kernel_bias([v for i in m1 + m2 for v in i])
n_components = n_component(len(m1[0][0]), wd=True)
for i in tqdm(range(len(m1))):
s = []
v1, v2 = m1[i], m2[i]
s.extend(explore_vector_av(v1, v2, wd=True))
s.extend(
explore_vector_av(transform(v1, kernel=kernel, bias=bias),
transform(v2, kernel=kernel, bias=bias),
wd=True))
for nc in n_components:
s.extend(
explore_vector_av(transform(v1,
kernel=kernel[:, :nc],
bias=bias),
transform(v2,
kernel=kernel[:, :nc],
bias=bias),
wd=True))
score.append(s)
return score
else:
kernel, bias, cov = compute_kernel_bias(m1 + m2)
n_components = n_component(len(m1[0]))
COV, M1, M2, N = [], [], [], []
COV.append(cov)
M1.append(m1)
M2.append(m2)
N.append(None)
temp_m1 = [
np.ravel(transform(v1, kernel=kernel, bias=bias)) for v1 in m1
]
temp_m2 = [
np.ravel(transform(v2, kernel=kernel, bias=bias)) for v2 in m2
]
COV.append(np.cov(np.array(temp_m1 + temp_m2).T))
M1.append(temp_m1)
M2.append(temp_m2)
N.append(None)
for nc in n_components:
temp_m1 = [
np.ravel(transform(v1, kernel=kernel[:, :nc], bias=bias))
for v1 in m1
]
temp_m2 = [
np.ravel(transform(v2, kernel=kernel[:, :nc], bias=bias))
for v2 in m2
]
if nc == 1:
COV.append(None)
N.append(n)
else:
COV.append(np.cov(np.array(temp_m1 + temp_m2).T))
N.append(None)
M1.append(temp_m1)
M2.append(temp_m2)
for i in tqdm(range(len(m1))):
s = []
for j in range(len(COV)):
v1, v2, cov, nn = M1[j][i], M2[j][i], COV[j], N[j]
s.extend(explore_vector_av(v1, v2, cov=cov, n=nn))
score.append(s)
return score
def explore_plm_av(data, embeddings, of=False):
MD, MS = [], []
C1D, C2D, C3D, C4D, C5D, C6D, C7D = [], [], [], [], [], [], []
C1S, C2S, C3S, C4S, C5S, C6S, C7S = [], [], [], [], [], [], []
for i in tqdm(range(len(data[0]))):
s = []
d = data[0][i]
if of != 'only':
item1 = convert(d[0])
item2 = convert(d[1])
if of and data[-1][i] != '(空)':
item1.append(data[-1][i])
else:
item1 = [data[-1][i]]
item2 = ['(空)']
e1_d, e1_s = embeddings(item1)
e2_d, e2_s = embeddings(item2)
MD.append((e1_d, e2_d))
MS.append((e1_s, e2_s))
c1d, c2d, c3d, c4d, c5d, c6d, c7d = form_matrix(e1_d, e2_d)
c1s, c2s, c3s, c4s, c5s, c6s, c7s = form_matrix(e1_s, e2_s)
C1D.append(c1d)
C2D.append(c2d)
C3D.append(c3d)
C4D.append(c4d)
C5D.append(c5d)
C6D.append(c6d)
C7D.append(c7d)
C1S.append(c1s)
C2S.append(c2s)
C3S.append(c3s)
C4S.append(c4s)
C5S.append(c5s)
C6S.append(c6s)
C7S.append(c7s)
scoreMD = explore_matrix_av(MD, wd=True)
scoreMS = explore_matrix_av(MS, wd=True)
scoreD1 = explore_matrix_av(C1D)
scoreD2 = explore_matrix_av(C2D)
scoreD3 = explore_matrix_av(C3D)
scoreD4 = explore_matrix_av(C4D)
scoreD5 = explore_matrix_av(C5D)
scoreD6 = explore_matrix_av(C6D)
scoreD7 = explore_matrix_av(C7D)
scoreS1 = explore_matrix_av(C1S)
scoreS2 = explore_matrix_av(C2S)
scoreS3 = explore_matrix_av(C3S)
scoreS4 = explore_matrix_av(C4S)
scoreS5 = explore_matrix_av(C5S)
scoreS6 = explore_matrix_av(C6S)
scoreS7 = explore_matrix_av(C7S)
return np.concatenate((scoreMD, scoreMS, scoreD1, scoreD2, scoreD3, scoreD4, scoreD5, scoreD6, scoreD7, \
scoreS1, scoreS2, scoreS3, scoreS4, scoreS5, scoreS6, scoreS7), axis=1)
def original_emb():
d2c_1 = {0: [0, 0, 0, 1], 1: [0, 0, 1, 0], 2: [0, 1, 0, 0], 3: [1, 0, 0, 0]}
d2c_2 = {0: [0, 1], 1: [1, 0]}
def data2code(data):
return np.array([d2c_1[i] if len(data) > 1 else d2c_2[i] for i in data])
def explore_original_av(data):
score = []
mv_data = [[[l / 3 if idx < 6 and len(j) > 1 else l for idx, l in enumerate(j)] for j in i] for i in data]
X_m = np.mean(sum(mv_data, []), axis=0)
rank_data = rankdata([[sum(i[0]), sum(i[1])] for i in data])
cov = np.cov(sum(mv_data, []), rowvar=False)
for i in tqdm(range(len(data))):
s = []
rank_x = rank_data[i]
x = data[i]
mv_x = mv_data[i]
s.append(abs_distance(rank_x[0], rank_x[1], len(data) * 2))
s.append(mean_distance(rank_x[0], rank_x[1], len(data) * 2))
s.append(min_distance(rank_x[0], rank_x[1], len(data) * 2))
s.append(am_distance(rank_x[0], rank_x[1], len(data) * 2))
s.append(max_distance(rank_x[0], rank_x[1], len(data) * 2))
s.append(pearson_distance(np.array(mv_x[0]), np.array(mv_x[1])))
s.append(euclidean_distance(np.array(x[0]), np.array(mv_x[1])))
s.append(mahalanobis_distance(np.array(mv_x[0]), np.array(mv_x[1]), cov))
s.append(cosine_distance(np.array([xx + 1e-20 for xx in mv_x[0]]), np.array([xx + 1e-20 for xx in mv_x[1]])))
s.append(
cosine_distance(
np.array([xx - X_m[idx] for idx, xx in enumerate(mv_x[0])]),
np.array([xx - X_m[idx] for idx, xx in enumerate(mv_x[1])])))
s.append(manhattan_distance(np.array(mv_x[0]), np.array(mv_x[1])))
s.append(word_mover_distance(data2code(x[0]), data2code(x[1])))
s.append(word_rotator_distance(data2code(x[0]), data2code(x[1])))
score.append(s)
return score
pa = [[[i[0], i[1], i[2], i[-1]] for i in j] for j in allAffect]
na = [[[i[3], i[4]] for i in j] for j in allAffect]
mf = [[[0], [0]] if i == '(空)' else [[0], [1]] for i in firstOtherFeelings+secondOtherFeelings+thirdOtherFeelings]
print('Processing All Affect')
allScore = explore_original_av(allAffect)
firstScore = [allScore[i] for i, j in enumerate(allSegment) if j == 1]
secondScore = [allScore[i] for i, j in enumerate(allSegment) if j == 2]
thirdScore = [allScore[i] for i, j in enumerate(allSegment) if j == 3]
w_filePath = 'data/av_data/original/aa.pkl'
with open(w_filePath, 'wb') as fp:
pickle.dump((allScore, firstScore, secondScore, thirdScore), fp, -1)
print('Processing All Affect and Other Feelings')
allScore = explore_original_av([[j[0]+mf[idx][0], j[1]+mf[idx][1]] for idx, j in enumerate(allAffect)])
firstScore = [allScore[i] for i, j in enumerate(allSegment) if j == 1]
secondScore = [allScore[i] for i, j in enumerate(allSegment) if j == 2]
thirdScore = [allScore[i] for i, j in enumerate(allSegment) if j == 3]
w_filePath = 'data/av_data/original/aa+of.pkl'
with open(w_filePath, 'wb') as fp:
pickle.dump((allScore, firstScore, secondScore, thirdScore), fp, -1)
print('Processing Positive Affect')
allScore = explore_original_av(pa)
firstScore = [allScore[i] for i, j in enumerate(allSegment) if j == 1]
secondScore = [allScore[i] for i, j in enumerate(allSegment) if j == 2]
thirdScore = [allScore[i] for i, j in enumerate(allSegment) if j == 3]
w_filePath = 'data/av_data/original/pa.pkl'
with open(w_filePath, 'wb') as fp:
pickle.dump((allScore, firstScore, secondScore, thirdScore), fp, -1)
print('Processing Positive Affect and Other Feelings')
allScore = explore_original_av([[j[0]+mf[idx][0], j[1]+mf[idx][1]] for idx, j in enumerate(pa)])
firstScore = [allScore[i] for i, j in enumerate(allSegment) if j == 1]
secondScore = [allScore[i] for i, j in enumerate(allSegment) if j == 2]
thirdScore = [allScore[i] for i, j in enumerate(allSegment) if j == 3]
w_filePath = 'data/av_data/original/pa+of.pkl'
with open(w_filePath, 'wb') as fp:
pickle.dump((allScore, firstScore, secondScore, thirdScore), fp, -1)
print('Processing Negative Affect')
allScore = explore_original_av(na)
firstScore = [allScore[i] for i, j in enumerate(allSegment) if j == 1]
secondScore = [allScore[i] for i, j in enumerate(allSegment) if j == 2]
thirdScore = [allScore[i] for i, j in enumerate(allSegment) if j == 3]
w_filePath = 'data/av_data/original/na.pkl'
with open(w_filePath, 'wb') as fp:
pickle.dump((allScore, firstScore, secondScore, thirdScore), fp, -1)
print('Processing Negative Affect and Other Feelings')
allScore = explore_original_av([[j[0]+mf[idx][0], j[1]+mf[idx][1]] for idx, j in enumerate(na)])
firstScore = [allScore[i] for i, j in enumerate(allSegment) if j == 1]
secondScore = [allScore[i] for i, j in enumerate(allSegment) if j == 2]
thirdScore = [allScore[i] for i, j in enumerate(allSegment) if j == 3]
w_filePath = 'data/av_data/original/na+of.pkl'
with open(w_filePath, 'wb') as fp:
pickle.dump((allScore, firstScore, secondScore, thirdScore), fp, -1)
print('Processing Other Feelings')
allScore = explore_original_av(mf)
firstScore = [allScore[i] for i, j in enumerate(allSegment) if j == 1]
secondScore = [allScore[i] for i, j in enumerate(allSegment) if j == 2]
thirdScore = [allScore[i] for i, j in enumerate(allSegment) if j == 3]
w_filePath = 'data/av_data/original/of.pkl'
with open(w_filePath, 'wb') as fp:
pickle.dump((allScore, firstScore, secondScore, thirdScore), fp, -1)
def word2vector(model, mode, name):
if mode == 'char':
vocab = set(''.join(data2chn.values())+' '.join(allOtherFeelings+['。', ';']))
elif mode == 'mix':
import jieba
jieba.initialize()
def pre_tokenize(text):
return [
w.replace(' ', u'\u2582').replace('\n', u'\u2583').replace(',', ',')
for w in jieba.cut(text, cut_all=False)
]
vocab = set(sum([pre_tokenize(i) for i in data2chn.values()], [])+sum([pre_tokenize(i) for i in allOtherFeelings], [])+['。', ';'])
word2index = {w: i for i, w in enumerate(vocab)}
index2word = {i: w for w, i in word2index.items()}
SEED = 0
if model == 'word':
n_symbols = 1292607
filePath = './PLMs/sgns/word.txt'
DIM = 300
elif model == 'word+ngram':
n_symbols = 1285531
filePath = './PLMs/sgns/word+ngram.txt'
DIM = 300
elif model == 'word+char':
n_symbols = 1292679
filePath = './PLMs/sgns/word+char.txt'
DIM = 300
elif model == 'word+char+ngram':
n_symbols = 1348468
filePath = './PLMs/sgns/word+char+ngram.txt'
DIM = 300
elif model == 'v010-d200':
n_symbols = 8824330
filePath = './PLMs/tencent/v010-d200.txt'
DIM = 200
elif model == 'v020-d200-small':
n_symbols = 2000000
filePath = './PLMs/tencent/v020-d200-small.txt'
DIM = 200
elif model == 'v020-d200-large':
n_symbols = 12287936
filePath = './PLMs/tencent/v020-d200-large.txt'
DIM = 200
elif model == 'v020-d100-small':
n_symbols = 2000000
filePath = './PLMs/tencent/v020-d100-small.txt'
DIM = 100
elif model == 'v020-d100-large':
n_symbols = 12287936
filePath = './PLMs/tencent/v020-d100-large.txt'
DIM = 100
elif 'tw_' or 'cw_' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if model == 'tw_word':
n_symbols = 636013
elif model == 'tw_ngram_1':
n_symbols = 636025
elif model == 'tw_ngram_2':
n_symbols = 628667
elif model == 'tw_ngram_3':
n_symbols = 6969164
elif 'tw_char' in model:
n_symbols = 636086
elif model == 'tw_position_1':
n_symbols = 636006
elif model == 'tw_position_2':
n_symbols = 636086
elif model == 'cw_word':
n_symbols = 636000
elif model == 'cw_ngram_1':
n_symbols = 6967693
elif model == 'cw_ngram_2':
n_symbols = 13589304
elif model == 'cw_ngram_3':
n_symbols = 6969093
elif model == 'cw_char_1':
n_symbols = 636248
elif model == 'cw_char_2':
n_symbols = 792679
elif model == 'cw_char_3':
n_symbols = 1117509
elif model == 'cw_position_1':
n_symbols = 1271139
elif model == 'cw_position_2':
n_symbols = 6294532
if 'baidu' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 636013
elif 'word+ngram_' in model:
n_symbols = 636025
elif 'word+char_' in model:
n_symbols = 636086
elif 'word+char+ngram_' in model:
n_symbols = 635974
if 'wiki' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 352217
elif 'word+ngram_' in model:
n_symbols = 352217
elif 'word+char_' in model:
n_symbols = 352221
elif 'word+char+ngram_' in model:
n_symbols = 352272
if 'renmin' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 355987
elif 'word+ngram_' in model:
n_symbols = 355989
elif 'word+char_' in model:
n_symbols = 355996
elif 'word+char+ngram_' in model:
n_symbols = 356053
if 'sogou' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 364990
elif 'word+ngram_' in model:
n_symbols = 364992
elif 'word+char_' in model:
n_symbols = 365076
elif 'word+char+ngram_' in model:
n_symbols = 365113
if 'financial' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 467370
elif 'word+ngram_' in model:
n_symbols = 467377
elif 'word+char_' in model:
n_symbols = 467389
elif 'word+char+ngram_' in model:
n_symbols = 467210
if 'zhihu' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 259922
elif 'word+ngram_' in model:
n_symbols = 259936
elif 'word+char_' in model:
n_symbols = 260008
elif 'word+char+ngram_' in model:
n_symbols = 259753
if 'weibo' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 195202
elif 'word+ngram_' in model:
n_symbols = 195202
elif 'word+char_' in model:
n_symbols = 195202
elif 'word+char+ngram_' in model:
n_symbols = 195197
if 'literature' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 187959
elif 'word+ngram_' in model:
n_symbols = 187960
elif 'word+char_' in model:
n_symbols = 187985
elif 'word+char+ngram_' in model:
n_symbols = 187980
if 'sikuquanshu' in model:
DIM = 300
filePath = './PLMs/sgns/' + model + '.txt'
if 'word_' in model:
n_symbols = 19527
elif 'word+ngram_' in model:
n_symbols = 19527
index_dict = {}
embedding_weights = np.empty((n_symbols, DIM))
with open(filePath, encoding='utf-8') as fp:
index = 0
for l in tqdm(fp):
l = l.strip().split(' ')
if len(l) > DIM:
word = l[0]
index_dict[word] = index
embedding_weights[index, :] = np.asarray([float(i) for i in l[1:]], dtype='float32')
index += 1
np.random.seed(SEED)
shape = (len(word2index), DIM)
scale = math.sqrt(3.0 / DIM)
w2v_embedding = np.random.uniform(low=-scale, high=scale, size=shape)
count = 0
for i in range(0, len(word2index)):
w = index2word[i]
g = index_dict.get(w)
if g is not None:
w2v_embedding[i, :] = embedding_weights[g, :]
count += 1
print('{num_tokens}-{per:.3f}% tokens in vocab found in word2vector and copied to embedding.'.format(
num_tokens=count, per=count/float(len(word2index))*100))
def embeddings(text):
r_document, r_sentence, count = [], [], 0
for t in text:
r = []
if mode == 'char':
for tt in t:
r.append((w2v_embedding[word2index[tt]]))
elif mode == 'mix':
for tt in pre_tokenize(t):
r.append((w2v_embedding[word2index[tt]]))
r_sentence.extend(r)
if count < len(text)-1:
r_sentence.append(w2v_embedding[word2index[';']])
r_document.append(np.mean(r, axis=0))
count += 1
return np.array(r_document), np.array(r_sentence)
run(embeddings, name)
def tencent_emb():
import jieba
jieba.initialize()
def pre_tokenize(text):
return [
w.replace(' ', u'\u2582').replace('\n', u'\u2583').replace(',', ',')
for w in jieba.cut(text, cut_all=False)
]
vocab = set(sum([pre_tokenize(i) for i in data2chn.values()], [])+sum([pre_tokenize(i) for i in allOtherFeelings], [])+['。', ';'])
print(vocab)
return 1
word2index = {w: i for i, w in enumerate(vocab)}
index2word = {i: w for w, i in word2index.items()}
TENCENT_DIM = 200
SEED = 0
tencent_n_symbols = 8824330
tencent_index_dict = {}
tencent_embedding_weights = np.empty((tencent_n_symbols, TENCENT_DIM))
filePath = './PLMs/Tencent_AILab_ChineseEmbedding/Tencent_AILab_ChineseEmbedding.txt'
with open(filePath, encoding='utf-8') as fp:
index = 0
for l in tqdm(fp):
l = l.strip().split(' ')
if len(l) > TENCENT_DIM:
word = l[0]
tencent_index_dict[word] = index
tencent_embedding_weights[index, :] = np.asarray([float(i) for i in l[1:]], dtype='float32')
index += 1
np.random.seed(SEED)
shape = (len(word2index), TENCENT_DIM)
scale = math.sqrt(3.0 / TENCENT_DIM)
tencent_embedding = np.random.uniform(low=-scale, high=scale, size=shape)
count = 0
for i in tqdm(range(0, len(word2index))):
w = index2word[i]
g = tencent_index_dict.get(w)
if g is not None:
tencent_embedding[i, :] = tencent_embedding_weights[g, :]
count += 1
print('{num_tokens}-{per:.3f}% tokens in vocab found in TENCENT and copied to embedding.'.format(
num_tokens=count, per=count/float(len(word2index))*100))
def embeddings(text):
r_document, r_sentence, count = [], [], 0
for t in text:
r = []
for tt in pre_tokenize(t):
r.append((tencent_embedding[word2index[tt]]))
r_sentence.extend(r)
if count < len(text)-1:
r_sentence.append(tencent_embedding[word2index[';']])
r_document.append(np.mean(r, axis=0))
count += 1
return np.array(r_document), np.array(r_sentence)
run(embeddings, '002')
def plm_pt_emb(name, number):
if 'clue/' in name:
if 'xlnet' in name:
from transformers import XLNetTokenizer, XLNetModel
tokenizer = XLNetTokenizer.from_pretrained(name)
plm = XLNetModel.from_pretrained(name)
elif 'albert' in name:
from transformers import BertTokenizer, AlbertModel
tokenizer = BertTokenizer.from_pretrained(name)
plm = AlbertModel.from_pretrained(name)
else:
from transformers import BertTokenizer, BertModel
tokenizer = BertTokenizer.from_pretrained(name)
plm = BertModel.from_pretrained(name)
elif 'hfl/' in name:
if 'mrc' in name:
from transformers import BertTokenizer, BertForQuestionAnswering
tokenizer = BertTokenizer.from_pretrained(name)
plm = BertForQuestionAnswering.from_pretrained(name)
elif 'cino' in name:
from transformers import XLMRobertaTokenizer, XLMRobertaModel
tokenizer = XLMRobertaTokenizer.from_pretrained(name)
plm = XLMRobertaModel.from_pretrained(name)
elif 'electra' or 'xlnet' in name:
from transformers import AutoTokenizer, AutoModel