Skip to content

Instantly share code, notes, and snippets.

@xoraus
Created August 22, 2019 12:48
Show Gist options
  • Save xoraus/a14b262dd3776c72b8d66c286da273c9 to your computer and use it in GitHub Desktop.
Save xoraus/a14b262dd3776c72b8d66c286da273c9 to your computer and use it in GitHub Desktop.
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]
@mxa256
Copy link

mxa256 commented Feb 12, 2022

When I try to run this, it says "actual labels is not defined"

@mxa256
Copy link

mxa256 commented Feb 12, 2022

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