-
Notifications
You must be signed in to change notification settings - Fork 0
/
purity.py
89 lines (72 loc) · 3.38 KB
/
purity.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
"""
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)
if __name__ == "__main__":
import pandas as pd
answer_df = pd.read_csv('Stars Clustering/Stars_original.csv')
groundtruth_df = pd.read_csv('Stars Clustering/Stars_original.csv')
y_pred = answer_df['Type'].to_numpy()
y_true = groundtruth_df['Type'].to_numpy()
y_pred = np.where(y_pred==3, 8, y_pred)
print(np.unique(y_pred))
print(purity_score(y_true, y_pred))