-
Notifications
You must be signed in to change notification settings - Fork 0
/
draft.py
142 lines (122 loc) · 4.34 KB
/
draft.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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import make_moons, make_blobs
from sklearn import svm
from sklearn.covariance import EllipticEnvelope
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
import time
import rrcf
rng = np.random.RandomState(42)
# Example settings
n_samples = 300
outliers_fraction = 0.15
n_outliers = int(outliers_fraction * n_samples)
n_inliers = n_samples - n_outliers
# Outlier detectors from sklean plot
anomaly_algorithms = [
("Robust covariance",
EllipticEnvelope(contamination=outliers_fraction)),
("One-Class SVM",
svm.OneClassSVM(nu=outliers_fraction,
kernel="rbf",
gamma=0.1)),
("Isolation Forest",
IsolationForest(contamination=outliers_fraction,)),
("Local Outlier Factor",
LocalOutlierFactor(n_neighbors=17, algorithm='brute', #'ball_tree', 'kd_tree', 'brute'
contamination=outliers_fraction))]
# Define datasets
blobs_params = dict(random_state=0,
n_samples=n_inliers,
n_features=2)
datasets = [
make_blobs(centers=[[0, 0], [0, 0]],
cluster_std=0.5,**blobs_params)[0],
make_blobs(centers=[[2, 2], [-2, -2]],
cluster_std=[0.5, 0.5],**blobs_params)[0],
make_blobs(centers=[[2, 2], [-2, -2]],
cluster_std=[1.5, .3],**blobs_params)[0],
4. * (make_moons(n_samples=n_samples,
noise=.05, random_state=0)[0]
- np.array([0.5, 0.25])),
14. * (np.random.RandomState(42).rand(n_samples, 2)
- 0.5)]
# Add outliers to the data sets
outliers = [] # record keeping
data = []
for i in datasets:
out = rng.uniform(low=-6, high=6,
size=(n_outliers, 2))
outliers.append(out)
data.append(np.concatenate([i, out], axis=0))
# Set forest params
avg_codisp = []
num_trees = 100
tree_size = 256
plot_num = 1
fig = plt.figure(1, figsize=(12, 12))
for d in range(len(data)):
forest = []
n = len(data[d])
tr1 = time.time()
while len(forest) < num_trees:
# Select random subsets of points uniformly from point set
ixs = np.random.choice(n,
size=(n // tree_size, tree_size),
replace=False)
# Add sampled trees to forest
trees = [rrcf.RCTree(data[d][ix],
index_labels=ix) for ix in ixs]
forest.extend(trees)
# Compute average CoDisp
avg_codisp_d = pd.Series(0.0, index=np.arange(n))
index = np.zeros(n)
for tree in forest:
codisp = pd.Series({leaf : tree.codisp(leaf)
for leaf in tree.leaves})
avg_codisp_d[codisp.index] += codisp
np.add.at(index, codisp.index.values, 1)
avg_codisp_d /= index
avg_codisp.append(avg_codisp_d)
tr2 = time.time()
for name, algorithm in anomaly_algorithms:
t0 = time.time()
algorithm.fit(data[d])
t1 = time.time()
plt.subplot(5, len(anomaly_algorithms) + 1,
plot_num)
if d == 0:
plt.title(name, size=16)
# fit the data and tag outliers
if name == "Local Outlier Factor":
y_pred = algorithm.fit_predict(data[d])
else:
y_pred = (algorithm.fit(data[d])
.predict(data[d]))
colors = np.array(['#377eb8', '#ff7f00'])
plt.scatter(data[d][:, 0], data[d][:, 1], s=1,
color=colors[(y_pred + 1) // 2])
plt.text(.99, .01,
('%.2fs' % (t1 - t0)).lstrip('0'),
transform=plt.gca().transAxes, size=15,
horizontalalignment='right')
plot_num += 1
plt.subplot(5, len(anomaly_algorithms) + 1, plot_num)
avg_cod = avg_codisp[-1]
mask = np.percentile(avg_cod, 85)
avg_cod[avg_cod < mask] = 1
avg_cod[avg_cod > mask] = 0
c = ['#377eb8' if i == 0 else '#ff7f00'
for i in avg_cod]
plt.scatter(data[d][:,0], data[d][:,1], s=1, c=c)
if d == 0:
plt.title("RRCF", size=16)
plt.text(.99, .01,
('%.2fs' % (tr2 - tr1)).lstrip('0'),
transform=plt.gca().transAxes, size=15,
horizontalalignment='right')
plot_num += 1
plt.show()