In [3]:
'''
MIT License
Copyright (c) 2016 Parvez Ahammad, Qingzhu (Clark) Gao, Prasenjit Dey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this dataset, associated software, documentation files and analysis scripts (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.
'''
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
from scipy.stats import chi2_contingency
from matplotlib import pyplot as plt
import seaborn as sns
import matplotlib as mpl
sns.set(style="whitegrid", color_codes=True)
def pick_one(l1, l2):
result = []
pick = (l1-l2)/((l1+l2)/2.)*100
for i in pick:
if i > 5:
result.append(2)
elif i < -5:
result.append(1)
else:
result.append(0)
return result
def cramers_stat(confusion_matrix):
chi2 = chi2_contingency(confusion_matrix)[0]
n = confusion_matrix.sum()
return np.sqrt(chi2 / (n*(min(confusion_matrix.shape)-1)))
def short_name(s):
return s[:s.find('_')]
def entropy(labels):
n_labels = len(labels)
if n_labels <= 1:
return 0
unique_value = pd.Series(labels).unique()
unique_value.sort()
counts = [labels.count(x) for x in unique_value]
probs = np.array(counts) / float(n_labels)
ent = 0.
# Compute standard entropy.
for i in probs:
ent -= i * np.log(i)
return ent
def entropy_cont_var(labels):
n_labels = len(labels)
if n_labels <= 1:
return 0
out = pd.cut(labels, bins = 100)
counts = pd.value_counts(out).reindex(out.categories)
bin_width = max(labels) - min(labels)/100.0
probs = np.array(counts) / float(n_labels)
# print probs
ent = 0
for p in probs:
if p > 0:
ent -= p * np.log(p)
return ent + np.log(bin_width)
def plot_bar(a_list, title, ylabel, xlabel):
fig = plt.figure(figsize=(12,6))
d_tmp = pd.DataFrame({'Perf_Metric':[x[0] for x in a_list], 'Percentage':[x[1] for x in a_list]})
plt.title(title, size=20)
ax = sns.barplot(x='Perf_Metric', y='Percentage', data=d_tmp, palette="Greens_d")
for p in ax.patches:
height = p.get_height()
if height < 1:
ax.text(p.get_x()+0.1, height+0.01, '%1.2f'%(height))
else:
ax.text(p.get_x()+0.2, height+0.5, '%d'%(height))
# print a_list[0]
if a_list[0][1] > 1:
ax.set(xlabel=xlabel, ylabel=ylabel)
else:
ax.set(xlabel=xlabel, ylabel=ylabel, ylim=(0,1))
plt.xticks(rotation=30)
# return fig
def percentage_match(dd, target):
if target=='Population':
t = 'vote'
else:
t = 'majority_pick'
match_perc = []
for col in dd.columns.tolist()[2:]:
if col == 'majority_pick' and t == 'majority_pick':
pass
else:
# print '%.4f%% result matches %s'%(len(dd.loc[(dd[t]==dd[col])])/float(len(dd)), col[:-5])
perc = len(dd.loc[(dd[t]==dd[col])])/float(len(dd))
name = col[:-5]
match_perc.append((name, perc))
a_list = sorted(match_perc, key=lambda x: x[1])
plot_bar(a_list, 'User Perception Match %s'%target, 'Match Fraction', 'Performance Indicator')
def chiSquare_association(dd, target):
if target=='Population':
t = 'vote'
else:
t = 'majority_pick'
y_true = d_cat[t]
chi = []
for key in d_cat.keys():
if key == t or key == 'visualComplete_pick' or key == 'pairID' or key == 'vote':
pass
else:
y_pred = d_cat[key]
cm = confusion_matrix(y_true, y_pred)
cramers_v = cramers_stat(cm)
chi.append((key, cramers_v))
# print '%s: %.2f'%(key, cramers_v)
b_list = sorted(chi, key=lambda x: x[1])
plot_bar(b_list, 'Chi-squre based Association with %s Perception'%target, "Cramer's V score", 'Performance Indicator')
In [ ]:
In [ ]: