-
Notifications
You must be signed in to change notification settings - Fork 6
/
baselines.py
204 lines (176 loc) · 6.24 KB
/
baselines.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import torch
import numpy as np
from itertools import permutations
from sklearn import linear_model
from YahooDataReader import YahooDataReader
from models import NNModel, LinearModel
from evaluation import evaluate_model
import scipy
vvector = lambda N: 1. / np.log2(2 + np.arange(N))
def get_best_rankmatrix(true_rel_vector):
N = len(true_rel_vector)
bestranking = np.zeros((N, N))
bestr = np.argsort(true_rel_vector)[::-1]
for i in range(N):
bestranking[bestr[i], i] = 1
return bestranking
#returns DCG value
def get_DCG(ranking, relevances, vvector):
N = len(relevances)
return np.matmul(np.matmul(relevances, ranking), vvector.transpose())
def get_ndcg(ranking, relevances, vvector):
if np.all(relevances == 0):
return 1.0
bestr = get_best_rankmatrix(relevances)
return get_DCG(ranking, relevances, vvector) / get_DCG(
bestr, relevances, vvector)
def get_fairness_loss(ranking, relevances, vvector, groups):
# print(ranking, relevances, vvector, groups)
if np.all(groups == 0) or np.all(groups == 1):
return 0.0
avg_rels = [np.mean(relevances[groups == i]) for i in range(2)]
if avg_rels[0] == 0 or avg_rels[1] == 0:
return 0.0
sign = +1 if avg_rels[0] >= avg_rels[1] else -1
exposures = np.matmul(ranking, vvector)
group_avg_exposures = [
np.mean(exposures[groups == 0]),
np.mean(exposures[groups == 1])
]
#print(avg_rels, sign, exposures, group_avg_exposures)
loss = max([
0.0, sign * (group_avg_exposures[0] / avg_rels[0] -
group_avg_exposures[1] / avg_rels[1])
])
return loss
def get_avg_fairness_loss(dr, predicted_rels, vvector, lmbda, args):
feats, rel = dr.data
test_losses = []
for i in range(len(rel)):
N = len(rel[i])
pred_rels = predicted_rels[i]
groups = np.array(feats[i][:, args.group_feat_id], dtype=np.int)
P, _, _ = fair_rank(pred_rels, groups, lmbda)
test_loss = get_fairness_loss(P, rel[i], vvector[:N], groups)
test_losses.append(test_loss)
return np.mean(test_losses)
def get_avg_ndcg_unfairness(dr, predicted_rels, vvector, lmbda,
group_feature_id):
feats, rel = dr.data
test_losses = []
test_ndcgs = []
for i in range(len(rel)):
N = len(rel[i])
pred_rels = predicted_rels[i]
groups = np.array(feats[i][:, group_feature_id], dtype=np.int)
P, _, _ = fair_rank(pred_rels, groups, lmbda)
test_ndcg = get_ndcg(P, rel[i], vvector[:N])
test_ndcgs.append(test_ndcg)
test_loss = get_fairness_loss(P, rel[i], vvector[:N], groups)
test_losses.append(test_loss)
return np.mean(test_ndcgs), np.mean(test_losses)
def assign_groups(groups):
G = [[], []]
for i in range(len(groups)):
G[groups[i]].append(i)
return G
def fair_rank(relevances, groups, lmda=1):
n = len(relevances)
pos_bias = vvector(n)
G = assign_groups(groups)
n_g, n_i = 0, 0
n_g += (len(G) - 1) * len(G)
n_c = n**2 + n_g
c = np.ones(n_c)
c[:n**2] *= -1
c[n**2:] *= lmda
A_eq = []
#For each Row
for i in range(n):
A_temp = np.zeros(n_c)
A_temp[i * n:(i + 1) * n] = 1
assert (sum(A_temp) == n)
A_eq.append(A_temp)
c[i * n:(i + 1) * n] *= relevances[i]
#For each coloumn
for i in range(n):
A_temp = np.zeros(n_c)
A_temp[i:n**2:n] = 1
assert (sum(A_temp) == n)
A_eq.append(A_temp)
#Optimization
c[i:n**2:n] *= pos_bias[i]
b_eq = np.ones(n * 2)
A_eq = np.asarray(A_eq)
bounds = [(0, 1) for _ in range(n**2)] + [(0, None)
for _ in range(n_g + n_i)]
A_ub = []
b_ub = np.zeros(n_g)
sum_rels = []
for group in G:
#Avoid devision by zero
sum_rel = np.max([np.sum(np.asarray(relevances)[group]), 0.01])
sum_rels.append(sum_rel)
comparisons = list(permutations(np.arange(len(G)), 2))
j = 0
for a, b in comparisons:
f = np.zeros(n_c)
if len(G[a]) > 0 and len(G[b]) > 0 and sum_rels[a] / len(
G[a]) >= sum_rels[b] / len(G[b]):
for i in range(n):
tmp1 = len(G[a]) / sum_rels[a] if i in G[a] else 0
tmp2 = len(G[b]) / sum_rels[b] if i in G[b] else 0
#f[i*n:(i+1)*n] *= max(0, sign*(tmp1 - tmp2))
f[i * n:(i + 1) * n] = (tmp1 - tmp2)
for i in range(n):
f[i:n**2:n] *= pos_bias[i]
f[n**2 + j] = -1
j += 1
A_ub.append(f)
res = scipy.optimize.linprog(
c,
A_eq=A_eq,
b_eq=b_eq,
A_ub=A_ub,
b_ub=b_ub,
bounds=bounds,
method="interior-point") #, options=dict(tol=1e-12),)
if res.success is False:
print("Constraint not satisfied!!")
probabilistic_ranking = np.reshape(res.x[:n**2], (n, n))
return probabilistic_ranking, res, res.fun
def learn_and_predict(dr, vdr, intercept=True):
# Linear regression
print("Training linear regression on data with {} queries".format(
len(dr.data[1])))
model = linear_model.LinearRegression(
fit_intercept=intercept, normalize=False)
feats, rel = dr.data
feats = np.array([item for sublist in feats for item in sublist])
rel = np.array([item for sublist in rel for item in sublist])
model.fit(feats, rel)
# predictions on validation
feats, rel = vdr.data
se_sum = 0
length = 0
predicted_rels = []
for i, query in enumerate(feats):
rel_pred = model.predict(query[:, :])
predicted_rels.append(rel_pred)
se_sum += np.sum((rel_pred - rel[i])**2)
length += len(rel[i])
print("MSE : {}".format(se_sum / length))
return predicted_rels, model
def eval_params(w, bias, dr, D, det=False, args=None, intercept=True):
# Given the model weights, this function evaluates the model
model = LinearModel(D=D)
model.w.weight.data = torch.FloatTensor([w])
if intercept:
model.w.bias.data = torch.FloatTensor([bias])
return evaluate_model(
model,
dr,
deterministic=det,
group_fairness_evaluation=True,
args=args,
fairness_evaluation=True)