Created
August 22, 2019 12:48
-
-
Save xoraus/a14b262dd3776c72b8d66c286da273c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def infer_cluster_labels(kmeans, actual_labels): | |
inferred_labels = {} | |
for i in range(kmeans.n_clusters): | |
# find index of points in cluster | |
labels = [] | |
index = np.where(kmeans.labels_ == i) | |
# append actual labels for each point in cluster | |
labels.append(actual_labels[index]) | |
# determine most common label | |
if len(labels[0]) == 1: | |
counts = np.bincount(labels[0]) | |
else: | |
counts = np.bincount(np.squeeze(labels)) | |
# assign the cluster to a value in the inferred_labels dictionary | |
if np.argmax(counts) in inferred_labels: | |
# append the new number to the existing array at this slot | |
inferred_labels[np.argmax(counts)].append(i) | |
else: | |
# create a new array in this slot | |
inferred_labels[np.argmax(counts)] = [i] | |
#print(labels) | |
#print('Cluster: {}, label: {}'.format(i, np.argmax(counts))) | |
return inferred_labels | |
def infer_data_labels(X_labels, cluster_labels): | |
# empty array of len(X) | |
predicted_labels = np.zeros(len(X_labels)).astype(np.uint8) | |
for i, cluster in enumerate(X_labels): | |
for key, value in cluster_labels.items(): | |
if cluster in value: | |
predicted_labels[i] = key | |
return predicted_labels | |
# test the infer_cluster_labels() and infer_data_labels() functions | |
cluster_labels = infer_cluster_labels(kmeans, Y) | |
X_clusters = kmeans.predict(X) | |
predicted_labels = infer_data_labels(X_clusters, cluster_labels) | |
print predicted_labels[:20] | |
print Y[:20] | |
Thanks--When I try to run the function "infer_cluster_labels" to test it out on line 45, I get the following error: "KeyError: 'key of type tuple not found and not a MultiIndex'"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mxa256 Refer this -> https://github.com/xoraus/K-Means-Clustering-for-Imagery-Analysis/blob/master/KMeans%20Clustering%20for%20Imagery%20Analysis%20(Jupyter%20Notebook).ipynb