def adjusted_rand_score(labels_true, labels_pred):
 (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred)
 n_samples = labels_true.shape[0]
 n_classes = np.unique(labels_true).shape[0]
 n_clusters = np.unique(labels_pred).shape[0]
 if ((n_classes == n_clusters == 1) or (n_classes == n_clusters == 0) or (n_classes == n_clusters == n_samples)):
  return 1.0
 contingency = contingency_matrix(labels_true, labels_pred, sparse=True)
 sum_comb_c = sum((comb2(n_c) for n_c in np.ravel(contingency.sum(axis=1))))
 sum_comb_k = sum((comb2(n_k) for n_k in np.ravel(contingency.sum(axis=0))))
 sum_comb = sum((comb2(n_ij) for n_ij in contingency.data))
 prod_comb = ((sum_comb_c * sum_comb_k) / comb(n_samples, 2))
 mean_comb = ((sum_comb_k + sum_comb_c) / 2.0)
 return ((sum_comb - prod_comb) / (mean_comb - prod_comb))

def adjusted_rand_score ( labels_true , labels_pred ) : ( labels_true , labels_pred ) = check_clusterings ( labels_true , labels_pred ) n_samples = labels_true . shape [ 0 ] n_classes = np . unique ( labels_true ) . shape [ 0 ] n_clusters = np . unique ( labels_pred ) . shape [ 0 ] if ( ( n_classes == n_clusters == 1 ) or ( n_classes == n_clusters == 0 ) or ( n_classes == n_clusters == n_samples ) ) : return 1.0 contingency = contingency_matrix ( labels_true , labels_pred , sparse = True ) sum_comb_c = sum ( ( comb2 ( n_c ) for n_c in np . ravel ( contingency . sum ( axis = 1 ) ) ) ) sum_comb_k = sum ( ( comb2 ( n_k ) for n_k in np . ravel ( contingency . sum ( axis = 0 ) ) ) ) sum_comb = sum ( ( comb2 ( n_ij ) for n_ij in contingency . data ) ) prod_comb = ( ( sum_comb_c * sum_comb_k ) / comb ( n_samples , 2 ) ) mean_comb = ( ( sum_comb_k + sum_comb_c ) / 2.0 ) return ( ( sum_comb - prod_comb ) / ( mean_comb - prod_comb ) )
rand index adjusted for chance .