-
Notifications
You must be signed in to change notification settings - Fork 20
/
outlier_detection_sd.py
72 lines (64 loc) · 2.35 KB
/
outlier_detection_sd.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
from sklearn.feature_extraction.text import TfidfVectorizer
from compute_util import compute_sim_matrix
from compute_util import compute_mean_sd
from compute_util import compute_row_sim_I
def detect_outlier_sd_txt_tfidf(txts, percentoutlier):
vectorizer = TfidfVectorizer(max_df=1.0, min_df=1, stop_words='english', use_idf=True, smooth_idf=True, norm='l2')
txtVecs = vectorizer.fit_transform(txts)
outlierLabels = detect_outlier_sd_vec(txtVecs.toarray(), percentoutlier)
return outlierLabels
def detect_outlier_sd_vec(txtVecs, percentoutlier):
rows = len(txtVecs)
outlierLabels = [1 for i in range(rows)]
#simMatrix = compute_sim_matrix(txtVecs)
mostSimLists= {}
for i in range(rows):
rowSimsToI = compute_row_sim_I(txtVecs[i], txtVecs)
meanVal,sdVal = compute_mean_sd(rowSimsToI)
for j in range(len(rowSimsToI)):
if i!=j and rowSimsToI[j] > meanVal + sdVal:
#mostSimLists[j].append(i)
if j in mostSimLists:
mostSimLists[j]= mostSimLists[j]+1
else:
mostSimLists[j]=1
numOutliers = int(percentoutlier*rows)
items = [(v, k) for k, v in mostSimLists.items()]
items.sort()
items.reverse()
sortedKeys = [k for v, k in items] #key is index of a text
#print(mostSimLists)
#print(sortedKeys)
#print(rows, numOutliers)
sortedKeys = sortedKeys[rows-numOutliers: rows] #outliers index
for outlierInd in sortedKeys:
outlierLabels[outlierInd]=-1
#print("SD based outliers="+str(outlierLabels))
return outlierLabels
"""def detect_outlier_sd_vec(txtVecs, percentoutlier): #working
rows = len(txtVecs)
outlierLabels = [1 for i in range(rows)]
simMatrix = compute_sim_matrix(txtVecs)
mostSimLists= {}
for i in range(len(simMatrix)):
meanVal,sdVal = compute_mean_sd(simMatrix[i])
for j in range(len(simMatrix[i])):
if i!=j and simMatrix[i][j] > meanVal + sdVal:
#mostSimLists[j].append(i)
if j in mostSimLists:
mostSimLists[j]= mostSimLists[j]+1
else:
mostSimLists[j]=1
numOutliers = int(percentoutlier*rows)
items = [(v, k) for k, v in mostSimLists.items()]
items.sort()
items.reverse()
sortedKeys = [k for v, k in items] #key is index of a text
#print(mostSimLists)
#print(sortedKeys)
#print(rows, numOutliers)
sortedKeys = sortedKeys[rows-numOutliers: rows] #outliers index
for outlierInd in sortedKeys:
outlierLabels[outlierInd]=-1
#print("SD based outliers="+str(outlierLabels))
return outlierLabels"""