| 121 | |
| 122 | ### calculate the purity of our clusters ### |
| 123 | def purity(true_labels, cluster_assignments, categories): |
| 124 | # maximum purity is 1, higher is better |
| 125 | N = len(true_labels) |
| 126 | |
| 127 | total = 0.0 |
| 128 | for k in categories: |
| 129 | max_intersection = 0 |
| 130 | for j in categories: |
| 131 | intersection = ((cluster_assignments == k) & (true_labels == j)).sum() |
| 132 | if intersection > max_intersection: |
| 133 | max_intersection = intersection |
| 134 | total += max_intersection |
| 135 | return total / N |
| 136 | |
| 137 | print("purity:", purity(Y, C, categories)) |
| 138 | |