-
Notifications
You must be signed in to change notification settings - Fork 0
/
circles.py
70 lines (58 loc) · 2.32 KB
/
circles.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
import logging
import time
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_circles
from sklearn.metrics import accuracy_score
from measure_propagation import similarity
from measure_propagation.graph import KNNGraph
from measure_propagation.wrapper import MeasurePropagationSklearn
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
# generate ring with inner box
n_samples = 200
X, y = make_circles(n_samples=n_samples, shuffle=False)
# create labels
outer, inner = 0, 1
labels = -np.ones(n_samples, dtype=np.int32) # -1 is set for unlabeled data points
labels[0] = outer
labels[-1] = inner
# create a nearest neighbor graph
K = 4
graph = KNNGraph(K, similarity.euclidean_similarity).build(X)
# create measure propagation
mp = MeasurePropagationSklearn(mu=0.1,
nu=0.01,
tol=2e-2,
max_iter=100)
# run algorithm
start = time.time()
mp.fit(graph, labels)
end = time.time()
logging.debug(end - start)
logger.debug(mp.q)
output_labels = mp.predict()
logging.debug("Accuracy %f" % accuracy_score(y, output_labels))
# visualize results
plt.figure(figsize=(8.5, 4))
plt.subplot(1, 2, 1)
plt.scatter(X[labels == outer, 0], X[labels == outer, 1], color='navy',
marker='s', lw=0, label="outer labeled", s=10)
plt.scatter(X[labels == inner, 0], X[labels == inner, 1], color='c',
marker='s', lw=0, label='inner labeled', s=10)
plt.scatter(X[labels == -1, 0], X[labels == -1, 1], color='darkorange',
marker='.', label='unlabeled')
plt.legend(scatterpoints=1, shadow=False, loc='upper right')
plt.title("Raw data (2 classes=outer and inner)")
plt.subplot(1, 2, 2)
output_label_array = np.asarray(output_labels)
outer_numbers = np.where(output_label_array == outer)[0]
inner_numbers = np.where(output_label_array == inner)[0]
plt.scatter(X[outer_numbers, 0], X[outer_numbers, 1], color='navy',
marker='s', lw=0, s=10, label="outer learned")
plt.scatter(X[inner_numbers, 0], X[inner_numbers, 1], color='c',
marker='s', lw=0, s=10, label="inner learned")
plt.legend(scatterpoints=1, shadow=False, loc='upper right')
plt.title("Labels learned with Measure Propagation (%d-NN)" % K)
plt.subplots_adjust(left=0.07, bottom=0.07, right=0.93, top=0.92)
plt.show()