Last active
February 16, 2023 06:49
-
-
Save jhumigas/010473a456462106a3720ca953b2c4e2 to your computer and use it in GitHub Desktop.
purity.py
This file contains hidden or 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
""" | |
The MIT License (MIT) | |
Copyright (c) 2017 David Mugisha | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
""" | |
Computation of purity score with sklearn. | |
""" | |
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from sklearn.metrics import accuracy_score | |
import numpy as np | |
def purity_score(y_true, y_pred): | |
"""Purity score | |
To compute purity, each cluster is assigned to the class which is most frequent | |
in the cluster [1], and then the accuracy of this assignment is measured by counting | |
the number of correctly assigned documents and dividing by the number of documents. | |
We suppose here that the ground truth labels are integers, the same with the predicted clusters i.e | |
the clusters index. | |
Args: | |
y_true(np.ndarray): n*1 matrix Ground truth labels | |
y_pred(np.ndarray): n*1 matrix Predicted clusters | |
Returns: | |
float: Purity score | |
References: | |
[1] https://nlp.stanford.edu/IR-book/html/htmledition/evaluation-of-clustering-1.html | |
""" | |
# matrix which will hold the majority-voted labels | |
y_voted_labels = np.zeros(y_true.shape) | |
# Ordering labels | |
## Labels might be missing e.g with set like 0,2 where 1 is missing | |
## First find the unique labels, then map the labels to an ordered set | |
## 0,2 should become 0,1 | |
labels = np.unique(y_true) | |
ordered_labels = np.arange(labels.shape[0]) | |
for k in range(labels.shape[0]): | |
y_true[y_true==labels[k]] = ordered_labels[k] | |
# Update unique labels | |
labels = np.unique(y_true) | |
# We set the number of bins to be n_classes+2 so that | |
# we count the actual occurence of classes between two consecutive bin | |
# the bigger being excluded [bin_i, bin_i+1[ | |
bins = np.concatenate((labels, [np.max(labels)+1]), axis=0) | |
for cluster in np.unique(y_pred): | |
hist, _ = np.histogram(y_true[y_pred==cluster], bins=bins) | |
# Find the most present label in the cluster | |
winner = np.argmax(hist) | |
y_voted_labels[y_pred==cluster] = winner | |
return accuracy_score(y_true, y_voted_labels) |
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import numpy as np | |
from purity import purity_score | |
y_true = np.random.randint(1,6, size=(20,1)) | |
y_pred = np.random.randint(5, size=(20,1)) | |
purity_score(y_true, y_pred) | |
Hi @ahmedhumza94, sorry for the delay. I have just seen your comment. Thank you for your feedback, have you found a to make the function better ?
I will see if I can find a workaround.
EDIT:
I have updated the function to take into account the flaws you pointed out
I tested it and it works fine now.
Here is a simpler implementation if you are interested.
@ugurite I am indeed, it is simpler and concise! Thank you, it is even better as it uses scikit-learn own functions!
I can add it to the gist, as a python file, referring to your answer with your name, as it is way better, of course if you allow me too :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After testing this for a bit, it seems that the purity score works correctly only when: