How to use group_pred method in hypothesis

Best Python code snippet using hypothesis

helpers.py

Source:helpers.py Github

copy

Full Screen

1import numpy as np2import cvxpy as cp3from sys import argv4import os5from scipy import stats6from scipy.special import softmax7from sklearn.preprocessing import normalize8# generate a numpy matrix of size \R num_samples * m, dist can be "uniform" or "normal"9def generate_data(n_s, m, dist, normalized=False):10 if (dist == 'uniform'):11 X = np.random.uniform(low=0.0, high=1.0, size=(n_s, m))12 elif(dist == 'normal'):13 X = stats.truncnorm.rvs(-1.0, 1.0, 0.0, 1.0, size=(n_s, m))14 15 if normalized:16 norm_X = normalize(X, axis=1, norm='l1') 17 return norm_X18 else:19 return X20# generate matrix L of size d x m according to distribution dist21def generate_loss_matrix(d, m, dist):22 if (dist == 'uniform'):23 L = np.random.uniform(low=0.0, high=1.0, size=(d, m))24 elif(dist == 'normal'):25 L = stats.truncnorm.rvs(-1.0, 1.0, 0.0, 1.0, size=(d, m))26 return L27# generate matrix U of size d x m according to distribution dist28def generate_utility_matrix(d, m, dist):29 if (dist == 'uniform'):30 U = np.random.uniform(low=0.0, high=1.0, size=(d, m))31 elif (dist == 'normal'):32 U = stats.truncnorm.rvs(-1.0, 1.0, 0.0, 1.0, size=(d, m))33 return U34def generate_utility_matrix_var(d, m, dist, var):35 if (dist == 'uniform'):36 U_vec = np.random.uniform(low=0.0, high=1.0, size=(d,))37 elif (dist == 'normal'):38 U_vec = stats.truncnorm.rvs(-1.0, 1.0, 0.0, 1.0, size=(d,))39 40 U_mat = np.ones((d,m))41 for col in range(m):42 noise = np.random.normal(scale=var, size=(d,))43 U_mat[:,col] = np.clip(U_vec+noise, 0, 1)44 45 return U_mat46def define_groups(X, group_dist, normalized=False):47 """ Given a vector where each element represents the portion of the population that should48 belong to each group, and the size of the vector represents the number of groups.49 Return a list of matricies, where each matrix contains all the individuals that belong50 to that group 51 """52 n, m = X.shape53 assert(sum(group_dist)-1 <= 1e-5)54 assert(min(group_dist) >= 0)55 # Let the first element in the feature vector represent group identity56 X0s = X[:,0]57 low = 058 samples_by_group = {}59 for group_id, val in enumerate(group_dist):60 high = low + val61 low_indicies = np.where(X0s >= low)62 high_indicies = np.where(X0s <= high)63 indicies = np.intersect1d(low_indicies, high_indicies)64 65 if normalized:66 norm_X = normalize(X[indicies,:], axis=1, norm='l1') 67 samples_by_group[group_id] = norm_X68 else:69 samples_by_group[group_id] = X[indicies,:]70 low = high71 return samples_by_group72def test_groups():73 X = np.random.uniform(size=(6,6))74 print(X)75 group_dist = [0.25, 0.25, 0.25, 0.25]76 grps = define_groups(X, group_dist)77 print(grps)78def get_default_alpha_arr(K):79 alpha = []80 alpha_value = 1.081 for k in range(K-1):82 alpha_value = alpha_value / 283 alpha.append(alpha_value)84 alpha.append(alpha_value)85 return alpha86def get_optimal_loss(L_mat, X):87 loss_matrix = np.matmul(X, L_mat.T)88 loss_matrix = normalize(loss_matrix, axis=1, norm='l1')89 (n, d) = loss_matrix.shape90 min_val = loss_matrix.min(axis=1)91 assert(min_val.shape == (n,))92 return sum(min_val)/n93 94def predictions(beta_value, all_X):95 return np.argmax(np.matmul(beta_value, all_X.T), axis = 0)96def get_all_predictions(beta_values, all_X, groups, K_):97 learned_predictions = []98 for k in range(K_):99 all_prediction = np.argmax(np.matmul(beta_values[k], all_X.T), axis = 0)100 learned_predictions.append(all_prediction)101 num_groups = len(groups.keys())102 learned_pred_group = {h:[] for h in range(num_groups)} 103 for k in range(K_):104 for h in range(num_groups):105 learned_pred_group[h].append(predictions(beta_values[k], groups[h]))106 107 return learned_predictions, learned_pred_group108def compute_final_loss(alphas, L_mat, X, learned_predictions):109 L_X = np.matmul(X, L_mat.T)110 L_X = normalize(L_X, axis=1, norm='l1')111 112 final_loss = 0113 K = len(alphas)114 n, m = X.shape115 116 for k in range(K):117 for i in range(n):118 final_loss += alphas[k]*L_X[i, learned_predictions[k][i]]119 return final_loss/n120def compute_welfare(alphas, U_mat, X, learned_predictions):121 return compute_final_loss(alphas, U_mat, X, learned_predictions)122def group_utility(alphas, U_mat, group_i, group_j, pred_i, pred_j, same=False):123 ## Compute the utility group i has for group j's clasification124 UX_i = np.matmul(group_i, U_mat.T)125 UX_j = np.matmul(group_j, U_mat.T)126 127 UX_i = normalize(UX_i, axis=1, norm='l1')128 UX_j = normalize(UX_j, axis=1, norm='l1')129 130 ni = group_i.shape[0]131 nj = group_j.shape[0]132 if same:133 welf = compute_welfare(alphas, U_mat, group_i, pred_i)134 return welf135 else:136 welf = 0137 for t, alpha in enumerate(alphas):138 for li in range(ni):139 for lj in range(nj):140 welf += alpha*UX_i[li, pred_j[t][lj]]141 return welf/(ni*nj) 142def total_group_envy(alphas, U_mat, groups, group_pred):143 violations = 0144 total_envy = 0145 num_groups = len(groups.keys())146 for i in range(num_groups):147 for j in range(num_groups):148 if i != j:149 u_ii = group_utility(alphas, U_mat, groups[i], \150 groups[i], group_pred[i], group_pred[i], same=True)151 u_ij = group_utility(alphas, U_mat, groups[i], \152 groups[j], group_pred[i], group_pred[j]) 153 total_envy += max(u_ij - u_ii, 0)154 if u_ij > u_ii + 1e-3:155 violations += 1156 157 total_envy = total_envy / (num_groups*(num_groups-1)) 158 violations = violations / (num_groups*(num_groups-1))159 return total_envy, violations160def total_average_envy(alphas, U_mat, X, pred):161 U_X = np.matmul(X, U_mat.T)162 U_X = normalize(U_X, axis=1, norm='l1')163 n, m = X.shape164 total_envy = 0165 violations = 0166 for i in range(n):167 for j in range(n):168 if i != j:169 u_ii, u_ij = 0, 0170 for k in range(len(alphas)):171 u_ii += alphas[k]*U_X[i, pred[k][i]]172 u_ij += alphas[k]*U_X[i, pred[k][j]]173 total_envy += max(u_ij - u_ii, 0) 174 if u_ij > u_ii + 1e-3:175 violations += 1176 total_envy = total_envy * (1/(n*(n-1)))177 violations = violations * (1/(n*(n-1)))178 return total_envy, violations179def total_group_equi(alphas, U_mat, groups, group_pred):180 violations = 0181 total_equi = 0182 num_groups = len(groups.keys())183 for i in range(num_groups):184 for j in range(num_groups):185 if i != j:186 u_ii = group_utility(alphas, U_mat, groups[i], \187 groups[i], group_pred[i], group_pred[i], same=True)188 u_jj = group_utility(alphas, U_mat, groups[j], \189 groups[j], group_pred[j], group_pred[j], same=True) 190 #print("i: ", i, "j: ", j, "uii:", u_ii, "ujj: ", u_jj) 191 total_equi += abs(u_jj - u_ii)192 if total_equi >= 1e-3:193 violations += 1194 total_equi = total_equi / (num_groups*(num_groups-1)) 195 violations = violations / (num_groups*(num_groups-1))196 return total_equi, violations197def min_group_welfare(alphas, U_mat, groups, group_pred):198 # return the welfare of group with the lowest welfare199 welfares = []200 num_groups = len(groups.keys())201 for i in range(num_groups):202 u_ii = group_utility(alphas, U_mat, groups[i], \203 groups[i], group_pred[i], group_pred[i], same=True)204 welfares.append(u_ii) 205 206 return min(welfares)207def get_convex_version(X, Mat_X, Beta, y, i): 208 return cp.max(Mat_X[i, :] + cp.matmul(Beta,X[i,:])) - cp.matmul(Beta[y[i],:], X[i,:])209if __name__ == "__main__":...

Full Screen

Full Screen

translator.py

Source:translator.py Github

copy

Full Screen

1class Translator(object):2 @staticmethod3 def num_to_string(num):4 if not isinstance(num, int):5 raise TypeError6 elif num < 0:7 raise ValueError8 if num == 0:9 return "zero"10 simple_nums_to_str = {11 1: "one",12 2: "two",13 3: "three",14 4: "four",15 5: "five",16 6: "six",17 7: "seven",18 8: "eight",19 9: "nine",20 10: "ten",21 11: "eleven",22 12: "twelve",23 13: "thirteen",24 14: "fourteen",25 15: "fifteen",26 16: "sixteen",27 17: "seventeen",28 18: "eighteen",29 19: "nineteen"30 }31 if num in simple_nums_to_str:32 return simple_nums_to_str[num]33 second_placed_nums_to_str = {34 2: "twenty",35 3: "thirty",36 4: "forty",37 5: "fifty",38 6: "sixty",39 7: "seventy",40 8: "eighty",41 9: "ninety",42 }43 result_str = ""44 dig_place_groups = []45 while num:46 dig_place_groups.append(num % 100)47 num //= 10048 dig_place_groups.append(num % 10)49 num //= 1050 group_pred = {51 0: "",52 1: " hundred ",53 2: " thousand ",54 4: " million ",55 6: " billion ",56 8: " trillion ",57 10: " quadrillion ",58 12: " quintillion ",59 14: " sextillion ",60 16: " septillion "61 }62 for group, gnum in enumerate(dig_place_groups):63 if gnum == 0:64 continue65 if group % 2 == 0:66 if gnum in simple_nums_to_str:67 result_str = simple_nums_to_str[gnum] + group_pred[group] + result_str68 else:69 result_str = second_placed_nums_to_str[gnum // 10]\70 + ("-" + simple_nums_to_str[gnum % 10] if gnum % 10 != 0 else "")\71 + group_pred[group] + result_str72 else:73 result_str = simple_nums_to_str[gnum] + group_pred[1] + result_str...

Full Screen

Full Screen

Linear_Regression_Classifier.py

Source:Linear_Regression_Classifier.py Github

copy

Full Screen

1# Linear Regression2import numpy as np3from numpy.linalg import inv4import pickle5import numpy as np6import math7class Linear_Regression_Classifier(object):8 def __init__(self, X, y):9 self.features = X10 self.target = y11 def train(self,l):12 """STUDNET_CODE"""13 x = self.features14 y = self.target15 16 I = np.identity(len(x[1,:]))17 I[0,0] = 018 xT = np.matrix.transpose(x)19 xTx = np.dot(xT,x) + l*I20 XTX = inv(xTx)21 XTX_xT = np.dot(XTX,xT) 22 23 W = XTX_xT.dot(y)24 W = W[np.newaxis]25 Y = np.dot(x,W.T)26 27 self.W = W28 29 def predict(self, X):30 wT = self.W.T31 y = X.dot(wT)32 return y33 34 def encoding_scalar_to_group(self,y):35 group_pred = np.around(y)36 group_pred = np.squeeze(group_pred).T37 return group_pred38 def encdoing_vector_to_group(self,y):39 group_pred = np.squeeze(y)40 group = [np.argmax(r,axis=0) for r in group_pred]41 return group42 def classifier_onehot(self,X):43 y = self.predict(X)44 group_pred=self.encdoing_vector_to_group(y)45 return group_pred46 47 def classifier_scalar(self,X):48 y = self.predict(X)49 group_pred=self.encoding_scalar_to_group(y)50 return group_pred...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful