-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpecNorm.py
46 lines (40 loc) · 1.02 KB
/
SpecNorm.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 21 11:15:11 2022
@author: kwesi
"""
import numpy as np
def computeSVD(embed):
"""
Args:
emded: Monolingual Embedding
Returns:
Singular Value Decomposition
"""
U, S, VT = np.linalg.svd(embed,full_matrices=False)
return U, S, VT
def specNorm(embed, beta):
"""
Args:
emded: Monolingual Embedding
beta: Use to determine smaller (noisy)
singular values to be removed
Returns:
Spectral Normalized Embedding
"""
# Perform SVD on the Data
_, S, VT = computeSVD(embed)
# Compute eta
eta = np.sqrt(np.sum(S**2)/len(S))
# Transform diagonal matrix
S_prime = 1 / S
for idx, sigma in enumerate(S):
if sigma > beta*eta:
S_prime[idx] = S_prime[idx] * (beta*eta)
else:
S_prime[idx] = 1
S_prime = np.eye(len(S)) * S_prime
# Compute new monolingual embedding
embed = embed @ VT.T @ S_prime
return embed