forked from microsoft/temporal-cluster-matching
-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithms.py
191 lines (149 loc) · 8.26 KB
/
algorithms.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
'''
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
'''
import numpy as np
import scipy.stats
from sklearn.cluster import KMeans, MiniBatchKMeans
from sklearn.preprocessing import StandardScaler
from skimage.feature import local_binary_pattern
from skimage.color import rgb2gray
def calculate_change_values(index, years, images, masks, n_clusters, num_samples_for_kmeans=10000, use_minibatch=False):
'''
Args:
imagery: A list of `numpy.ndarray` of shape (height, width, n_channels). This imagery should cover an area that is larger than the parcel of interest by some fixed distance (i.e. a buffer value).
masks: A list of boolean `numpy.ndarray` of shape (height, width) with `1` in locations where the parcel covers and `0` everywhere else.
n_clusters: The number of clusters to use in the k-means model.
num_samples_for_kmeans: An integer specifying the number of samples to use to fit the k-means model. If `None` then all pixels in the neighborhood + footprint are used, however this is probably overkill.
use_minibatch: A flag that indicates whether we should use MiniBatchKMeans over KMeans. MiniBatchKMeans should be much faster.
Returns:
divergences: A list of KL-divergence values
'''
divergences = []
for image, mask, year in zip(images, masks, years):
if mask.shape[0] > image.shape[0]:
mask = mask[:image.shape[0], :]
elif mask.shape[0] < image.shape[0]:
image = image[:mask.shape[0], :, :]
if mask.shape[1] > image.shape[1]:
mask = mask[:, :image.shape[1]]
elif mask.shape[1] < image.shape[1]:
image = image[:, :mask.shape[1], :]
h, w, c = image.shape
if mask.shape[0] != h or mask.shape[1] != w:
print(index)
for i, m, y in zip(images, masks, years):
h1, w1, c1 = i.shape
print("Year: {}".format(y))
print("Width: image {} mask {}".format(w1, m.shape[1]))
print("Width: image {} mask {}".format(h1, m.shape[0]))
assert mask.shape[0] == h and mask.shape[1] == w
mask = mask.astype(bool)
# fit a k-means model and use it to cluster the image
if use_minibatch:
cluster_model = MiniBatchKMeans(n_clusters=n_clusters, n_init=3, batch_size=2000, compute_labels=True, init="random")
else:
cluster_model = KMeans(n_clusters=n_clusters, n_init=3)
features = image.reshape(h*w, c)
scaler = StandardScaler()
features = scaler.fit_transform(features)
if num_samples_for_kmeans is None or (h*w <= num_samples_for_kmeans):
labels = cluster_model.fit_predict(features)
else:
cluster_model.fit(features[np.random.choice(features.shape[0], size=num_samples_for_kmeans)])
labels = cluster_model.predict(features)
labels = labels.reshape(h,w)
# select the cluster labels that fall within the parcel and those outside of the parcel
parcel_labels = labels[mask]
neighborhood_labels = labels[~mask]
# compute the frequency with which each cluster occurs in the parcel and outside of the parcel
parcel_counts = np.bincount(parcel_labels.ravel(), minlength=n_clusters)
neighborhood_counts = np.bincount(neighborhood_labels.ravel(), minlength=n_clusters)
if parcel_labels.shape[0] > 0:
# normalize each vector of cluster index counts into discrete distributions
parcel_distribution = (parcel_counts + 1e-5) / parcel_counts.sum()
neighborhood_distribution = (neighborhood_counts + 1e-5) / neighborhood_counts.sum()
# compute the KL divergence between the two distributions
divergence = scipy.stats.entropy(parcel_distribution, neighborhood_distribution)
divergences.append(divergence)
else:
divergences.append(float('inf'))
return divergences
def calculate_change_values1(index, years, images, masks, n_clusters, num_samples_for_kmeans=10000, use_minibatch=False):
'''
Args:
imagery: A list of `numpy.ndarray` of shape (height, width, n_channels). This imagery should cover an area that is larger than the parcel of interest by some fixed distance (i.e. a buffer value).
masks: A list of boolean `numpy.ndarray` of shape (height, width) with `1` in locations where the parcel covers and `0` everywhere else.
n_clusters: The number of clusters to use in the k-means model.
num_samples_for_kmeans: An integer specifying the number of samples to use to fit the k-means model. If `None` then all pixels in the neighborhood + footprint are used, however this is probably overkill.
use_minibatch: A flag that indicates whether we should use MiniBatchKMeans over KMeans. MiniBatchKMeans should be much faster.
Returns:
divergences: A list of KL-divergence values
'''
divergences = []
parcel_counts_list = []
for image, mask, year in zip(images, masks, years):
if mask.shape[0] > image.shape[0]:
mask = mask[:image.shape[0], :]
elif mask.shape[0] < image.shape[0]:
image = image[:mask.shape[0], :, :]
if mask.shape[1] > image.shape[1]:
mask = mask[:, :image.shape[1]]
elif mask.shape[1] < image.shape[1]:
image = image[:, :mask.shape[1], :]
h, w, c = image.shape
if mask.shape[0] != h or mask.shape[1] != w:
print(index)
for i, m, y in zip(images, masks, years):
h1, w1, c1 = i.shape
print("Year: {}".format(y))
print("Width: image {} mask {}".format(w1, m.shape[1]))
print("Width: image {} mask {}".format(h1, m.shape[0]))
assert mask.shape[0] == h and mask.shape[1] == w
mask = mask.astype(bool)
# fit a k-means model and use it to cluster the image
if use_minibatch:
cluster_model = MiniBatchKMeans(n_clusters=n_clusters, n_init=3, batch_size=2000, compute_labels=True, init="random")
else:
cluster_model = KMeans(n_clusters=n_clusters, n_init=3)
features = image.reshape(h*w, c)
scaler = StandardScaler()
features = scaler.fit_transform(features)
if num_samples_for_kmeans is None or (h*w <= num_samples_for_kmeans):
labels = cluster_model.fit_predict(features)
else:
cluster_model.fit(features[np.random.choice(features.shape[0], size=num_samples_for_kmeans)])
labels = cluster_model.predict(features)
labels = labels.reshape(h,w)
# select the cluster labels that fall within the parcel and those outside of the parcel
parcel_labels = labels[mask]
# compute the frequency with which each cluster occurs in the parcel and outside of the parcel
parcel_counts = np.bincount(parcel_labels.ravel(), minlength=n_clusters)
parcel_counts_list.append(parcel_counts)
for i in range(len(parcel_counts_list)-1):
prev_year = parcel_counts_list[i]
next_year = parcel_counts_list[i+1]
prev_distribution = (prev_year + 1e-5) / prev_year.sum()
next_distribution = (next_year + 1e-5) / next_year.sum()
# compute the KL divergence between the two distributions
divergence = scipy.stats.entropy(prev_distribution, next_distribution)
divergences.append(divergence)
return divergences
def calculate_change_values_with_color(images, masks):
'''
Args:
imagery: A list of `numpy.ndarray` of shape (height, width, n_channels). This imagery should cover an area that is larger than the parcel of interest by some fixed distance (i.e. a buffer value).
masks: A list of boolean `numpy.ndarray` of shape (height, width) with `1` in locations where the parcel covers and `0` everywhere else.
Returns:
distances: A list of Euclidean distances
'''
distances = []
for image, mask in zip(images, masks):
h,w,c = image.shape
assert mask.shape[0] == h and mask.shape[1] == w
colors_inside = image[mask==1].mean(axis=0)
colors_outside = image[mask==0].mean(axis=0)
distances.append(np.linalg.norm(
colors_outside - colors_inside
))
return distances