python_code
stringlengths 0
4.04M
| repo_name
stringlengths 7
58
| file_path
stringlengths 5
147
|
---|---|---|
# Copyright (c) 2020 Flowers Team
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
def get_empty_env_ranges():
return {'roughness':None,
'stump_height':None,
'obstacle_spacing':None,
'gap_width':None}
def get_test_set_name(env_ranges):
name = ''
for k, v in env_ranges.items():
if (v is not None) and (k is not 'env_param_input') and (k is not 'nb_rand_dim'):
if k is "stump_height": # always same test set for stump height experiments
name += k + str(v[0]) + "_3.0"
else:
name += k + str(v[0]) + "_" + str(v[1])
if name == '':
print('Empty parameter space, please choose one when launching run.py, e.g:\n'
'"--max_stump_h 3.0 --max_obstacle_spacing 6.0" or\n'
'"-poly" or\n'
'"-seq"')
raise NotImplementedError
return name | dcd-main | teachDeepRL/teachers/utils/test_utils.py |
# Copyright (c) 2020 Flowers Team
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
# Modified version of dataset from https://github.com/flowersteam/explauto
# Implements a buffered knn using a kd-tree
# WARNING ugly code, sorry
try:
import numpy as np
import scipy.spatial
except:
print("Can't import scipy.spatial (or numpy). Is scipy (or numpy) correctly installed ?")
exit(1)
DATA_X = 0
DATA_Y = 1
class Databag(object):
"""Hold a set of vectors and provides nearest neighbors capabilities"""
def __init__(self, dim):
"""
:arg dim: the dimension of the data vectors
"""
self.dim = dim
self.reset()
def __repr__(self):
return 'Databag(dim={0}, data=[{1}])'.format(self.dim, ', '.join(str(x) for x in self.data))
def add(self, x):
assert len(x) == self.dim
self.data.append(np.array(x))
self.size += 1
self.nn_ready = False
def reset(self):
"""Reset the dataset to zero elements."""
self.data = []
self.size = 0
self.kdtree = None # KDTree
self.nn_ready = False # if True, the tree is up-to-date.
def nn(self, x, k = 1, radius = np.inf, eps = 0.0, p = 2):
"""Find the k nearest neighbors of x in the observed input data
:arg x: center
:arg k: the number of nearest neighbors to return (default: 1)
:arg eps: approximate nearest neighbors.
the k-th returned value is guaranteed to be no further than
(1 + eps) times the distance to the real k-th nearest neighbor.
:arg p: Which Minkowski p-norm to use. (default: 2, euclidean)
:arg radius: the maximum radius (default: +inf)
:return: distance and indexes of found nearest neighbors.
"""
assert len(x) == self.dim, 'dimension of input {} does not match expected dimension {}.'.format(len(x), self.dim)
k_x = min(k, self.size)
# Because linear models requires x vector to be extended to [1.0]+x
# to accomodate a constant, we store them that way.
return self._nn(np.array(x), k_x, radius = radius, eps = eps, p = p)
def get(self, index):
return self.data[index]
def iter(self):
return iter(self.data)
def _nn(self, v, k = 1, radius = np.inf, eps = 0.0, p = 2):
"""Compute the k nearest neighbors of v in the observed data,
:see: nn() for arguments descriptions.
"""
self._build_tree()
dists, idxes = self.kdtree.query(v, k = k, distance_upper_bound = radius,
eps = eps, p = p)
if k == 1:
dists, idxes = np.array([dists]), [idxes]
return dists, idxes
def _build_tree(self):
"""Build the KDTree for the observed data
"""
if not self.nn_ready:
self.kdtree = scipy.spatial.cKDTree(self.data)
self.nn_ready = True
def __len__(self):
return self.size
class Dataset(object):
"""Hold observations an provide nearest neighbors facilities"""
@classmethod
def from_data(cls, data):
""" Create a dataset from an array of data, infering the dimension from the datapoint """
if len(data) == 0:
raise ValueError("data array is empty.")
dim_x, dim_y = len(data[0][0]), len(data[0][1])
dataset = cls(dim_x, dim_y)
for x, y in data:
assert len(x) == dim_x and len(y) == dim_y
dataset.add_xy(x, y)
return dataset
@classmethod
def from_xy(cls, x_array, y_array):
""" Create a dataset from two arrays of data.
:note: infering the dimensions for the first elements of each array.
"""
if len(x_array) == 0:
raise ValueError("data array is empty.")
dim_x, dim_y = len(x_array[0]), len(y_array[0])
dataset = cls(dim_x, dim_y)
for x, y in zip(x_array, y_array):
assert len(x) == dim_x and len(y) == dim_y
dataset.add_xy(x, y)
return dataset
def __init__(self, dim_x, dim_y, lateness=0, max_size=None):
"""
:arg dim_x: the dimension of the input vectors
:arg dim_y: the dimension of the output vectors
"""
self.dim_x = dim_x
self.dim_y = dim_y
self.lateness = lateness
self.max_size = max_size
self.reset()
# The two next methods are used for plicling/unpickling the object (because cKDTree cannot be pickled).
def __getstate__(self):
odict = self.__dict__.copy()
del odict['kdtree']
return odict
def __setstate__(self,dict):
self.__dict__.update(dict)
self.nn_ready = [False, False]
self.kdtree = [None, None]
def reset(self):
"""Reset the dataset to zero elements."""
self.data = [[], []]
self.size = 0
self.kdtree = [None, None] # KDTreeX, KDTreeY
self.nn_ready = [False, False] # if True, the tree is up-to-date.
self.kdtree_y_sub = None
self.late_points = 0
def add_xy(self, x, y=None):
#assert len(x) == self.dim_x, (len(x), self.dim_x)
#assert self.dim_y == 0 or len(y) == self.dim_y, (len(y), self.dim_y)
self.data[0].append(x)
if self.dim_y > 0:
self.data[1].append(y)
self.size += 1
if self.late_points == self.lateness:
self.nn_ready = [False, False]
self.late_points = 0
else:
self.late_points += 1
# Reduce data size
if self.max_size and self.size > self.max_size:
n = self.size - self.max_size
del self.data[0][:n]
del self.data[1][:n]
self.size = self.max_size
def add_xy_batch(self, x_list, y_list):
assert len(x_list) == len(y_list)
self.data[0] = self.data[0] + x_list
self.data[1] = self.data[1] + y_list
self.size += len(x_list)
# Reduce data size
if self.max_size and self.size > self.max_size:
n = self.size - self.max_size
del self.data[0][:n]
del self.data[1][:n]
self.size = self.max_size
def get_x(self, index):
return self.data[0][index]
def set_x(self, x, index):
self.data[0][index] = x
def get_x_padded(self, index):
return np.append(1.0,self.data[0][index])
def get_y(self, index):
return self.data[1][index]
def set_y(self, y, index):
self.data[1][index] = y
def get_xy(self, index):
return self.get_x(index), self.get_y(index)
def set_xy(self, x, y, index):
self.set_x(x, index)
self.set_y(y, index)
def get_dims(self, index, dims_x=None, dims_y=None, dims=None):
if dims is None:
return np.hstack((np.array(self.data[0][index])[dims_x], np.array(self.data[1][index])[np.array(dims_y) - self.dim_x]))
else:
if max(dims) < self.dim_x:
return np.array(self.data[0][index])[dims]
elif min(dims) > self.dim_x:
return np.array(self.data[1][index])[np.array(dims) - self.dim_x]
else:
raise NotImplementedError
def iter_x(self):
return iter(d for d in self.data[0])
def iter_y(self):
return iter(self.data[1])
def iter_xy(self):
return zip(self.iter_x(), self.data[1])
def __len__(self):
return self.size
def nn_x(self, x, k=1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of x in the observed input data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
assert len(x) == self.dim_x
k_x = min(k, self.size)
# Because linear models requires x vector to be extended to [1.0]+x
# to accomodate a constant, we store them that way.
return self._nn(DATA_X, x, k=k_x, radius=radius, eps=eps, p=p)
def nn_y(self, y, k=1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of y in the observed output data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
assert len(y) == self.dim_y
k_y = min(k, self.size)
return self._nn(DATA_Y, y, k=k_y, radius=radius, eps=eps, p=p)
def nn_dims(self, x, y, dims_x, dims_y, k=1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of a subset of dims of x and y in the observed output data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
assert len(x) == len(dims_x)
assert len(y) == len(dims_y)
if len(dims_x) == 0:
kdtree = scipy.spatial.cKDTree([np.array(data_y)[np.array(dims_y) - self.dim_x] for data_y in self.data[DATA_Y]])
elif len(dims_y) == 0:
kdtree = scipy.spatial.cKDTree([np.array(data_x)[dims_x] for data_x in self.data[DATA_X]])
else:
kdtree = scipy.spatial.cKDTree([np.hstack((np.array(data_x)[dims_x], np.array(data_y)[np.array(dims_y) - self.dim_x])) for data_x,data_y in zip(self.data[DATA_X], self.data[DATA_Y])])
dists, idxes = kdtree.query(np.hstack((x, y)),
k = k,
distance_upper_bound = radius,
eps = eps,
p = p)
if k == 1:
dists, idxes = np.array([dists]), [idxes]
return dists, idxes
def _nn(self, side, v, k = 1, radius = np.inf, eps = 0.0, p = 2):
"""Compute the k nearest neighbors of v in the observed data,
:arg side if equal to DATA_X, search among input data.
if equal to DATA_Y, search among output data.
@return distance and indexes of found nearest neighbors.
"""
self._build_tree(side)
dists, idxes = self.kdtree[side].query(v, k = k, distance_upper_bound = radius,
eps = eps, p = p)
if k == 1:
dists, idxes = np.array([dists]), [idxes]
return dists, idxes
def _build_tree(self, side):
"""Build the KDTree for the observed data
:arg side if equal to DATA_X, build input data tree.
if equal to DATA_Y, build output data tree.
"""
if not self.nn_ready[side]:
self.kdtree[side] = scipy.spatial.cKDTree(self.data[side], compact_nodes=False, balanced_tree=False) # Those options are required with scipy >= 0.16
self.nn_ready[side] = True
class BufferedDataset(Dataset):
"""Add a buffer of a few points to avoid recomputing the kdtree at each addition"""
def __init__(self, dim_x, dim_y, buffer_size=200, lateness=5, max_size=None):
"""
:arg dim_x: the dimension of the input vectors
:arg dim_y: the dimension of the output vectors
"""
self.buffer_size = buffer_size
self.lateness = lateness
self.buffer = Dataset(dim_x, dim_y, lateness=self.lateness)
Dataset.__init__(self, dim_x, dim_y, lateness=0)
self.max_size = max_size
def reset(self):
self.buffer.reset()
Dataset.reset(self)
def add_xy(self, x, y=None):
if self.buffer.size < self.buffer_size:
self.buffer.add_xy(x, y)
else:
self.data[0] = self.data[0] + self.buffer.data[0]
if self.dim_y > 0:
self.data[1] = self.data[1] + self.buffer.data[1]
self.size += self.buffer.size
self.buffer = Dataset(self.dim_x, self.dim_y, lateness=self.lateness)
self.nn_ready = [False, False]
self.buffer.add_xy(x, y)
# Reduce data size
if self.max_size and self.size > self.max_size:
n = self.size - self.max_size
del self.data[0][:n]
del self.data[1][:n]
self.size = self.max_size
def add_xy_batch(self, x_list, y_list):
assert len(x_list) == len(y_list)
Dataset.add_xy_batch(self, self.buffer.data[0], self.buffer.data[1])
self.buffer = Dataset(self.dim_x, self.dim_y, lateness=self.lateness)
Dataset.add_xy_batch(self, x_list, y_list)
self.nn_ready = [False, False]
def get_x(self, index):
if index >= self.size:
return self.buffer.data[0][index-self.size]
else:
return self.data[0][index]
def set_x(self, x, index):
if index >= self.size:
self.buffer.set_x(x, index-self.size)
else:
self.data[0][index] = x
def get_x_padded(self, index):
if index >= self.size:
return np.append(1.0, self.buffer.data[0][index-self.size])
else:
return np.append(1.0, self.data[0][index])
def get_y(self, index):
if index >= self.size:
return self.buffer.data[1][index-self.size]
else:
return self.data[1][index]
def set_y(self, y, index):
if index >= self.size:
self.buffer.set_y(y, index-self.size)
else:
self.data[1][index] = y
def get_dims(self, index, dims_x=None, dims_y=None, dims=None):
if index >= self.size:
return self.buffer.get_dims(index-self.size, dims_x, dims_y, dims)
else:
return Dataset.get_dims(self, index, dims_x, dims_y, dims)
def iter_x(self):
return iter(d for d in self.data[0] + self.buffer.data[0])
def iter_y(self):
return iter(self.data[1] + self.buffer.data[1])
def iter_xy(self):
return zip(self.iter_x(), self.data[1] + self.buffer.data[1])
def __len__(self):
return self.size + self.buffer.size
def nn_x(self, x, k=1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of x in the observed input data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
assert len(x) == self.dim_x
k_x = min(k, self.__len__())
# Because linear models requires x vector to be extended to [1.0]+x
# to accomodate a constant, we store them that way.
return self._nn(DATA_X, x, k=k_x, radius=radius, eps=eps, p=p)
def nn_y(self, y, dims=None, k = 1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of y in the observed output data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
if dims is None:
assert len(y) == self.dim_y
k_y = min(k, self.__len__())
return self._nn(DATA_Y, y, k=k_y, radius=radius, eps=eps, p=p)
else:
return self.nn_y_sub(y, dims, k, radius, eps, p)
def nn_dims(self, x, y, dims_x, dims_y, k=1, radius=np.inf, eps=0.0, p=2):
"""Find the k nearest neighbors of a subset of dims of x and y in the observed output data
@see Databag.nn() for argument description
@return distance and indexes of found nearest neighbors.
"""
if self.size > 0:
dists, idxes = Dataset.nn_dims(self, x, y, dims_x, dims_y, k, radius, eps, p)
else:
return self.buffer.nn_dims(x, y, dims_x, dims_y, k, radius, eps, p)
if self.buffer.size > 0:
buffer_dists, buffer_idxes = self.buffer.nn_dims(x, y, dims_x, dims_y, k, radius, eps, p)
buffer_idxes = [i + self.size for i in buffer_idxes]
ziped = zip(dists, idxes)
buffer_ziped = zip(buffer_dists, buffer_idxes)
sorted_dists_idxes = sorted(ziped + buffer_ziped, key=lambda di:di[0])
knns = sorted_dists_idxes[:k]
return [knn[0] for knn in knns], [knn[1] for knn in knns]
else:
return dists, idxes
def _nn(self, side, v, k=1, radius=np.inf, eps=0.0, p=2):
"""Compute the k nearest neighbors of v in the observed data,
:arg side if equal to DATA_X, search among input data.
if equal to DATA_Y, search among output data.
@return distance and indexes of found nearest neighbors.
"""
if self.size > 0:
dists, idxes = Dataset._nn(self, side, v, k, radius, eps, p)
else:
return self.buffer._nn(side, v, k, radius, eps, p)
if self.buffer.size > 0:
buffer_dists, buffer_idxes = self.buffer._nn(side, v, k, radius, eps, p)
buffer_idxes = [i + self.size for i in buffer_idxes]
if dists[0] <= buffer_dists:
return dists, idxes
else:
return buffer_dists, buffer_idxes
ziped = zip(dists, idxes)
buffer_ziped = zip(buffer_dists, buffer_idxes)
sorted_dists_idxes = sorted(ziped + buffer_ziped, key=lambda di:di[0])
knns = sorted_dists_idxes[:k]
return [knn[0] for knn in knns], [knn[1] for knn in knns]
else:
return dists, idxes
| dcd-main | teachDeepRL/teachers/utils/dataset.py |
# Copyright (c) 2020 Flowers Team
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
# Plotting functions
# WARNING ugly code, sorry
import matplotlib.patches as patches
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import matplotlib.colorbar as cbar
import matplotlib.pyplot as plt
import imageio
import numpy as np
import copy
import os
from matplotlib.patches import Ellipse
import matplotlib.colors as colors
# scale numpy 1d array to [-1:1] given its bounds
# bounds must be of the form [[min1,max1],[min2,max2],...]
def scale_vector(values, bounds):
mins_maxs_diff = np.diff(bounds).squeeze()
mins = bounds[:, 0]
return (((values - mins) * 2) / mins_maxs_diff) - 1
def unscale_vector(scaled_values, bounds=[[-1,1]]):
mins_maxs_diff = np.diff(bounds).squeeze()
mins = bounds[:, 0]
return (((scaled_values + 1) * mins_maxs_diff) / 2) + mins
def plt_2_rgb(ax):
ax.figure.canvas.draw()
data = np.frombuffer(ax.figure.canvas.tostring_rgb(), dtype=np.uint8)
data = data.reshape(ax.figure.canvas.get_width_height()[::-1] + (3,))
return data
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
new_cmap = colors.LinearSegmentedColormap.from_list(
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
cmap(np.linspace(minval, maxval, n)))
return new_cmap
def scatter_plot(data, ax=None, emph_data=None, xlabel='stump height', ylabel='spacing', xlim=None, ylim=None):
if ax is None:
f, ax = plt.subplots(1, 1, figsize=(7, 7))
Xs, Ys = [d[0] for d in data], [d[1] for d in data]
if emph_data is not None:
emphXs, emphYs = [d[0] for d in emph_data], [d[1] for d in emph_data]
ax.plot(Xs, Ys, 'r.', markersize=2)
ax.axis('equal')
ax.set_xlim(left=xlim[0], right=xlim[1])
ax.set_ylim(bottom=ylim[0], top=ylim[1])
if emph_data is not None:
ax.plot(emphXs, emphYs, 'b.', markersize=5)
ax.set_xlabel(xlabel, fontsize=20)
ax.set_ylabel(ylabel, fontsize=20)
def plot_regions(boxes, interests, ax=None, xlabel='', ylabel='', xlim=None, ylim=None, bar=True):
ft_off = 15
# Create figure and axes
if ax == None:
f, ax = plt.subplots(1, 1, figsize=(8, 7))
# Add the patch to the Axes
#print(boxes)
for b, ints in zip(boxes, interests):
# print(b)
lx, ly = b.low
hx, hy = b.high
c = plt.cm.jet(ints)
rect = patches.Rectangle([lx, ly], (hx - lx), (hy - ly), linewidth=3, edgecolor='white', facecolor=c)
ax.add_patch(rect)
# plt.Rectangle([lx,ly],(hx - lx), (hy - ly))
if bar:
cax, _ = cbar.make_axes(ax, shrink=0.8)
cb = cbar.ColorbarBase(cax, cmap=plt.cm.jet)
cb.set_label('Absolute Learning Progress', fontsize=ft_off + 5)
cax.tick_params(labelsize=ft_off + 0)
ax.set_xlim(left=xlim[0], right=xlim[1])
ax.set_ylim(bottom=ylim[0], top=ylim[1])
ax.set_xlabel(xlabel, fontsize=ft_off + 0)
ax.set_ylabel(ylabel, fontsize=ft_off + 0)
ax.tick_params(axis='both', which='major', labelsize=ft_off + 5)
ax.set_aspect('equal', 'box')
def region_plot_gif(all_boxes, interests, iterations, goals, gifname='riac', rewards=None, ep_len=None,
gifdir='graphics/', xlim=[0,1], ylim=[0,1], scatter=False, fs=(9,6), plot_step=250):
gifdir = 'graphics/' + gifdir
ft_off = 15
plt.ioff()
print("Making an exploration GIF: " + gifname)
# Create target Directory if don't exist
tmpdir = 'tmp/'
tmppath = gifdir + 'tmp/'
if not os.path.exists(gifdir):
os.mkdir(gifdir)
print("Directory ", gifdir, " Created ")
if not os.path.exists(tmppath):
os.mkdir(tmppath)
print("Directory ", tmppath, " Created ")
filenames = []
images = []
steps = []
mean_rewards = []
for i in range(len(goals)):
if i > 0 and (i % plot_step == 0):
f, (ax0) = plt.subplots(1, 1, figsize=fs)
ax = [ax0]
if scatter:
scatter_plot(goals[0:i], ax=ax[0], emph_data=goals[i - plot_step:i], xlim=xlim, ylim=ylim)
idx = 0
cur_idx = 0
for j in range(len(all_boxes)):
if iterations[j] > i:
break
else:
cur_idx = j
plot_regions(all_boxes[cur_idx], interests[cur_idx], ax=ax[0], xlim=xlim, ylim=ylim)
f_name = gifdir+tmpdir+"scatter_{}.png".format(i)
plt.suptitle('Episode {}'.format(i), fontsize=ft_off+0)
images.append(plt_2_rgb(plt.gca()))
plt.close(f)
imageio.mimsave(gifdir + gifname + '.gif', images, duration=0.4)
def draw_ellipse(position, covariance, ax=None, color=None, **kwargs):
"""Draw an ellipse with a given position and covariance"""
ax = ax or plt.gca()
covariance = covariance[0:2,0:2]
position = position[0:2]
# Convert covariance to principal axes
if covariance.shape == (2, 2):
U, s, Vt = np.linalg.svd(covariance)
angle = np.degrees(np.arctan2(U[1, 0], U[0, 0]))
width, height = 2 * np.sqrt(s)
else:
angle = 0
width, height = 2 * np.sqrt(covariance)
# Draw the Ellipse
for nsig in range(2, 3):
ax.add_patch(Ellipse(position, nsig * width, nsig * height,
angle, **kwargs, color=color))
def draw_competence_grid(ax, comp_grid, x_bnds, y_bnds, bar=True):
comp_grid[comp_grid == 100] = 1000
ax.pcolor(x_bnds, y_bnds, np.transpose(comp_grid),cmap=plt.cm.gray, edgecolors='k', linewidths=2,
alpha=0.3)
if bar:
cax, _ = cbar.make_axes(ax,location='left')
cb = cbar.ColorbarBase(cax, cmap=plt.cm.gray)
cb.set_label('Competence')
cax.yaxis.set_ticks_position('left')
cax.yaxis.set_label_position('left')
def plot_gmm(weights, means, covariances, X=None, ax=None, xlim=[0,1], ylim=[0,1], xlabel='', ylabel='',
bar=True, bar_side='right',no_y=False, color=None):
ft_off = 15
ax = ax or plt.gca()
cmap = truncate_colormap(plt.cm.autumn_r, minval=0.2,maxval=1.0)
#colors = [plt.cm.jet(i) for i in X[:, -1]]
if X is not None:
colors = [cmap(i) for i in X[:, -1]]
sizes = [5+np.interp(i,[0,1],[0,10]) for i in X[:, -1]]
ax.scatter(X[:, 0], X[:, 1], c=colors, s=sizes, zorder=2)
#ax.axis('equal')
w_factor = 0.6 / weights.max()
for pos, covar, w in zip(means, covariances, weights):
draw_ellipse(pos, covar, alpha=0.6, ax=ax, color=color)
#plt.margins(0, 0)
ax.set_xlim(left=xlim[0], right=xlim[1])
ax.set_ylim(bottom=ylim[0], top=ylim[1])
if bar:
cax, _ = cbar.make_axes(ax, location=bar_side, shrink=0.8)
cb = cbar.ColorbarBase(cax, cmap=cmap)
cb.set_label('Absolute Learning Progress', fontsize=ft_off + 5)
cax.tick_params(labelsize=ft_off + 0)
cax.yaxis.set_ticks_position(bar_side)
cax.yaxis.set_label_position(bar_side)
#ax.yaxis.tick_right()
if no_y:
ax.set_yticks([])
else:
ax.set_ylabel(ylabel, fontsize=ft_off + 5)
#ax.yaxis.set_label_position("right")
ax.set_xlabel(xlabel, fontsize=ft_off + 5)
ax.tick_params(axis='both', which='major', labelsize=ft_off + 5)
ax.set_aspect('equal', 'box')
def gmm_plot_gif(bk, gifname='test', gifdir='graphics/', ax=None,
xlim=[0,1], ylim=[0,1], fig_size=(9,6), save_imgs=False, title=True, bar=True):
gifdir = 'graphics/' + gifdir
plt.ioff()
# Create target Directory if don't exist
tmpdir = 'tmp/'
tmppath = gifdir + 'tmp/'
if not os.path.exists(gifdir):
os.mkdir(gifdir)
print("Directory ", gifdir, " Created ")
if not os.path.exists(tmppath):
os.mkdir(tmppath)
print("Directory ", tmppath, " Created ")
print("Making " + tmppath + gifname + ".gif")
images = []
old_ep = 0
gen_size = int(len(bk['tasks_lps']) / len(bk['episodes']))
gs_lps = bk['tasks_lps']
for i,(ws, covs, means, ep) in enumerate(zip(bk['weights'], bk['covariances'], bk['means'], bk['episodes'])):
plt.figure(figsize=fig_size)
ax = plt.gca()
plot_gmm(ws, means, covs, np.array(gs_lps[old_ep + gen_size:ep + gen_size]),
ax=ax, xlim=xlim, ylim=ylim,
bar=bar) # add gen_size to have gmm + the points that they generated, not they fitted
if 'comp_grids' in bk: # add competence grid info
draw_competence_grid(ax,bk['comp_grids'][i], bk['comp_xs'][i], bk['comp_ys'][i])
if 'start_points' in bk: # add lineworld info
draw_lineworld_info(ax, bk['start_points'], bk['end_points'], bk['current_states'][i])
f_name = gifdir+tmpdir+gifname+"_{}.png".format(ep)
if title:
plt.suptitle('Episode {} | nb Gaussians:{}'.format(ep,len(means)), fontsize=20)
old_ep = ep
if save_imgs: plt.savefig(f_name, bbox_inches='tight')
images.append(plt_2_rgb(ax))
plt.close()
imageio.mimsave(gifdir + gifname + '.gif', images, duration=0.4)
def random_plot_gif(bk, step=250, gifname='test', gifdir='graphics/', ax=None,
xlim=[0,1], ylim=[0,1], fig_size=(9,6), save_imgs=False, title=True, bar=True):
gifdir = 'graphics/' + gifdir
plt.ioff()
# Create target Directory if don't exist
tmpdir = 'tmp/'
tmppath = gifdir + 'tmp/'
if not os.path.exists(gifdir):
os.mkdir(gifdir)
print("Directory ", gifdir, " Created ")
if not os.path.exists(tmppath):
os.mkdir(tmppath)
print("Directory ", tmppath, " Created ")
print("Making " + tmppath + gifname + ".gif")
images = []
tasks = np.array(bk['tasks'])
for i,(c_grids, c_xs, c_ys) in enumerate(zip(bk['comp_grids'], bk['comp_xs'], bk['comp_ys'])):
plt.figure(figsize=fig_size)
ax = plt.gca()
draw_competence_grid(ax, c_grids, c_xs, c_ys)
ax.scatter(tasks[i*step:(i+1)*step, 0], tasks[i*step:(i+1)*step, 1], c='blue', s=2, zorder=2)
ax.set_xlim(left=xlim[0], right=xlim[1])
ax.set_ylim(bottom=ylim[0], top=ylim[1])
ax.tick_params(axis='both', which='major', labelsize=20)
ax.set_aspect('equal', 'box')
f_name = gifdir+tmpdir+gifname+"_{}.png".format(i)
if title:
plt.suptitle('Episode {}'.format(i*step), fontsize=20)
if save_imgs: plt.savefig(f_name, bbox_inches='tight')
images.append(plt_2_rgb(ax))
plt.close()
imageio.mimsave(gifdir + gifname + '.gif', images, duration=0.4) | dcd-main | teachDeepRL/teachers/utils/plot_utils.py |
# Copyright (c) 2020 Flowers Team
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
import numpy as np
from gym.spaces import Box
from collections import deque
import copy
from treelib import Tree
from itertools import islice
def proportional_choice(v, eps=0.):
if np.sum(v) == 0 or np.random.rand() < eps:
return np.random.randint(np.size(v))
else:
probas = np.array(v) / np.sum(v)
return np.where(np.random.multinomial(1, probas) == 1)[0][0]
# A region is a subspace of the task space
class Region(object):
def __init__(self, maxlen, r_t_pairs=None, bounds=None, alp=None):
self.r_t_pairs = r_t_pairs # A list of pairs of sampled tasks associated to the reward the student obtained
self.bounds = bounds
self.alp = alp # Absolute Learning Progress of Region
self.maxlen = maxlen
def add(self, task, reward, is_leaf):
self.r_t_pairs[1].append(task.copy())
self.r_t_pairs[0].append(reward)
need_split = False
if is_leaf and (len(self.r_t_pairs[0]) > self.maxlen):
# Leaf is full, need split
need_split = True
return need_split
# Implementation of Robust Intelligent-Adaptive-Curiosity (with minor improvements)
class RIAC():
def __init__(self, mins, maxs, seed=None, params=dict()): # Example --> mins = [-1,-1], maxs = [1,1]
self.seed = seed
if not seed:
self.seed = np.random.randint(42, 424242)
np.random.seed(self.seed)
self.mins = np.array(mins)
self.maxs = np.array(maxs)
# Maximal number of (task, reward) pairs a region can hold before splitting
self.maxlen = 200 if "max_region_size" not in params else params['max_region_size']
self.alp_window = self.maxlen if "alp_window_size" not in params else params['alp_window_size']
# Initialize Regions' tree
self.tree = Tree()
self.regions_bounds = [Box(self.mins, self.maxs, dtype=np.float32)]
self.regions_alp = [0.]
self.tree.create_node('root', 'root',
data=Region(maxlen=self.maxlen,
r_t_pairs=[deque(maxlen=self.maxlen + 1), deque(maxlen=self.maxlen + 1)],
bounds=self.regions_bounds[-1], alp=self.regions_alp[-1]))
self.nb_dims = len(mins)
self.nb_split_attempts = 50 if "nb_split_attempts" not in params else params['nb_split_attempts']
# Whether task sampling uses parent and child regions (False) or only child regions (True)
self.sampling_in_leaves_only = False if "sampling_in_leaves_only" not in params else params["sampling_in_leaves_only"]
# Additional tricks to original RIAC, enforcing splitting rules
# 1 - Minimum population required for both children when splitting --> set to 1 to cancel
self.minlen = self.maxlen / 20 if "min_reg_size" not in params else params['min_reg_size']
# 2 - minimum children region size (compared to initial range of each dimension)
# Set min_dims_range_ratio to 1/np.inf to cancel
self.dims_ranges = self.maxs - self.mins
self.min_dims_range_ratio = 1/15 if "min_dims_range_ratio" not in params else params["min_dims_range_ratio"]
# 3 - If after nb_split_attempts, no split is valid, flush oldest points of parent region
# If 1- and 2- are canceled, this will be canceled since any split will be valid
self.discard_ratio = 1/4 if "discard_ratio" not in params else params["discard_ratio"]
# book-keeping
self.sampled_tasks = []
self.all_boxes = []
self.all_alps = []
self.update_nb = -1
self.split_iterations = []
self.hyperparams = locals()
def compute_alp(self, sub_region):
if len(sub_region[0]) > 2:
cp_window = min(len(sub_region[0]), self.alp_window) # not completely window
half = int(cp_window / 2)
# print(str(cp_window) + 'and' + str(half))
first_half = np.array(sub_region[0])[-cp_window:-half]
snd_half = np.array(sub_region[0])[-half:]
diff = first_half.mean() - snd_half.mean()
cp = np.abs(diff)
else:
cp = 0
alp = np.abs(cp)
return alp
def split(self, nid):
# Try nb_split_attempts splits on region corresponding to node <nid>
reg = self.tree.get_node(nid).data
best_split_score = 0
best_bounds = None
best_sub_regions = None
is_split = False
for i in range(self.nb_split_attempts):
sub_reg1 = [deque(maxlen=self.maxlen + 1), deque(maxlen=self.maxlen + 1)]
sub_reg2 = [deque(maxlen=self.maxlen + 1), deque(maxlen=self.maxlen + 1)]
# repeat until the two sub regions contain at least minlen of the mother region
while len(sub_reg1[0]) < self.minlen or len(sub_reg2[0]) < self.minlen:
# decide on dimension
dim = np.random.choice(range(self.nb_dims))
threshold = reg.bounds.sample()[dim]
bounds1 = Box(reg.bounds.low, reg.bounds.high, dtype=np.float32)
bounds1.high[dim] = threshold
bounds2 = Box(reg.bounds.low, reg.bounds.high, dtype=np.float32)
bounds2.low[dim] = threshold
bounds = [bounds1, bounds2]
valid_bounds = True
if np.any(bounds1.high - bounds1.low < self.dims_ranges * self.min_dims_range_ratio):
valid_bounds = False
if np.any(bounds2.high - bounds2.low < self.dims_ranges * self.min_dims_range_ratio):
valid_bounds = valid_bounds and False
# perform split in sub regions
sub_reg1 = [deque(maxlen=self.maxlen + 1), deque(maxlen=self.maxlen + 1)]
sub_reg2 = [deque(maxlen=self.maxlen + 1), deque(maxlen=self.maxlen + 1)]
for i, task in enumerate(reg.r_t_pairs[1]):
if bounds1.contains(task):
sub_reg1[1].append(task)
sub_reg1[0].append(reg.r_t_pairs[0][i])
else:
sub_reg2[1].append(task)
sub_reg2[0].append(reg.r_t_pairs[0][i])
sub_regions = [sub_reg1, sub_reg2]
# compute alp
alp = [self.compute_alp(sub_reg1), self.compute_alp(sub_reg2)]
# compute score
split_score = len(sub_reg1) * len(sub_reg2) * np.abs(alp[0] - alp[1])
if split_score >= best_split_score and valid_bounds:
is_split = True
best_split_score = split_score
best_sub_regions = sub_regions
best_bounds = bounds
if is_split:
# add new nodes to tree
for i, (r_t_pairs, bounds) in enumerate(zip(best_sub_regions, best_bounds)):
self.tree.create_node(identifier=self.tree.size(), parent=nid,
data=Region(self.maxlen, r_t_pairs=r_t_pairs, bounds=bounds, alp=alp[i]))
else:
assert len(reg.r_t_pairs[0]) == (self.maxlen + 1)
reg.r_t_pairs[0] = deque(islice(reg.r_t_pairs[0], int(self.maxlen * self.discard_ratio), self.maxlen + 1))
reg.r_t_pairs[1] = deque(islice(reg.r_t_pairs[1], int(self.maxlen * self.discard_ratio), self.maxlen + 1))
return is_split
def add_task_reward(self, node, task, reward):
reg = node.data
nid = node.identifier
if reg.bounds.contains(task): # task falls within region
self.nodes_to_recompute.append(nid)
children = self.tree.children(nid)
for n in children: # if task in region, task is in one sub-region
self.add_task_reward(n, task, reward)
need_split = reg.add(task, reward, children == []) # COPY ALL MODE
if need_split:
self.nodes_to_split.append(nid)
def update(self, task, reward):
self.update_nb += 1
# Add new (task, reward) to regions nodes
self.nodes_to_split = []
self.nodes_to_recompute = []
new_split = False
root = self.tree.get_node('root')
self.add_task_reward(root, task, reward) # Will update self.nodes_to_split if needed
assert len(self.nodes_to_split) <= 1
# Split a node if needed
need_split = len(self.nodes_to_split) == 1
if need_split:
new_split = self.split(self.nodes_to_split[0]) # Execute the split
if new_split:
# Update list of regions_bounds
if self.sampling_in_leaves_only:
self.regions_bounds = [n.data.bounds for n in self.tree.leaves()]
else:
self.regions_bounds = [n.data.bounds for n in self.tree.all_nodes()]
# Recompute ALPs of modified nodes
for nid in self.nodes_to_recompute:
node = self.tree.get_node(nid)
reg = node.data
reg.alp = self.compute_alp(reg.r_t_pairs)
# Collect regions data (regions' ALP and regions' (task, reward) pairs)
all_nodes = self.tree.all_nodes() if not self.sampling_in_leaves_only else self.tree.leaves()
self.regions_alp = []
self.r_t_pairs = []
for n in all_nodes:
self.regions_alp.append(n.data.alp)
self.r_t_pairs.append(n.data.r_t_pairs)
# Book-keeping
if new_split:
self.all_boxes.append(copy.copy(self.regions_bounds))
self.all_alps.append(copy.copy(self.regions_alp))
self.split_iterations.append(self.update_nb)
assert len(self.regions_alp) == len(self.regions_bounds)
return new_split, None
def sample_random_task(self):
return self.regions_bounds[0].sample() # First region is root region
def sample_task(self):
mode = np.random.rand()
if mode < 0.1: # "mode 3" (10%) -> sample on regions and then mutate lowest-performing task in region
if len(self.sampled_tasks) == 0:
self.sampled_tasks.append(self.sample_random_task())
else:
# 1 - Sample region proportionally to its ALP
region_id = proportional_choice(self.regions_alp, eps=0.0)
# 2 - Retrieve (task, reward) pair with lowest reward
worst_task_idx = np.argmin(self.r_t_pairs[region_id][0])
# 3 - Mutate task by a small amount (using Gaussian centered on task, with 0.1 std)
task = np.random.normal(self.r_t_pairs[region_id][1][worst_task_idx].copy(), 0.1)
# clip to stay within region (add small epsilon to avoid falling in multiple regions)
task = np.clip(task, self.regions_bounds[region_id].low + 1e-5, self.regions_bounds[region_id].high - 1e-5)
self.sampled_tasks.append(task)
elif mode < 0.3: # "mode 2" (20%) -> random task
self.sampled_tasks.append(self.sample_random_task())
else: # "mode 1" (70%) -> proportional sampling on regions based on ALP and then random task in selected region
region_id = proportional_choice(self.regions_alp, eps=0.0)
self.sampled_tasks.append(self.regions_bounds[region_id].sample())
return self.sampled_tasks[-1].astype(np.float32)
def dump(self, dump_dict):
dump_dict['all_boxes'] = self.all_boxes
dump_dict['split_iterations'] = self.split_iterations
dump_dict['all_alps'] = self.all_alps
dump_dict['riac_params'] = self.hyperparams
return dump_dict
@property
def nb_regions(self):
return len(self.regions_bounds)
@property
def get_regions(self):
return self.regions_bounds | dcd-main | teachDeepRL/teachers/algos/riac.py |
# Copyright (c) 2020 Flowers Team
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
from sklearn.mixture import GaussianMixture as GMM
import numpy as np
from gym.spaces import Box
def proportional_choice(v, eps=0.):
if np.sum(v) == 0 or np.random.rand() < eps:
return np.random.randint(np.size(v))
else:
probas = np.array(v) / np.sum(v)
return np.where(np.random.multinomial(1, probas) == 1)[0][0]
# Implementation of IGMM (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3893575/) + minor improvements
class CovarGMM():
def __init__(self, mins, maxs, seed=None, params=dict()):
self.seed = seed
if not seed:
self.seed = np.random.randint(42,424242)
np.random.seed(self.seed)
# Task space boundaries
self.mins = np.array(mins)
self.maxs = np.array(maxs)
# Range of number of Gaussians to try when fitting the GMM
self.potential_ks = np.arange(2, 11, 1) if "potential_ks" not in params else params["potential_ks"]
# Ratio of randomly sampled tasks VS tasks sampling using GMM
self.random_task_ratio = 0.2 if "random_task_ratio" not in params else params["random_task_ratio"]
self.random_task_generator = Box(self.mins, self.maxs, dtype=np.float32)
# Number of episodes between two fit of the GMM
self.fit_rate = 250 if "fit_rate" not in params else params['fit_rate']
self.nb_random = self.fit_rate # Number of bootstrapping episodes
# Original version do not use Absolute LP, only LP.
self.absolute_lp = False if "absolute_lp" not in params else params['absolute_lp']
self.tasks = []
self.tasks_times_rewards = []
self.all_times = np.arange(0, 1, 1/self.fit_rate)
# boring book-keeping
self.bk = {'weights': [], 'covariances': [], 'means': [], 'tasks_lps': [], 'episodes': []}
def update(self, task, reward):
# Compute time of task, relative to position in current batch of tasks
current_time = self.all_times[len(self.tasks) % self.fit_rate]
self.tasks.append(task)
# Concatenate task with its corresponding time and reward
self.tasks_times_rewards.append(np.array(task.tolist() + [current_time] + [reward]))
if len(self.tasks) >= self.nb_random: # If initial bootstrapping is done
if (len(self.tasks) % self.fit_rate) == 0: # Time to fit
# 1 - Retrieve last <fit_rate> (task, time, reward) triplets
cur_tasks_times_rewards = np.array(self.tasks_times_rewards[-self.fit_rate:])
# 2 - Fit batch of GMMs with varying number of Gaussians
potential_gmms = [GMM(n_components=k, covariance_type='full') for k in self.potential_ks]
potential_gmms = [g.fit(cur_tasks_times_rewards) for g in potential_gmms]
# 3 - Compute fitness and keep best GMM
aics = [m.aic(cur_tasks_times_rewards) for m in potential_gmms]
self.gmm = potential_gmms[np.argmin(aics)]
# book-keeping
self.bk['weights'].append(self.gmm.weights_.copy())
self.bk['covariances'].append(self.gmm.covariances_.copy())
self.bk['means'].append(self.gmm.means_.copy())
self.bk['tasks_lps'] = self.tasks_times_rewards
self.bk['episodes'].append(len(self.tasks))
def sample_task(self):
if (len(self.tasks) < self.nb_random) or (np.random.random() < self.random_task_ratio):
# Random task sampling
new_task = self.random_task_generator.sample()
else:
# Task sampling based on positive time-reward covariance
# 1 - Retrieve positive time-reward covariance for each Gaussian
self.times_rewards_covars = []
for pos, covar, w in zip(self.gmm.means_, self.gmm.covariances_, self.gmm.weights_):
if self.absolute_lp:
self.times_rewards_covars.append(np.abs(covar[-2,-1]))
else:
self.times_rewards_covars.append(max(0, covar[-2, -1]))
# 2 - Sample Gaussian according to its Learning Progress, defined as positive time-reward covariance
idx = proportional_choice(self.times_rewards_covars, eps=0.0)
# 3 - Sample task in Gaussian, without forgetting to remove time and reward dimension
new_task = np.random.multivariate_normal(self.gmm.means_[idx], self.gmm.covariances_[idx])[:-2]
new_task = np.clip(new_task, self.mins, self.maxs).astype(np.float32)
return new_task
def dump(self, dump_dict):
dump_dict.update(self.bk)
return dump_dict | dcd-main | teachDeepRL/teachers/algos/covar_gmm.py |
# Copyright (c) 2020 Flowers Team
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
from sklearn.mixture import GaussianMixture as GMM
import numpy as np
from gym.spaces import Box
from teachDeepRL.teachers.utils.dataset import BufferedDataset
def proportional_choice(v, eps=0.):
if np.sum(v) == 0 or np.random.rand() < eps:
return np.random.randint(np.size(v))
else:
probas = np.array(v) / np.sum(v)
return np.where(np.random.multinomial(1, probas) == 1)[0][0]
# Absolute Learning Progress (ALP) computer object
# It uses a buffered kd-tree to efficiently implement a k-nearest-neighbor algorithm
class EmpiricalALPComputer():
def __init__(self, task_size, max_size=None, buffer_size=500):
self.alp_knn = BufferedDataset(1, task_size, buffer_size=buffer_size, lateness=0, max_size=max_size)
def compute_alp(self, task, reward):
alp = 0
if len(self.alp_knn) > 5:
# Compute absolute learning progress for new task
# 1 - Retrieve closest previous task
dist, idx = self.alp_knn.nn_y(task)
# 2 - Retrieve corresponding reward
closest_previous_task_reward = self.alp_knn.get_x(idx[0])
# 3 - Compute alp as absolute difference in reward
lp = reward - closest_previous_task_reward
alp = np.abs(lp)
# Add to database
self.alp_knn.add_xy(reward, task)
return alp
# Absolute Learning Progress - Gaussian Mixture Model
# mins / maxs are vectors defining task space boundaries (ex: mins=[0,0,0] maxs=[1,1,1])
class ALPGMM():
def __init__(self, mins, maxs, seed=None, params=dict()):
self.seed = seed
if not seed:
self.seed = np.random.randint(42,424242)
np.random.seed(self.seed)
# Task space boundaries
self.mins = np.array(mins)
self.maxs = np.array(maxs)
# Range of number of Gaussians to try when fitting the GMM
self.potential_ks = np.arange(2,21,1) if "potential_ks" not in params else params["potential_ks"]
# Restart new fit by initializing with last fit
self.warm_start = False if "warm_start" not in params else params["warm_start"]
# Fitness criterion when selecting best GMM among range of GMMs varying in number of Gaussians.
self.gmm_fitness_fun = "aic" if "gmm_fitness_fun" not in params else params["gmm_fitness_fun"]
# Number of Expectation-Maximization trials when fitting
self.nb_em_init = 1 if "nb_em_init" not in params else params['nb_em_init']
# Number of episodes between two fit of the GMM
self.fit_rate = 250 if "fit_rate" not in params else params['fit_rate']
self.nb_random = self.fit_rate # Number of bootstrapping episodes
# Ratio of randomly sampled tasks VS tasks sampling using GMM
self.random_task_ratio = 0.2 if "random_task_ratio" not in params else params["random_task_ratio"]
self.random_task_generator = Box(self.mins, self.maxs, dtype=np.float32)
# Maximal number of episodes to account for when computing ALP
alp_max_size = None if "alp_max_size" not in params else params["alp_max_size"]
alp_buffer_size = 500 if "alp_buffer_size" not in params else params["alp_buffer_size"]
# Init ALP computer
self.alp_computer = EmpiricalALPComputer(len(mins), max_size=alp_max_size, buffer_size=alp_buffer_size)
self.tasks = []
self.alps = []
self.tasks_alps = []
# Init GMMs
self.potential_gmms = [self.init_gmm(k) for k in self.potential_ks]
self.gmm = None
# Boring book-keeping
self.bk = {'weights': [], 'covariances': [], 'means': [], 'tasks_alps': [], 'episodes': []}
def init_gmm(self, nb_gaussians):
return GMM(n_components=nb_gaussians, covariance_type='full', random_state=self.seed,
warm_start=self.warm_start, n_init=self.nb_em_init)
def get_nb_gmm_params(self, gmm):
# assumes full covariance
# see https://stats.stackexchange.com/questions/229293/the-number-of-parameters-in-gaussian-mixture-model
nb_gmms = gmm.get_params()['n_components']
d = len(self.mins)
params_per_gmm = (d*d - d)/2 + 2*d + 1
return nb_gmms * params_per_gmm - 1
def update(self, task, reward):
self.tasks.append(task)
# Compute corresponding ALP
self.alps.append(self.alp_computer.compute_alp(task, reward))
# Concatenate task vector with ALP dimension
self.tasks_alps.append(np.array(task.tolist() + [self.alps[-1]]))
if len(self.tasks) >= self.nb_random: # If initial bootstrapping is done
if (len(self.tasks) % self.fit_rate) == 0: # Time to fit
# 1 - Retrieve last <fit_rate> (task, reward) pairs
cur_tasks_alps = np.array(self.tasks_alps[-self.fit_rate:])
# 2 - Fit batch of GMMs with varying number of Gaussians
# self.potential_gmms = [g.fit(cur_tasks_alps) for g in self.potential_gmms] .... this is very buggy
potentials = []
for g in self.potential_gmms:
try:
g.fit(cur_tasks_alps)
potentials.append(g)
except FloatingPointError:
pass
self.potential_gmms = potentials
# 3 - Compute fitness and keep best GMM
fitnesses = []
if self.gmm_fitness_fun == 'bic':
fitnesses = [m.bic(cur_tasks_alps) for m in self.potential_gmms]
# Bayesian Information Criterion
elif self.gmm_fitness_fun == 'aic': # Akaike Information Criterion
fitnesses = [m.aic(cur_tasks_alps) for m in self.potential_gmms]
elif self.gmm_fitness_fun == 'aicc': # Modified AIC
n = self.fit_rate
fitnesses = []
for l, m in enumerate(self.potential_gmms):
k = self.get_nb_gmm_params(m)
penalty = (2*k*(k+1)) / (n-k-1)
fitnesses.append(m.aic(cur_tasks_alps) + penalty)
else:
raise NotImplementedError
exit(1)
if len(fitnesses)> 0:
self.gmm = self.potential_gmms[np.argmin(fitnesses)]
else:
self.gmm = None
print("GMM issues", flush=True)
def sample_task(self):
if (len(self.tasks) < self.nb_random) or (np.random.random() < self.random_task_ratio) or (not self.gmm):
# Random task sampling
new_task = self.random_task_generator.sample()
else:
# ALP-based task sampling
# 1 - Retrieve the mean ALP value of each Gaussian in the GMM
self.alp_means = []
for pos, _, w in zip(self.gmm.means_, self.gmm.covariances_, self.gmm.weights_):
self.alp_means.append(pos[-1])
# 2 - Sample Gaussian proportionally to its mean ALP
idx = proportional_choice(self.alp_means, eps=0.0)
# 3 - Sample task in Gaussian, without forgetting to remove ALP dimension
try:
new_task = np.random.multivariate_normal(self.gmm.means_[idx], self.gmm.covariances_[idx])[:-1]
except:
import pdb; pdb.set_trace()
new_task = np.clip(new_task, self.mins, self.maxs).astype(np.float32)
return new_task
def dump(self, dump_dict):
dump_dict.update(self.bk)
return dump_dict | dcd-main | teachDeepRL/teachers/algos/alp_gmm.py |
dcd-main | teachDeepRL/teachers/algos/__init__.py |
|
# Copyright (c) 2020 Flowers Team
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
import numpy as np
from gym.spaces import Box
class RandomTeacher():
def __init__(self, mins, maxs, seed=None):
self.seed = seed
if not seed:
self.seed = np.random.randint(42,424242)
np.random.seed(self.seed)
self.mins = mins
self.maxs = maxs
self.random_task_generator = Box(np.array(mins), np.array(maxs), dtype=np.float32)
def update(self, task, competence):
pass
def sample_task(self):
return self.random_task_generator.sample()
def dump(self, dump_dict):
return dump_dict | dcd-main | teachDeepRL/teachers/algos/random_teacher.py |
# Copyright (c) 2020 Flowers Team
#
# Licensed under the MIT License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
import numpy as np
from gym.spaces import Box
from collections import deque
class OracleTeacher():
def __init__(self, mins, maxs, window_step_vector,
seed=None, reward_thr=230, step_rate=50):
self.seed = seed
if not seed:
self.seed = np.random.randint(42,424242)
np.random.seed(self.seed)
self.mins = np.array(mins, dtype=np.float32)
self.maxs = np.array(maxs, dtype=np.float32)
self.window_step_vector = window_step_vector
self.reward_thr = reward_thr
self.step_rate = step_rate
self.window_range = (self.maxs - self.mins) / 6
self.window_pos = np.zeros(len(self.mins), dtype=np.float32) # stores bottom left point of window
for i, step in enumerate(self.window_step_vector):
if step > 0: # if step is positive, we go from min to max (and thus start at min)
self.window_pos[i] = self.mins[i]
else: # if step is negative, we go from max to min (and thus start at max - window_range)
self.window_pos[i] = self.maxs[i] - self.window_range[i]
self.train_rewards = []
print("window range:{} \n position:{}\n step:{}\n"
.format(self.window_range, self.window_pos, self.window_step_vector))
def update(self, task, reward):
self.train_rewards.append(reward)
if len(self.train_rewards) == self.step_rate:
mean_reward = np.mean(self.train_rewards)
self.train_rewards = []
if mean_reward > self.reward_thr:
for i,step in enumerate(self.window_step_vector):
if step > 0: # check if not stepping over max
self.window_pos[i] = min(self.window_pos[i] + step, self.maxs[i] - self.window_range[i])
elif step <= 0: # check if not stepping below min
self.window_pos[i] = max(self.window_pos[i] + step, self.mins[i])
print('mut stump: mean_ret:{} window_pos:({})'.format(mean_reward, self.window_pos))
def sample_task(self):
task = np.random.uniform(self.window_pos, self.window_pos+self.window_range).astype(np.float32)
#print(task)
return task
def dump(self, dump_dict):
return dump_dict | dcd-main | teachDeepRL/teachers/algos/oracle_teacher.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from setuptools import find_packages, setup
"""
Core library deps
Version requirements
* scipy<=1.9.2: Required by glmnet-python
* pandas<=1.4.3: 1.5.0 moved UndefinedVariableError into pandas.errors
Other requirements:
* [email protected], from https://github.com/bbalasub1/glmnet_python.git
"""
REQUIRES = [
"numpy",
"pandas<=1.4.3",
"ipython",
"scipy<=1.9.2",
"patsy",
"seaborn<=0.13",
"plotly",
"matplotlib",
"statsmodels",
"scikit-learn",
"ipfn",
"session-info",
]
# Development deps (e.g. pytest, builds)
# TODO[scubasteve]: Add dev requirements
DEV_REQUIRES = [
"setuptools_scm",
"wheel",
"pytest",
"sphinx",
"notebook",
"nbconvert",
]
DESCRIPTION = (
"balance is a Python package offering a simple workflow and methods for "
"dealing with biased data samples when looking to infer from them to "
"some target population of interest."
)
def setup_package() -> None:
"""Used for building/installing the balance package."""
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="balance",
description=DESCRIPTION,
author="Facebook, Inc.",
license="GPLv2",
url="https://github.com/facebookresearch/balance",
keywords=[""],
long_description=long_description,
long_description_content_type="text/markdown",
python_requires=">=3.7",
install_requires=REQUIRES,
packages=find_packages(include=["balance*"]),
# Include all csv files
package_data={"": ["*.csv"]},
extras_require={
"dev": DEV_REQUIRES,
},
use_scm_version={
"write_to": "version.py",
},
setup_requires=["setuptools_scm"],
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"License :: OSI Approved :: GNU General Public License v2 (GPLv2)",
],
)
if __name__ == "__main__":
setup_package()
| balance-main | setup.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import balance
import balance.testutil
class TestBalanceSetWarnings(balance.testutil.BalanceTestCase):
def test_balance_set_warnings(self):
logger = logging.getLogger(__package__)
balance.set_warnings("WARNING")
self.assertNotWarns(logger.debug, "test_message")
balance.set_warnings("DEBUG")
self.assertWarnsRegexp("test_message", logger.debug, "test_message")
self.assertWarnsRegexp("test_message", logger.warning, "test_message")
balance.set_warnings("WARNING")
self.assertWarnsRegexp("test_message", logger.warning, "test_message")
self.assertNotWarns(logger.debug, "test_message")
| balance-main | tests/test_logging.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import balance.testutil
import numpy as np
from balance.datasets import load_data
class TestDatasets(
balance.testutil.BalanceTestCase,
):
def test_load_data(self):
target_df, sample_df = load_data()
self.assertEqual(sample_df.shape, (1000, 5))
self.assertEqual(target_df.shape, (10000, 5))
self.assertEqual(
target_df.columns.to_numpy().tolist(),
["id", "gender", "age_group", "income", "happiness"],
)
self.assertEqual(
sample_df.columns.to_numpy().tolist(),
["id", "gender", "age_group", "income", "happiness"],
)
o = sample_df.head().round(2).to_dict()
e = {
"id": {0: "0", 1: "1", 2: "2", 3: "3", 4: "4"},
"gender": {0: "Male", 1: "Female", 2: "Male", 3: np.nan, 4: np.nan},
"age_group": {0: "25-34", 1: "18-24", 2: "18-24", 3: "18-24", 4: "18-24"},
"income": {0: 6.43, 1: 9.94, 2: 2.67, 3: 10.55, 4: 2.69},
"happiness": {0: 26.04, 1: 66.89, 2: 37.09, 3: 49.39, 4: 72.3},
}
self.assertEqual(o.__str__(), e.__str__())
# NOTE: using .__str__() since doing o==e will give False
o = target_df.head().round(2).to_dict()
e = {
"id": {0: "100000", 1: "100001", 2: "100002", 3: "100003", 4: "100004"},
"gender": {0: "Male", 1: "Male", 2: "Male", 3: np.nan, 4: np.nan},
"age_group": {0: "45+", 1: "45+", 2: "35-44", 3: "45+", 4: "25-34"},
"income": {0: 10.18, 1: 6.04, 2: 5.23, 3: 5.75, 4: 4.84},
"happiness": {0: 61.71, 1: 79.12, 2: 44.21, 3: 83.99, 4: 49.34},
}
self.assertEqual(o.__str__(), e.__str__())
def test_load_data_cbps(self):
target_df, sample_df = load_data("sim_data_cbps")
self.assertEqual(sample_df.shape, (246, 7))
self.assertEqual(target_df.shape, (254, 7))
self.assertEqual(
target_df.columns.to_numpy().tolist(),
["X1", "X2", "X3", "X4", "cbps_weights", "y", "id"],
)
self.assertEqual(
sample_df.columns.to_numpy().tolist(),
target_df.columns.to_numpy().tolist(),
)
o = sample_df.head().round(2).to_dict()
e = {
"X1": {0: 1.07, 2: 0.69, 4: 0.5, 5: 1.52, 6: 1.03},
"X2": {0: 10.32, 2: 10.65, 4: 9.59, 5: 10.03, 6: 9.79},
"X3": {0: 0.21, 2: 0.22, 4: 0.23, 5: 0.33, 6: 0.22},
"X4": {0: 463.28, 2: 424.29, 4: 472.85, 5: 438.38, 6: 436.39},
"cbps_weights": {0: 0.01, 2: 0.01, 4: 0.01, 5: 0.0, 6: 0.0},
"y": {0: 227.53, 2: 196.89, 4: 191.3, 5: 280.45, 6: 227.07},
"id": {0: 1, 2: 3, 4: 5, 5: 6, 6: 7},
}
self.assertEqual(o.__str__(), e.__str__())
# NOTE: using .__str__() since doing o==e will give False
o = target_df.head().round(2).to_dict()
e = {
"X1": {1: 0.72, 3: 0.35, 11: 0.69, 12: 0.78, 13: 0.82},
"X2": {1: 9.91, 3: 9.91, 11: 10.73, 12: 9.56, 13: 9.8},
"X3": {1: 0.19, 3: 0.1, 11: 0.21, 12: 0.18, 13: 0.21},
"X4": {1: 383.76, 3: 399.37, 11: 398.31, 12: 370.18, 13: 434.45},
"cbps_weights": {1: 0.0, 3: 0.0, 11: 0.0, 12: 0.0, 13: 0.0},
"y": {1: 199.82, 3: 174.69, 11: 189.58, 12: 208.18, 13: 214.28},
"id": {1: 2, 3: 4, 11: 12, 12: 13, 13: 14},
}
self.assertEqual(o.__str__(), e.__str__())
| balance-main | tests/test_datasets.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import balance.testutil
import numpy as np
import pandas as pd
import scipy
from balance.datasets import load_data
from balance.sample_class import Sample
from balance.stats_and_plots.weights_stats import design_effect
from balance.weighting_methods import cbps as balance_cbps
class Testcbps(
balance.testutil.BalanceTestCase,
):
def test_cbps_from_adjust_function(self):
sample = Sample.from_frame(
pd.DataFrame({"a": (1, 2, 3, 4, 5, 6, 7, 8, 9, 1), "id": range(0, 10)})
)
target = Sample.from_frame(
pd.DataFrame({"a": (1, 2, 3, 4, 5, 6, 7, 8, 9, 9), "id": range(0, 10)})
)
sample = sample.set_target(target)
result_adjust = sample.adjust(method="cbps", transformations=None)
sample_df = pd.DataFrame({"a": (1, 2, 3, 4, 5, 6, 7, 8, 9, 1)})
target_df = pd.DataFrame({"a": (1, 2, 3, 4, 5, 6, 7, 8, 9, 9)})
sample_weights = pd.Series((1,) * 10)
target_weights = pd.Series((1,) * 10)
result_cbps = balance_cbps.cbps(
sample_df, sample_weights, target_df, target_weights, transformations=None
)
self.assertEqual(
result_adjust.df["weight"], result_cbps["weight"].rename("weight")
)
def test_logit_truncated(self):
X = np.array([[1, 2, 3], [4, 5, 6], [0, 0, -100]])
beta = np.array([1, 0.5, 1])
result = balance_cbps.logit_truncated(X, beta)
self.assertEqual(
np.around(result, 6), np.array([0.993307, 0.99999, 1.00000000e-05])
)
# test truncation_value
X = np.array([[1, 2, 3], [4, 5, 6], [0, 0, -100]])
beta = np.array([1, 0.5, 1])
result = balance_cbps.logit_truncated(X, beta, truncation_value=0.1)
self.assertEqual(np.around(result, 6), np.array([0.9, 0.9, 0.1]))
def test_compute_pseudo_weights_from_logit_probs(self):
probs = np.array([0.1, 0.6, 0.2])
design_weights = np.array([1, 8, 3])
in_pop = np.array([1.0, 0, 1.0])
result = balance_cbps.compute_pseudo_weights_from_logit_probs(
probs, design_weights, in_pop
)
self.assertEqual(np.around(result, 1), np.array([3.0, -4.5, 3.0]))
# Testing consistency result of bal_loss
def test_bal_loss(self):
X = np.array([[1, 2, 3], [4, 5, 6], [0, 0, -100]])
beta = np.array([1, 0.5, 1])
design_weights = np.array([1, 8, 3])
in_pop = np.array([1.0, 0, 1.0])
XtXinv = np.linalg.inv(np.matmul(X.T, X))
result = balance_cbps.bal_loss(beta, X, design_weights, in_pop, XtXinv)
self.assertEqual(round(result, 2), 39999200004.99)
# Testing consistency result of gmm_function
def test_gmm_function(self):
X = np.array([[1, 2, 3], [4, 5, 6], [0, 0, -100]])
beta = np.array([1, 0.5, 1])
design_weights = np.array([1, 8, 3])
in_pop = np.array([1.0, 0, 1.0])
result = balance_cbps.gmm_function(beta, X, design_weights, in_pop)
self.assertEqual(round(result["loss"], 2), 91665.75)
# with given invV
X = np.array([[1, 2], [4, 5], [0, -100]])
beta = np.array([1, 0.5])
design_weights = np.array([1, 8, 3])
in_pop = np.array([1.0, 0, 1.0])
invV = np.array([[1, 1, 1, 1], [2, 2, 2, 2], [1, 0, 0, 0], [0, 0, 0, 1]])
result = balance_cbps.gmm_function(beta, X, design_weights, in_pop, invV)
self.assertEqual(round(result["loss"], 4), 45967903.9923)
self.assertEqual(result["invV"], invV)
# Testing consistency result of gmm_loss
def test_gmm_loss(self):
X = np.array([[1, 2, 3], [4, 5, 6], [0, 0, -100]])
beta = np.array([1, 0.5, 1])
design_weights = np.array([1, 8, 3])
in_pop = np.array([1.0, 0, 1.0])
result = balance_cbps.gmm_loss(beta, X, design_weights, in_pop)
self.assertEqual(round(result, 2), 91665.75)
# with given invV
X = np.array([[1, 2], [4, 5], [0, -100]])
beta = np.array([1, 0.5])
design_weights = np.array([1, 8, 3])
in_pop = np.array([1.0, 0, 1.0])
invV = np.array([[1, 1, 1, 1], [2, 2, 2, 2], [1, 0, 0, 0], [0, 0, 0, 1]])
result = balance_cbps.gmm_loss(beta, X, design_weights, in_pop, invV)
self.assertEqual(round(result, 4), 45967903.9923)
# Testing consistency result of alpha_function
def test_alpha_function(self):
X = np.array([[1, 2, 3], [4, 5, 6], [0, 0, -100]])
beta = np.array([1, 0.5, 1])
design_weights = np.array([1, 8, 3])
in_pop = np.array([1.0, 0, 1.0])
alpha = 1
result = balance_cbps.alpha_function(alpha, beta, X, design_weights, in_pop)
self.assertEqual(result, balance_cbps.gmm_loss(beta, X, design_weights, in_pop))
X = np.array([[1, 2, 3], [4, 5, 6], [0, 0, -100]])
beta = np.array([1, 0.5, 1])
design_weights = np.array([1, 8, 3])
in_pop = np.array([1.0, 0, 1.0])
alpha = 0.5
result_smaller_alpha = balance_cbps.alpha_function(
alpha, beta, X, design_weights, in_pop
)
self.assertEqual(round(result_smaller_alpha, 4), 25345.0987)
# smaller alpha gives smaller loss
self.assertTrue(result_smaller_alpha <= result)
# Testing consistency result of compute_deff_from_beta function
def test_compute_deff_from_beta(self):
X = np.array([[1, 2, 3], [4, 5, 6], [0, 0, -100]])
beta = np.array([1, 0.5, 1])
design_weights = np.array([1, 8, 3])
in_pop = np.array([0.0, 0, 1.0])
result = balance_cbps.compute_deff_from_beta(X, beta, design_weights, in_pop)
self.assertEqual(round(result, 6), 1.999258)
def test__standardize_model_matrix(self):
# numpy array as input
mat = np.array([[1, 2], [3, 4]])
res = balance_cbps._standardize_model_matrix(mat, ["a", "b"])
self.assertEqual(res["model_matrix"], np.array([[-1.0, -1.0], [1.0, 1.0]]))
self.assertEqual(res["model_matrix_columns_names"], ["a", "b"])
self.assertEqual(res["model_matrix_mean"], np.array([2.0, 3.0]))
self.assertEqual(res["model_matrix_std"], np.array([1.0, 1.0]))
# check when column is constant
mat = np.array([[1, 2], [1, 4]])
res = balance_cbps._standardize_model_matrix(mat, ["a", "b"])
self.assertEqual(res["model_matrix"], np.array([[-1.0], [1.0]]))
self.assertEqual(res["model_matrix_columns_names"], ["b"])
self.assertEqual(res["model_matrix_mean"], np.array([3.0]))
self.assertEqual(res["model_matrix_std"], np.array([1.0]))
# pandas dataframe as input
mat = pd.DataFrame({"a": (1, 3), "b": (2, 4)}).values
res = balance_cbps._standardize_model_matrix(mat, ["a", "b"])
self.assertEqual(res["model_matrix"], np.array([[-1.0, -1.0], [1.0, 1.0]]))
self.assertEqual(res["model_matrix_columns_names"], ["a", "b"])
self.assertEqual(res["model_matrix_mean"], np.array([2.0, 3.0]))
self.assertEqual(res["model_matrix_std"], np.array([1.0, 1.0]))
# check when column is constant
mat = pd.DataFrame({"a": (1, 1), "b": (2, 4)}).values
res = balance_cbps._standardize_model_matrix(mat, ["a", "b"])
self.assertEqual(res["model_matrix"], np.array([[-1.0], [1.0]]))
self.assertEqual(res["model_matrix_columns_names"], ["b"])
self.assertEqual(res["model_matrix_mean"], np.array([3.0]))
self.assertEqual(res["model_matrix_std"], np.array([1.0]))
# check warnings
self.assertWarnsRegexp(
"The following variables have only one level, and are omitted:",
balance_cbps._standardize_model_matrix,
mat,
["a", "b"],
)
def test__reverse_svd_and_centralization(self):
np.random.seed(10)
m, n = 4, 3
X_matrix = np.random.randn(m, n)
X_matrix_std = np.std(X_matrix, axis=0)
X_matrix_mean = np.mean(X_matrix, axis=0)
X_matrix_new = (X_matrix - X_matrix_mean) / X_matrix_std
X_matrix_new = np.c_[
np.ones(X_matrix_new.shape[0]), X_matrix_new
] # Add intercept
U, s, Vh = scipy.linalg.svd(X_matrix_new, full_matrices=False)
beta = np.array([-5, 1, -2, 3])
self.assertEqual(
np.around(
np.matmul(
np.c_[np.ones(X_matrix.shape[0]), X_matrix],
balance_cbps._reverse_svd_and_centralization(
beta, U, s, Vh, X_matrix_mean, X_matrix_std
),
),
7,
),
np.around(np.matmul(U, beta), 7),
)
# Test consistency result of cbps
def test_cbps_consistency_with_default_arguments(self):
# This test is meant to check the consistency of the cbps function with the default arguments,
# Note that this test rely on all balance functions that are part of cbps:
# choose_variables, apply_transformations, model_matrix, trim_weights
# Therefore a failure in this test may indicate a failure in one
# of these functions as well as a failure of the cbps function
np.random.seed(2021)
n_sample = 1000
n_target = 2000
sample_df = pd.concat(
[
pd.DataFrame(np.random.uniform(0, 10, size=n_sample), columns=[0]),
pd.DataFrame(
np.random.uniform(0, 1, size=(n_sample, 4)), columns=range(1, 5)
),
pd.DataFrame(
np.random.choice(
["level1", "level2", "level3"], size=(n_sample, 5)
),
columns=range(5, 10),
),
],
axis=1,
)
sample_df = sample_df.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
target_df = pd.concat(
[
pd.DataFrame(
np.concatenate(
(
np.random.uniform(0, 8, size=int(n_target / 2)),
np.random.uniform(8, 10, size=int(n_target / 2)),
)
),
columns=[0],
),
pd.DataFrame(
np.random.uniform(0, 1, size=(n_target, 4)), columns=range(1, 5)
),
pd.DataFrame(
np.random.choice(
["level1", "level2", "level3"], size=(n_target, 5)
),
columns=range(5, 10),
),
],
axis=1,
)
target_df = target_df.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
sample_weights = pd.Series(np.random.uniform(0, 1, size=n_sample))
target_weights = pd.Series(np.random.uniform(0, 1, size=n_target))
res = balance_cbps.cbps(sample_df, sample_weights, target_df, target_weights)
# Compare output weights (examples and distribution)
# TODO: The results are not 100% reproducible due to rounding issues in SVD that produce slightly different U:
# http://numpy-discussion.10968.n7.nabble.com/strange-behavior-of-numpy-random-multivariate-normal-ticket-1842-td31547.html
# This results in slightly different optimizations solutions (that might have some randomness in them too).
# self.assertEqual(round(res["weight"][4],4), 4.3932)
# self.assertEqual(round(res["weight"][997],4), 0.7617)
# self.assertEqual(np.around(res["weight"].describe().values,4),
# np.array([1.0000e+03, 1.0167e+00, 1.1340e+00, 3.0000e-04,
# 3.3410e-01, 6.8400e-01, 1.2317e+00, 7.4006e+00]))
self.assertTrue(
res["weight"][995] < res["weight"][999]
) # these are obs with different a value
# Test cbps constraints
def test_cbps_constraints(self):
sample_df = pd.DataFrame({"a": [-20] + [1] * 13 + [10] * 1})
sample_weights = pd.Series((1,) * 15)
target_df = pd.DataFrame({"a": [10] * 10 + [11] * 5})
target_weights = pd.Series((1,) * 15)
unconconstrained_result = balance_cbps.cbps(
sample_df,
sample_weights,
target_df,
target_weights,
transformations=None,
max_de=None,
weight_trimming_mean_ratio=None,
)
# Ensure that example df would produce DE > 1.5 if unconstrained
self.assertTrue(design_effect(unconconstrained_result["weight"]) > 1.5)
# Same data but now with constraint produces desired design effect - for cbps_method = "over"
de_constrained_result = balance_cbps.cbps(
sample_df,
sample_weights,
target_df,
target_weights,
transformations=None,
max_de=1.5,
weight_trimming_mean_ratio=None,
)
self.assertTrue(round(design_effect(de_constrained_result["weight"]), 5) <= 1.5)
# Same data but now with constraint produces desired design effect - for cbps_method = "exact"
de_constrained_result = balance_cbps.cbps(
sample_df,
sample_weights,
target_df,
target_weights,
transformations=None,
max_de=1.5,
weight_trimming_mean_ratio=None,
cbps_method="exact",
)
self.assertTrue(round(design_effect(de_constrained_result["weight"]), 5) <= 1.5)
def test_cbps_weights_order(self):
sample = pd.DataFrame({"a": (1, 2, 3, 4, 5, 6, 7, 9, 1)})
target = pd.DataFrame({"a": (1, 2, 3, 4, 5, 6, 7, 9, 9)})
result = balance_cbps.cbps(
sample_df=sample,
sample_weights=pd.Series((1,) * 9),
target_df=target,
target_weights=pd.Series((1,) * 9),
transformations=None,
)
w = result["weight"].values
self.assertEqual(round(w[0], 10), round(w[8], 10))
self.assertTrue(w[0] < w[1])
self.assertTrue(w[0] < w[7])
def test_cbps_all_weight_identical(self):
# Test the check for identical weights
np.random.seed(1)
n = 1000
sample_df = pd.DataFrame({"a": np.random.normal(0, 1, n).reshape((n,))})
sample_weights = pd.Series((1,) * n)
target_df = sample_df
target_weights = sample_weights
result = balance_cbps.cbps(
sample_df, sample_weights, target_df, target_weights, transformations=None
)
self.assertTrue(np.var(result["weight"]) < 1e-10)
sample = Sample.from_frame(
df=pd.DataFrame(
{"a": np.random.normal(0, 1, n).reshape((n,)), "id": range(0, n)}
),
id_column="id",
)
sample = sample.set_target(sample)
self.assertWarnsRegexp(
"All weights are identical",
sample.adjust,
method="cbps",
transformations=None,
)
def test_cbps_na_drop(self):
s = Sample.from_frame(
pd.DataFrame(
{
"a": np.concatenate(
(np.array([np.nan, np.nan]), np.arange(3, 100))
),
"id": np.arange(1, 100),
}
),
id_column="id",
)
t = Sample.from_frame(
pd.DataFrame(
{
"a": np.concatenate((np.array([np.nan]), np.arange(2, 100))),
"id": np.arange(1, 100),
}
),
id_column="id",
)
self.assertWarnsRegexp(
"Dropped 2/99 rows of sample",
s.adjust,
t,
method="cbps",
na_action="drop",
transformations=None,
)
def test_cbps_input_assertions(self):
s_w = np.array((1))
self.assertRaisesRegex(
TypeError,
"must be a pandas DataFrame",
balance_cbps.cbps,
s_w,
s_w,
s_w,
s_w,
)
s = pd.DataFrame({"a": (1, 2), "id": (1, 2)})
s_w = pd.Series((1,))
self.assertRaisesRegex(
Exception,
"must be the same length",
balance_cbps.cbps,
s,
s_w,
s,
s_w,
)
def test_cbps_dropna_empty(self):
s = pd.DataFrame({"a": (1, None), "b": (np.nan, 2), "id": (1, 2)})
s_w = pd.Series((1, 2))
self.assertRaisesRegex(
Exception,
"Dropping rows led to empty",
balance_cbps.cbps,
s,
s_w,
s,
s_w,
na_action="drop",
)
def test_cbps_formula(self):
sample = pd.DataFrame(
{
"a": (1, 2, 3, 4, 5, 6, 7, 9, 1),
"b": (1, 2, 3, 4, 5, 6, 7, 9, 1),
"c": (1, 2, 3, 4, 5, 6, 7, 9, 1),
}
)
target = pd.DataFrame(
{
"a": (1, 2, 3, 4, 5, 6, 7, 9, 9),
"b": (1, 2, 3, 4, 5, 6, 7, 9, 1),
"c": (1, 2, 3, 4, 5, 6, 7, 9, 1),
}
)
result = balance_cbps.cbps(
sample_df=sample,
sample_weights=pd.Series((1,) * 9),
target_df=target,
target_weights=pd.Series((1,) * 9),
formula="a : b + c",
transformations=None,
)
self.assertEqual(result["model"]["X_matrix_columns"], ["Intercept", "a:b", "c"])
def test_cbps_warning_for_variable_with_one_level(self):
sample = Sample.from_frame(
pd.DataFrame(
{
"a": [-20] + [1] * 13 + [10] * 1,
"b": [1] * 15,
"id": np.arange(0, 15),
}
),
id_column="id",
)
target = Sample.from_frame(
pd.DataFrame(
{
"a": [10] * 10 + [11] * 5,
"b": [1] * 15,
"id": np.arange(0, 15),
}
),
id_column="id",
)
sample = sample.set_target(target)
self.assertWarnsRegexp(
"The following variables have only one level",
sample.adjust,
method="cbps",
transformations=None,
)
def test_cbps_in_balance_vs_r(self):
# TODO: add reference to the tutorial here (once it's online)
# Get data
target_df, sample_df = load_data("sim_data_cbps")
# Place it into Sample objects
sample = Sample.from_frame(sample_df, outcome_columns=["y", "cbps_weights"])
target = Sample.from_frame(target_df, outcome_columns=["y", "cbps_weights"])
sample_target = sample.set_target(target)
# adjust:
adjust = sample_target.adjust(method="cbps", transformations=None)
# Verify balnce's CBPS gives VERY similar results to R's CBPS weights
self.assertTrue(
adjust.df[["cbps_weights", "weight"]].corr(method="pearson").iloc[0, 1]
> 0.98
)
self.assertTrue(
adjust.df[["cbps_weights", "weight"]]
.apply(lambda x: np.log10(x))
.corr(method="pearson")
.iloc[0, 1]
> 0.99
)
| balance-main | tests/test_cbps.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import tempfile
from copy import deepcopy
import balance.testutil
import IPython.display
import numpy as np
import pandas as pd
from balance.sample_class import Sample
# TODO: move s3 and other definitions of sample outside of classes (from example from TestSamplePrivateAPI)
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s4 = Sample.from_frame(
pd.DataFrame(
{"a": (0, None, 2), "b": (0, None, 2), "c": ("a", "b", "c"), "id": (1, 2, 3)}
),
outcome_columns=("b", "c"),
)
class TestSample(
balance.testutil.BalanceTestCase,
):
def test_constructor_not_implemented(self):
with self.assertRaises(NotImplementedError):
s1 = Sample()
print(s1)
def test_Sample__str__(self):
self.assertTrue("4 observations x 3 variables" in s1.__str__())
self.assertTrue("outcome_columns: o" in s1.__str__())
self.assertTrue("weight_column: w" in s1.__str__())
self.assertTrue("outcome_columns: None" in s2.__str__())
self.assertTrue("weight_column: w" in s2.__str__())
s3 = s1.set_target(s2)
self.assertTrue("Sample object with target set" in s3.__str__())
self.assertTrue("target:" in s3.__str__())
self.assertTrue("3 common variables" in s3.__str__())
s4 = s3.adjust(method="null")
self.assertTrue(
"Adjusted balance Sample object with target set using" in s4.__str__()
)
def test_Sample__str__multiple_outcomes(self):
s1 = Sample.from_frame(
pd.DataFrame(
{"a": (1, 2, 3), "b": (4, 6, 8), "id": (1, 2, 3), "w": (0.5, 1, 2)}
),
id_column="id",
weight_column="w",
outcome_columns=("a", "b"),
)
self.assertTrue("outcome_columns: a,b" in s1.__str__())
def test_Sample_from_frame(self):
# test id_column
df = pd.DataFrame({"id": (1, 2), "a": (1, 2)})
self.assertWarnsRegexp(
"Guessed id column name id for the data", Sample.from_frame, df
)
# TODO: add tests for the two other warnings:
# self.assertWarnsRegexp("Casting id column to string", Sample.from_frame, df)
# self.assertWarnsRegexp("No weights passed, setting all weights to 1", Sample.from_frame, df)
# Using the above would fail since the warnings are sent sequentially and using self.assertWarnsRegexp
# only catches the first warning.
self.assertEqual(
Sample.from_frame(df).id_column, pd.Series((1, 2), name="id").astype(str)
)
df = pd.DataFrame({"b": (1, 2), "a": (1, 2)})
self.assertEqual(
Sample.from_frame(df, id_column="b").id_column,
pd.Series((1, 2), name="b").astype(str),
)
with self.assertRaisesRegex(
ValueError,
"Cannot guess id column name for this DataFrame. Please provide a value in id_column",
):
Sample.from_frame(df)
with self.assertRaisesRegex(
ValueError,
"Dataframe does not have column*",
):
Sample.from_frame(df, id_column="c")
# test exception if values in id are null
df = pd.DataFrame({"id": (1, None), "a": (1, 2)})
with self.assertRaisesRegex(
ValueError,
"Null values are not allowed in the id_column",
):
Sample.from_frame(df)
# test check_id_uniqueness argument
df = pd.DataFrame({"id": (1, 2, 2)})
with self.assertRaisesRegex(
ValueError,
"Values in the id_column must be unique",
):
Sample.from_frame(df)
df = pd.DataFrame({"id": (1, 2, 2)})
self.assertEqual(
Sample.from_frame(df, check_id_uniqueness=False).df.id,
pd.Series(("1", "2", "2"), name="id"),
)
# test weights_column
df = pd.DataFrame({"id": (1, 2), "weight": (1, 2)})
self.assertWarnsRegexp("Guessing weight", Sample.from_frame, df)
# NOTE how weight that was integer was changed into floats.
self.assertEqual(
Sample.from_frame(df).weight_column, pd.Series((1.0, 2.0), name="weight")
)
df = pd.DataFrame({"id": (1, 2)})
self.assertWarnsRegexp("No weights passed", Sample.from_frame, df)
# NOTE that the default weights are integers, not floats
# TODO: decide if it's o.k. to keep the default weights be 1s, or change the default to floats
self.assertEqual(
Sample.from_frame(df).weight_column, pd.Series((1, 1), name="weight")
)
# Test type conversion
df = pd.DataFrame({"id": (1, 2), "a": (1, 2)})
self.assertEqual(df.a.dtype.type, np.int64)
self.assertEqual(Sample.from_frame(df).df.a.dtype.type, np.float64)
df = pd.DataFrame({"id": (1, 2), "a": (1, 2)}, dtype=np.int32)
self.assertEqual(df.a.dtype.type, np.int32)
self.assertEqual(Sample.from_frame(df).df.a.dtype.type, np.float32)
df = pd.DataFrame({"id": (1, 2), "a": (1, 2)}, dtype=np.int16)
self.assertEqual(df.a.dtype.type, np.int16)
self.assertEqual(Sample.from_frame(df).df.a.dtype.type, np.float16)
df = pd.DataFrame({"id": (1, 2), "a": (1, 2)}, dtype=np.int8)
self.assertEqual(df.a.dtype.type, np.int8)
self.assertEqual(Sample.from_frame(df).df.a.dtype.type, np.float16)
# TODO: add tests for other types of conversions
# Test use_deepcopy
# after we invoked Sample.from_frame with use_deepcopy=False, we expect the dtype of id to be np.object_
# in BOTH the df inside sample and the ORIGINAL df:
df = pd.DataFrame({"id": (1, 2), "a": (1, 2)})
self.assertEqual(df.id.dtype.type, np.int64)
self.assertEqual(
Sample.from_frame(df, use_deepcopy=False).df.id.dtype.type, np.object_
)
self.assertEqual(df.id.dtype.type, np.object_)
# after we invoked Sample.from_frame with use_deepcopy=True (default), we expect the dtype of id to be object_
# in the df inside sample, but id in the ORIGINAL df to remain int64:
df = pd.DataFrame({"id": (1, 2), "a": (1, 2)})
self.assertEqual(df.id.dtype.type, np.int64)
self.assertEqual(Sample.from_frame(df).df.id.dtype.type, np.object_)
self.assertEqual(df.id.dtype.type, np.int64)
def test_Sample_adjust(self):
from balance.weighting_methods.adjust_null import adjust_null
s3 = s1.set_target(s2).adjust(method="null")
self.assertTrue(s3.is_adjusted())
s3 = s1.set_target(s2).adjust(method=adjust_null)
self.assertTrue(s3.is_adjusted())
# test exception
with self.assertRaisesRegex(
ValueError,
"Method should be one of existing weighting methods",
):
s1.set_target(s2).adjust(method=None)
class TestSample_base_and_adjust_methods(
balance.testutil.BalanceTestCase,
):
def test_Sample_df(self):
# NOTE how integers were changed into floats.
e = pd.DataFrame(
{
"a": (1.0, 2.0, 3.0, 1.0),
"b": (-42.0, 8.0, 2.0, -42.0),
"o": (7.0, 8.0, 9.0, 10.0),
"c": ("x", "y", "z", "v"),
"id": ("1", "2", "3", "4"),
"w": (0.5, 2, 1, 1),
},
columns=("id", "a", "b", "c", "o", "w"),
)
# Verify we get the expected output:
self.assertEqual(s1.df, e)
# Check that @property works:
self.assertTrue(isinstance(Sample.df, property))
self.assertEqual(Sample.df.fget(s1), s1.df)
# We can no longer call .df() as if it was a function:
with self.assertRaisesRegex(TypeError, "'DataFrame' object is not callable"):
s1.df()
# NOTE how integers were changed into floats.
e = pd.DataFrame(
{
"a": (1.0, 2.0, 3.0),
"b": (4.0, 6.0, 8.0),
"id": ("1", "2", "3"),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
},
columns=("id", "a", "b", "c", "w"),
)
self.assertEqual(s2.df, e)
def test_Sample_outcomes(self):
# NOTE how integers were changed into floats.
# TODO: consider removing this test, since it's already tested in test_balancedf.py
e = pd.DataFrame(
{
"o": (7.0, 8.0, 9.0, 10.0),
},
columns=["o"],
)
self.assertEqual(s1.outcomes().df, e)
def test_Sample_weights(self):
e = pd.DataFrame(
{
"w": (0.5, 2, 1, 1),
},
columns=["w"],
)
self.assertEqual(s1.weights().df, e)
# TODO: consider removing this test, since it's already tested in test_balancedf.py
def test_Sample_covars(self):
# NOTE how integers were changed into floats.
e = pd.DataFrame(
{
"a": (1.0, 2.0, 3.0, 1.0),
"b": (-42.0, 8.0, 2.0, -42.0),
"c": ("x", "y", "z", "v"),
}
)
self.assertEqual(s1.covars().df, e)
def test_Sample_model(self):
np.random.seed(112358)
d = pd.DataFrame(np.random.rand(1000, 10))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
s = Sample.from_frame(d)
d = pd.DataFrame(np.random.rand(10000, 10))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
t = Sample.from_frame(d)
a = s.adjust(t, max_de=None, method="null")
m = a.model()
self.assertEqual(m["method"], "null_adjustment")
a = s.adjust(t, max_de=None)
m = a.model()
self.assertEqual(m["method"], "ipw")
# Just test the structure of ipw output
self.assertTrue("perf" in m.keys())
self.assertTrue("fit" in m.keys())
self.assertTrue("coefs" in m["perf"].keys())
def test_Sample_model_matrix(self):
# Main tests for model_matrix are in test_util.py
s = Sample.from_frame(
pd.DataFrame(
{
"a": (0, 1, 2),
"b": (0, None, 2),
"c": ("a", "b", "a"),
"id": (1, 2, 3),
}
),
id_column="id",
)
e = pd.DataFrame(
{
"a": (0.0, 1.0, 2.0),
"b": (0.0, 0.0, 2.0),
"_is_na_b[T.True]": (0.0, 1.0, 0.0),
"c[a]": (1.0, 0.0, 1.0),
"c[b]": (0.0, 1.0, 0.0),
}
)
r = s.model_matrix()
self.assertEqual(r, e, lazy=True)
def test_Sample_set_weights(self):
s = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
)
# NOTE that if using set_weights with integers, the weights remain integers
s.set_weights(pd.Series([1, 2, 3, 4]))
self.assertEqual(s.weight_column, pd.Series([1, 2, 3, 4], name="w"))
s.set_weights(pd.Series([1, 2, 3, 4], index=(1, 2, 5, 6)))
self.assertEqual(
s.weight_column, pd.Series([np.nan, 1.0, 2.0, np.nan], name="w")
)
# test warning
self.assertWarnsRegexp(
"""Note that not all Sample units will be assigned weights""",
Sample.set_weights,
s,
pd.Series([1, 2, 3, 4], index=(1, 2, 5, 6)),
)
# no warning
self.assertNotWarns(
Sample.set_weights,
s,
pd.Series([1, 2, 3, 4], index=(0, 1, 2, 3)),
)
def test_Sample_set_unadjusted(self):
s5 = s1.set_unadjusted(s2)
self.assertTrue(s5._links["unadjusted"] is s2)
# test exceptions when there is no a second sample
with self.assertRaisesRegex(
TypeError,
"set_unadjusted must be called with second_sample argument of type Sample",
):
s1.set_unadjusted("Not a Sample object")
def test_Sample_is_adjusted(self):
self.assertFalse(s1.is_adjusted())
# TODO: move definitions of s3 outside of function
s3 = s1.set_target(s2)
self.assertFalse(s3.is_adjusted())
# TODO: move definitions of s3 outside of function
s3_adjusted = s3.adjust(method="null")
self.assertTrue(s3_adjusted.is_adjusted())
def test_Sample_set_target(self):
s5 = s1.set_target(s2)
self.assertTrue(s5._links["target"] is s2)
# test exceptions when the provided object is not a second sample
with self.assertRaisesRegex(
ValueError,
"A target, a Sample object, must be specified",
):
s1.set_target("Not a Sample object")
def test_Sample_has_target(self):
self.assertFalse(s1.has_target())
self.assertTrue(s1.set_target(s2).has_target())
class TestSample_metrics_methods(
balance.testutil.BalanceTestCase,
):
def test_Sample_covar_means(self):
# TODO: take definition of s3_null outside of function
s3_null = s1.adjust(s2, method="null")
e = pd.DataFrame(
{
"a": [(0.5 * 1 + 2 * 2 + 3 * 1 + 1 * 1) / (0.5 + 2 + 1 + 1)],
"b": [(-42 * 0.5 + 8 * 2 + 2 * 1 + -42 * 1) / (0.5 + 2 + 1 + 1)],
"c[x]": [(1 * 0.5) / (0.5 + 2 + 1 + 1)],
"c[y]": [(1 * 2) / (0.5 + 2 + 1 + 1)],
"c[z]": [(1 * 1) / (0.5 + 2 + 1 + 1)],
"c[v]": [(1 * 1) / (0.5 + 2 + 1 + 1)],
}
).transpose()
e = pd.concat((e,) * 2, axis=1, sort=True)
e = pd.concat(
(
e,
pd.DataFrame(
{
"a": [(1 * 0.5 + 2 * 1 + 3 * 2) / (0.5 + 1 + 2)],
"b": [(4 * 0.5 + 6 * 1 + 8 * 2) / (0.5 + 1 + 2)],
"c[x]": [(1 * 0.5) / (0.5 + 1 + 2)],
"c[y]": [(1 * 1) / (0.5 + 1 + 2)],
"c[z]": [(1 * 2) / (0.5 + 1 + 2)],
"c[v]": np.nan,
}
).transpose(),
),
axis=1,
sort=True,
)
e.columns = pd.Series(("unadjusted", "adjusted", "target"), name="source")
self.assertEqual(s3_null.covar_means(), e)
# test exceptions when there is no adjusted
with self.assertRaisesRegex(
ValueError,
"This is not an adjusted Sample. Use sample.adjust to adjust the sample to target",
):
s1.covar_means()
def test_Sample_design_effect(self):
self.assertEqual(s1.design_effect().round(3), 1.235)
self.assertEqual(s4.design_effect(), 1.0)
def test_Sample_design_effect_prop(self):
# TODO: take definition of s3_null outside of function
s3_null = s1.adjust(s2, method="null")
self.assertEqual(s3_null.design_effect_prop(), 0.0)
# test exceptions when there is no adjusted
with self.assertRaisesRegex(
ValueError,
"This is not an adjusted Sample. Use sample.adjust to adjust the sample to target",
):
s1.design_effect_prop()
def test_Sample_outcome_sd_prop(self):
# TODO: take definition of s3_null outside of function
s3_null = s1.adjust(s2, method="null")
self.assertEqual(s3_null.outcome_sd_prop(), pd.Series((0.0), index=["o"]))
# test with two outcomes
# TODO: take definition of s1_two_outcomes outside of function
s1_two_outcomes = Sample.from_frame(
pd.DataFrame(
{
"o1": (7, 8, 9, 10),
"o2": (7, 8, 9, 11),
"c": ("x", "y", "z", "y"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
},
),
id_column="id",
weight_column="w",
outcome_columns=["o1", "o2"],
)
s3_null = s1_two_outcomes.adjust(s2, method="null")
self.assertEqual(
s3_null.outcome_sd_prop(), pd.Series((0.0, 0.0), index=["o1", "o2"])
)
# test exceptions when there is no adjusted
with self.assertRaisesRegex(
ValueError,
"This Sample does not have outcome columns specified",
):
s2.adjust(s2, method="null").outcome_sd_prop()
def test_outcome_variance_ratio(self):
from balance.stats_and_plots.weighted_stats import weighted_var
# Testing it also works with outcomes
np.random.seed(112358)
d = pd.DataFrame(np.random.rand(1000, 10))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
t = Sample.from_frame(d)
d = pd.DataFrame(np.random.rand(1000, 11))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghijk"[i] for i in range(0, 11)})
d["b"] = np.sqrt(d["b"])
a_with_outcome = Sample.from_frame(d, outcome_columns=["k"])
a_with_outcome_adjusted = a_with_outcome.adjust(t, max_de=1.5)
# verifying this does what we expect it does:
self.assertEqual(
round(a_with_outcome_adjusted.outcome_variance_ratio()[0], 5),
round(
(
weighted_var(
a_with_outcome_adjusted.outcomes().df,
a_with_outcome_adjusted.weights().df["weight"],
)
/ weighted_var(
a_with_outcome_adjusted._links["unadjusted"].outcomes().df,
a_with_outcome_adjusted._links["unadjusted"]
.weights()
.df["weight"],
)
)[0],
5,
),
)
self.assertEqual(
round(a_with_outcome_adjusted.outcome_variance_ratio()[0], 5), 0.97516
)
# two outcomes, with no adjustment (var ratio should be 1)
a_with_outcome = Sample.from_frame(d, outcome_columns=["j", "k"])
a_with_outcome_adjusted = a_with_outcome.adjust(t, method="null")
self.assertEqual(
a_with_outcome_adjusted.outcome_variance_ratio(),
pd.Series([1.0, 1.0], index=["j", "k"]),
)
def test_Sample_weights_summary(self):
self.assertEqual(
s1.weights().summary().round(2).to_dict(),
{
"var": {
0: "design_effect",
1: "effective_sample_proportion",
2: "effective_sample_size",
3: "sum",
4: "describe_count",
5: "describe_mean",
6: "describe_std",
7: "describe_min",
8: "describe_25%",
9: "describe_50%",
10: "describe_75%",
11: "describe_max",
12: "prop(w < 0.1)",
13: "prop(w < 0.2)",
14: "prop(w < 0.333)",
15: "prop(w < 0.5)",
16: "prop(w < 1)",
17: "prop(w >= 1)",
18: "prop(w >= 2)",
19: "prop(w >= 3)",
20: "prop(w >= 5)",
21: "prop(w >= 10)",
22: "nonparametric_skew",
23: "weighted_median_breakdown_point",
},
"val": {
0: 1.23,
1: 0.81,
2: 3.24,
3: 4.5,
4: 4.0,
5: 1.0,
6: 0.56,
7: 0.44,
8: 0.78,
9: 0.89,
10: 1.11,
11: 1.78,
12: 0.0,
13: 0.0,
14: 0.0,
15: 0.25,
16: 0.75,
17: 0.25,
18: 0.0,
19: 0.0,
20: 0.0,
21: 0.0,
22: 0.2,
23: 0.25,
},
},
)
def test_Sample_summary(self):
s1_summ = s1.summary()
self.assertTrue("Model performance" not in s1_summ)
self.assertTrue("Covar ASMD" not in s1_summ)
s3 = s1.set_target(s2)
s3_summ = s3.summary()
self.assertTrue("Model performance" not in s1_summ)
self.assertTrue("Covar ASMD (6 variables)" in s3_summ)
self.assertTrue("design effect" not in s3_summ)
s3 = s3.set_unadjusted(s1)
s3_summ = s3.summary()
self.assertTrue("Covar ASMD reduction: 0.0%" in s3_summ)
self.assertTrue("Covar ASMD (6 variables)" in s3_summ)
self.assertTrue("->" in s3_summ)
self.assertTrue("design effect" in s3_summ)
s3 = s1.set_target(s2).adjust(method="null")
s3_summ = s3.summary()
self.assertTrue("Covar ASMD reduction: 0.0%" in s3_summ)
self.assertTrue("design effect" in s3_summ)
def test_Sample_invalid_outcomes(self):
with self.assertRaisesRegex(
ValueError,
r"outcome columns \['o'\] not in df columns \['a', 'id', 'weight'\]",
):
Sample.from_frame(
pd.DataFrame({"a": (1, 2, 3, 1), "id": (1, 2, 3, 4)}),
outcome_columns="o",
)
def test_Sample_diagnostics(self):
import numpy as np
import pandas as pd
# TODO (p2): move the objects created here outside of this function and possible make this simpler.
from balance.sample_class import Sample
np.random.seed(112358)
d = pd.DataFrame(np.random.rand(1000, 10))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
s = Sample.from_frame(d)
d = pd.DataFrame(np.random.rand(1000, 10))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
t = Sample.from_frame(d)
a = s.adjust(t)
a_diagnostics = a.diagnostics()
# print(a_diagnostics)
self.assertEqual(a_diagnostics.shape, (198, 3))
self.assertEqual(a_diagnostics.columns.to_list(), ["metric", "val", "var"])
self.assertEqual(
a_diagnostics[a_diagnostics["metric"] == "adjustment_method"]["var"].values,
np.array(["ipw"]),
)
output = a_diagnostics.groupby("metric").size().to_dict()
expected = {
"adjustment_failure": 1,
"covar_asmd_adjusted": 11,
"covar_asmd_improvement": 11,
"covar_asmd_unadjusted": 11,
"covar_main_asmd_adjusted": 11,
"covar_main_asmd_improvement": 11,
"covar_main_asmd_unadjusted": 11,
"model_coef": 92,
"model_glance": 10,
"adjustment_method": 1,
"size": 4,
"weights_diagnostics": 24,
}
self.assertEqual(output, expected)
b = s.adjust(t, method="cbps")
b_diagnostics = b.diagnostics()
# print(b_diagnostics)
self.assertEqual(b_diagnostics.shape, (196, 3))
self.assertEqual(b_diagnostics.columns.to_list(), ["metric", "val", "var"])
self.assertEqual(
b_diagnostics[b_diagnostics["metric"] == "adjustment_method"]["var"].values,
np.array(["cbps"]),
)
output = b_diagnostics.groupby("metric").size().to_dict()
expected = {
"adjustment_failure": 1,
"balance_optimize_result": 2,
"gmm_optimize_result_bal_init": 2,
"gmm_optimize_result_glm_init": 2,
"rescale_initial_result": 2,
"beta_optimal": 92,
"covar_asmd_adjusted": 11,
"covar_asmd_improvement": 11,
"covar_asmd_unadjusted": 11,
"covar_main_asmd_adjusted": 11,
"covar_main_asmd_improvement": 11,
"covar_main_asmd_unadjusted": 11,
"adjustment_method": 1,
"size": 4,
"weights_diagnostics": 24,
}
self.assertEqual(output, expected)
c = s.adjust(t, method="null")
c_diagnostics = c.diagnostics()
self.assertEqual(c_diagnostics.shape, (96, 3))
self.assertEqual(c_diagnostics.columns.to_list(), ["metric", "val", "var"])
self.assertEqual(
c_diagnostics[c_diagnostics["metric"] == "adjustment_method"]["var"].values,
np.array(["null_adjustment"]),
)
def test_Sample_keep_only_some_rows_columns(self):
import numpy as np
import pandas as pd
# TODO (p2): move the objects created here outside of this function and possible make this simpler.
from balance.sample_class import Sample
np.random.seed(112358)
d = pd.DataFrame(np.random.rand(1000, 10))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
d["b"] = np.sqrt(d["b"])
s = Sample.from_frame(d)
d = pd.DataFrame(np.random.rand(1000, 10))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
t = Sample.from_frame(d)
a = s.adjust(t, max_de=1.5)
# if both rows_to_keep = None, columns_to_keep = None - then keep_only_some_rows_columns returns the same object
self.assertTrue(
a is a.keep_only_some_rows_columns(rows_to_keep=None, columns_to_keep=None)
)
# let's remove some columns and rows:
a2 = a.keep_only_some_rows_columns(
rows_to_keep=None, columns_to_keep=["b", "c"]
)
# Making sure asmd works
output_orig = a.covars().asmd().round(2).to_dict()
output_new = a2.covars().asmd().round(2).to_dict()
expected_orig = {
"j": {"self": 0.01, "unadjusted": 0.03, "unadjusted - self": 0.02},
"i": {"self": 0.02, "unadjusted": 0.0, "unadjusted - self": -0.02},
"h": {"self": 0.04, "unadjusted": 0.09, "unadjusted - self": 0.04},
"g": {"self": 0.0, "unadjusted": 0.0, "unadjusted - self": 0.0},
"f": {"self": 0.01, "unadjusted": 0.03, "unadjusted - self": 0.02},
"e": {"self": 0.0, "unadjusted": 0.0, "unadjusted - self": 0.0},
"d": {"self": 0.05, "unadjusted": 0.12, "unadjusted - self": 0.06},
"c": {"self": 0.04, "unadjusted": 0.05, "unadjusted - self": 0.01},
"b": {"self": 0.14, "unadjusted": 0.55, "unadjusted - self": 0.41},
"a": {"self": 0.01, "unadjusted": 0.0, "unadjusted - self": -0.01},
"mean(asmd)": {"self": 0.03, "unadjusted": 0.09, "unadjusted - self": 0.05},
}
expected_new = {
"c": {"self": 0.04, "unadjusted": 0.05, "unadjusted - self": 0.01},
"b": {"self": 0.14, "unadjusted": 0.55, "unadjusted - self": 0.41},
"mean(asmd)": {"self": 0.09, "unadjusted": 0.3, "unadjusted - self": 0.21},
}
self.assertEqual(output_orig, expected_orig)
self.assertEqual(output_new, expected_new)
# Making sure diagnostics works, and also seeing we got change in
# what we expect
a_diag = a.diagnostics()
a2_diag = a2.diagnostics()
a_diag_tbl = a_diag.groupby("metric").size().to_dict()
a2_diag_tbl = a2_diag.groupby("metric").size().to_dict()
# The mean weight should be 1 (since we normalize for the sum of weights to be equal to len(weights))
ss = a_diag.eval("(metric == 'weights_diagnostics') & (var == 'describe_mean')")
self.assertEqual(round(float(a_diag[ss].val), 4), 1.000)
# keeping only columns 'b' and 'c' leads to have only 3 asmd instead of 11:
self.assertEqual(a_diag_tbl["covar_main_asmd_adjusted"], 11)
self.assertEqual(a2_diag_tbl["covar_main_asmd_adjusted"], 3)
# now we get only 2 covars counted instead of 10:
ss_condition = "(metric == 'size') & (var == 'sample_covars')"
ss = a_diag.eval(ss_condition)
ss2 = a2_diag.eval(ss_condition)
self.assertEqual(int(a_diag[ss].val), 10)
self.assertEqual(int(a2_diag[ss2].val), 2)
# And the mean asmd is different
ss_condition = "(metric == 'covar_main_asmd_adjusted') & (var == 'mean(asmd)')"
ss = a_diag.eval(ss_condition)
ss2 = a2_diag.eval(ss_condition)
self.assertEqual(round(float(a_diag[ss].val), 4), 0.0338)
self.assertEqual(round(float(a2_diag[ss2].val), 3), 0.093)
# Also checking filtering using rows_to_keep:
a3 = a.keep_only_some_rows_columns(
rows_to_keep="a>0.5", columns_to_keep=["b", "c"]
)
# Making sure the weights are of the same length as the df
self.assertEqual(a3.df.shape[0], a3.weights().df.shape[0])
# Making sure asmd works - we can see it's different then for a2
output_new = a3.covars().asmd().round(2).to_dict()
expected_new = {
"c": {"self": 0.06, "unadjusted": 0.07, "unadjusted - self": 0.01},
"b": {"self": 0.21, "unadjusted": 0.61, "unadjusted - self": 0.4},
"mean(asmd)": {"self": 0.13, "unadjusted": 0.34, "unadjusted - self": 0.21},
}
self.assertEqual(output_new, expected_new)
a3_diag = a3.diagnostics()
a3_diag_tbl = a3_diag.groupby("metric").size().to_dict()
# The structure of the diagnostics table is the same with and without
# the filtering. So when comparing a3 to a2, we should get the same results:
# i.e.: a2_diag_tbl == a3_diag_tbl # True
self.assertEqual(a2_diag_tbl, a3_diag_tbl)
# However, the number of samples is different!
ss_condition = "(metric == 'size') & (var == 'sample_obs')"
self.assertEqual(int(a_diag[a_diag.eval(ss_condition)].val), 1000)
self.assertEqual(int(a2_diag[a2_diag.eval(ss_condition)].val), 1000)
self.assertEqual(int(a3_diag[a3_diag.eval(ss_condition)].val), 508)
# also in the target
ss_condition = "(metric == 'size') & (var == 'target_obs')"
self.assertEqual(int(a_diag[a_diag.eval(ss_condition)].val), 1000)
self.assertEqual(int(a2_diag[a2_diag.eval(ss_condition)].val), 1000)
self.assertEqual(
int(a3_diag[a3_diag.eval(ss_condition)].val), 516
) # since a<0.5 is different for target!
# also in the weights
ss = a_diag.eval(
"(metric == 'weights_diagnostics') & (var == 'describe_count')"
)
self.assertEqual(int(a_diag[ss].val), 1000)
ss = a3_diag.eval(
"(metric == 'weights_diagnostics') & (var == 'describe_count')"
)
self.assertEqual(int(a3_diag[ss].val), 508)
# Notice also that the calculated values from the weights are different
ss = a_diag.eval("(metric == 'weights_diagnostics') & (var == 'design_effect')")
self.assertEqual(round(float(a_diag[ss].val), 4), 1.493)
ss = a3_diag.eval(
"(metric == 'weights_diagnostics') & (var == 'design_effect')"
)
self.assertEqual(round(float(a3_diag[ss].val), 4), 1.4802)
# Testing it also works with outcomes
np.random.seed(112358)
d = pd.DataFrame(np.random.rand(1000, 11))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghijk"[i] for i in range(0, 11)})
d["b"] = np.sqrt(d["b"])
a_with_outcome = Sample.from_frame(d, outcome_columns=["k"])
a_with_outcome_adjusted = a_with_outcome.adjust(t, max_de=1.5)
# We can also filter using an outcome variable (although this would NOT filter on target)
# a proper logger warning is issued
self.assertEqual(
a_with_outcome_adjusted.keep_only_some_rows_columns(
rows_to_keep="k>0.5"
).df.shape,
(481, 13),
)
a_with_outcome_adjusted2 = a_with_outcome_adjusted.keep_only_some_rows_columns(
rows_to_keep="b>0.5", columns_to_keep=["b", "c"]
)
self.assertEqual(
a_with_outcome_adjusted2.outcomes().mean().round(3).to_dict(),
{"k": {"self": 0.491, "unadjusted": 0.494}},
)
# TODO (p2): possibly add checks for columns_to_keep = None while doing something with rows_to_keep
# test if only some columns exists
self.assertWarnsRegexp(
"Note that not all columns_to_keep are in Sample",
s1.keep_only_some_rows_columns,
columns_to_keep=["g", "a"],
)
self.assertEqual(
s1.keep_only_some_rows_columns(
columns_to_keep=["g", "a"]
)._df.columns.tolist(),
["a"],
)
class TestSample_to_download(balance.testutil.BalanceTestCase):
def test_Sample_to_download(self):
r = s1.to_download()
self.assertIsInstance(r, IPython.display.FileLink)
def test_Sample_to_csv(self):
with tempfile.NamedTemporaryFile() as tf:
s1.to_csv(path_or_buf=tf.name)
r = tf.read()
e = (
b"id,a,b,c,o,w\n1,1,-42,x,7,0.5\n"
b"2,2,8,y,8,2.0\n3,3,2,z,9,1.0\n4,1,-42,v,10,1.0\n"
)
self.assertTrue(r, e)
class TestSamplePrivateAPI(balance.testutil.BalanceTestCase):
def test__links(self):
self.assertTrue(len(s1._links.keys()) == 0)
s3 = s1.set_target(s2)
self.assertTrue(s3._links["target"] is s2)
self.assertTrue(s3.has_target())
s3_adjusted = s3.adjust(method="null")
self.assertTrue(s3_adjusted._links["target"] is s2)
self.assertTrue(s3_adjusted._links["unadjusted"] is s3)
self.assertTrue(s3_adjusted.has_target())
def test__special_columns_names(self):
self.assertEqual(
sorted(s4._special_columns_names()), ["b", "c", "id", "weight"]
)
# NOTE how integers were changed into floats.
def test__special_columns(self):
# NOTE how integers in weight were changed into floats.
self.assertEqual(
s4._special_columns(),
pd.DataFrame(
{
"id": ("1", "2", "3"),
# Weights were filled automatically to be integers of 1s:
"weight": (1, 1, 1),
"b": (0.0, None, 2.0),
"c": ("a", "b", "c"),
}
),
)
def test__covar_columns_names(self):
self.assertEqual(sorted(s1._covar_columns_names()), ["a", "b", "c"])
def test__covar_columns(self):
# NOTE how integers were changed into floats.
self.assertEqual(
s1._covar_columns(),
pd.DataFrame(
{
"a": (1.0, 2.0, 3.0, 1.0),
"b": (-42.0, 8.0, 2.0, -42.0),
"c": ("x", "y", "z", "v"),
}
),
)
def test_Sample__check_if_adjusted(self):
with self.assertRaisesRegex(
ValueError,
"This is not an adjusted Sample. Use sample.adjust to adjust the sample to target",
):
s1._check_if_adjusted()
# TODO: move definitions of s3 outside of function
s3 = s1.set_target(s2)
with self.assertRaisesRegex(
ValueError,
"This is not an adjusted Sample. Use sample.adjust to adjust the sample to target",
):
s3._check_if_adjusted()
# TODO: move definitions of s3 outside of function
s3_adjusted = s3.adjust(method="null")
self.assertTrue(
s3_adjusted._check_if_adjusted() is None
) # Does not raise an error
def test_Sample__no_target_error(self):
# test exception when the is no target
with self.assertRaisesRegex(
ValueError,
"This Sample does not have a target set. Use sample.set_target to add target",
):
s1._no_target_error()
s3 = s1.set_target(s2)
s3._no_target_error() # Should not raise an error
def test_Sample__check_outcomes_exists(self):
with self.assertRaisesRegex(
ValueError,
"This Sample does not have outcome columns specified",
):
s2._check_outcomes_exists()
self.assertTrue(s1._check_outcomes_exists() is None) # Does not raise an error
class TestSample_NA_behavior(balance.testutil.BalanceTestCase):
def test_can_handle_various_NAs(self):
# Testing if we can handle NA values from pandas
def get_sample_to_adjust(df, standardize_types=True):
s1 = Sample.from_frame(df, standardize_types=standardize_types)
s2 = deepcopy(s1)
s2.set_weights(np.ones(100))
return s1.set_target(s2)
np.random.seed(123)
df = pd.DataFrame(
{
"a": np.random.uniform(size=100),
"c": np.random.choice(
["a", "b", "c", "d"],
size=100,
replace=True,
p=[0.01, 0.04, 0.5, 0.45],
),
"id": range(100),
"weight": np.random.uniform(size=100) + 0.5,
}
)
# This works fine
smpl_to_adj = get_sample_to_adjust(df)
self.assertIsInstance(smpl_to_adj.adjust(method="ipw"), Sample)
# This should raise a TypeError:
with self.assertRaisesRegex(
TypeError,
"boolean value of NA is ambiguous",
):
smpl_to_adj = get_sample_to_adjust(df)
# smpl_to_adj._df.iloc[0, 0] = pd.NA
smpl_to_adj._df.iloc[0, 1] = pd.NA
# This will raise the error:
smpl_to_adj.adjust(method="ipw")
# This should raise a TypeError:
with self.assertRaisesRegex(
Exception,
"series must be numeric",
):
# Adding NA to a numeric column turns it into an object.
# This raises an error in util.quantize
smpl_to_adj = get_sample_to_adjust(df)
smpl_to_adj._df.iloc[0, 0] = pd.NA
# smpl_to_adj._df.iloc[0, 1] = pd.NA
# This will raise the error:
smpl_to_adj.adjust(method="ipw")
# This works fine
df.iloc[0, 0] = np.nan
df.iloc[0, 1] = np.nan
smpl_to_adj = get_sample_to_adjust(df)
self.assertIsInstance(smpl_to_adj.adjust(method="ipw"), Sample)
# This also works fine (thanks to standardize_types=True)
df.iloc[0, 0] = pd.NA
df.iloc[0, 1] = pd.NA
smpl_to_adj = get_sample_to_adjust(df)
self.assertIsInstance(smpl_to_adj.adjust(method="ipw"), Sample)
# Turning standardize_types to False should raise a TypeError (since we have pd.NA):
with self.assertRaisesRegex(
TypeError,
"boolean value of NA is ambiguous",
):
# df.iloc[0, 0] = pd.NA
df.iloc[0, 1] = pd.NA
smpl_to_adj = get_sample_to_adjust(df, standardize_types=False)
smpl_to_adj.adjust(method="ipw")
| balance-main | tests/test_sample.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import random
import balance
import balance.testutil
import numpy as np
import pandas as pd
from balance.adjustment import (
apply_transformations,
default_transformations,
trim_weights,
)
from balance.sample_class import Sample
from balance.util import fct_lump, quantize
from balance.weighting_methods import (
cbps as balance_cbps,
ipw as balance_ipw,
poststratify as balance_poststratify,
)
EPSILON = 0.00001
sample = Sample.from_frame(
df=pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "x"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
target = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (-42, 8, 2),
"c": ("x", "y", "z"),
"id": (1, 2, 3),
"w": (2, 0.5, 1),
}
),
id_column="id",
weight_column="w",
)
class TestAdjustment(
balance.testutil.BalanceTestCase,
):
def test_trim_weights(self):
# Test no trimming
# Notice how it changes the dtype of int64 to float64~
pd.testing.assert_series_equal(
trim_weights(pd.Series([0, 1, 2])), pd.Series([0.0, 1.0, 2.0])
)
self.assertEqual(type(trim_weights(pd.Series([0, 1, 2]))), pd.Series)
self.assertEqual(trim_weights(pd.Series([0, 1, 2])).dtype, np.float64)
random.seed(42)
w = np.random.uniform(0, 1, 10000)
self.assertEqual(
trim_weights(
w,
weight_trimming_percentile=None,
weight_trimming_mean_ratio=None,
keep_sum_of_weights=False,
),
w,
)
# Test exceptions
with self.assertRaisesRegex(
TypeError, "weights must be np.array or pd.Series, are of type*"
):
trim_weights("Strings don't get trimmed", weight_trimming_mean_ratio=1)
with self.assertRaisesRegex(ValueError, "Only one"):
trim_weights(
np.array([0, 1, 2]),
1,
1,
)
# Test weight_trimming_mean_ratio
random.seed(42)
w = np.random.uniform(0, 1, 10000)
res = trim_weights(w, weight_trimming_mean_ratio=1)
self.assertAlmostEqual(np.mean(w), np.mean(res), delta=EPSILON)
self.assertAlmostEqual(
np.mean(w) / np.min(w), np.max(res) / np.min(res), delta=EPSILON
)
# Test weight_trimming_percentile
random.seed(42)
w = np.random.uniform(0, 1, 10000)
self.assertTrue(
max(
trim_weights(
w, weight_trimming_percentile=(0, 0.11), keep_sum_of_weights=False
)
)
< 0.9
)
self.assertTrue(
min(
trim_weights(
w, weight_trimming_percentile=(0.11, 0), keep_sum_of_weights=False
)
)
> 0.1
)
e = trim_weights(w, weight_trimming_percentile=(0.11, 0.11))
self.assertTrue(min(e) > 0.1)
self.assertTrue(max(e) < 0.9)
def test_default_transformations(self):
# For multiple dataframes
input = (
pd.DataFrame({"a": (1, 2), "b": ("a", "b")}),
pd.DataFrame({"c": (1, 2), "d": ("a", "b")}),
)
r = default_transformations(input)
self.assertEqual(
r,
{
"a": quantize,
"b": fct_lump,
"c": quantize,
"d": fct_lump,
},
)
# For one dataframe
input = pd.DataFrame({"a": (1, 2), "b": ("a", "b")})
r = default_transformations([input])
self.assertEqual(
r,
{
"a": quantize,
"b": fct_lump,
},
)
# For boolean and Int64 input
input = pd.DataFrame({"a": (1, 2), "b": (True, False)})
input = input.astype(
dtype={
"a": "Int64",
"b": "boolean",
}
)
r = default_transformations([input])
self.assertEqual(
r,
{
"a": quantize,
"b": fct_lump,
},
)
def test_default_transformations_pd_int64(self):
nullable_int = pd.DataFrame({"a": pd.array((1, 2), dtype="Int64")})
numpy_int = nullable_int.astype(np.int64)
test = default_transformations([nullable_int])
truth = default_transformations([numpy_int])
self.assertEqual(test, truth)
def test_apply_transformations(self):
s = pd.DataFrame({"d": [1, 2, 3], "e": [1, 2, 3]})
t = pd.DataFrame({"d": [4, 5, 6, 7], "e": [1, 2, 3, 4]})
transformations = {"d": lambda x: x * 2, "f": lambda x: x.d + 1}
r = apply_transformations((s, t), transformations)
e = (
pd.DataFrame({"d": [2, 4, 6], "f": [2, 3, 4]}),
pd.DataFrame({"d": [8, 10, 12, 14], "f": [5, 6, 7, 8]}),
)
self.assertEqual(r[0], e[0], lazy=True)
self.assertEqual(r[1], e[1], lazy=True)
# No transformations or additions
self.assertEqual(apply_transformations((s, t), None), (s, t))
# Only transformations
r = apply_transformations((s, t), {"d": lambda x: x * 2})
e = (pd.DataFrame({"d": [2, 4, 6]}), pd.DataFrame({"d": [8, 10, 12, 14]}))
self.assertEqual(r[0], e[0])
self.assertEqual(r[1], e[1])
# Only additions
r = apply_transformations((s, t), {"f": lambda x: x.d + 1})
e = (pd.DataFrame({"f": [2, 3, 4]}), pd.DataFrame({"f": [5, 6, 7, 8]}))
self.assertEqual(r[0], e[0])
self.assertEqual(r[1], e[1])
# Warns about dropping variable
self.assertWarnsRegexp(
r"Dropping the variables: \['e'\]",
apply_transformations,
(s, t),
transformations,
)
# Does not drop
r = apply_transformations((s, t), transformations, drop=False)
e = (
pd.DataFrame({"d": [2, 4, 6], "e": [1, 2, 3], "f": [2, 3, 4]}),
pd.DataFrame({"d": [8, 10, 12, 14], "e": [1, 2, 3, 4], "f": [5, 6, 7, 8]}),
)
self.assertEqual(r[0], e[0], lazy=True)
self.assertEqual(r[1], e[1], lazy=True)
# Works on three dfs
q = pd.DataFrame({"d": [8, 9], "g": [1, 2]})
r = apply_transformations((s, t, q), transformations)
e = (
pd.DataFrame({"d": [2, 4, 6], "f": [2, 3, 4]}),
pd.DataFrame({"d": [8, 10, 12, 14], "f": [5, 6, 7, 8]}),
pd.DataFrame({"d": [16, 18], "f": [9, 10]}),
)
self.assertEqual(r[0], e[0], lazy=True)
self.assertEqual(r[1], e[1], lazy=True)
self.assertEqual(r[2], e[2], lazy=True)
# Test that functions are computed over all dfs passed, not each individually
transformations = {"d": lambda x: x / max(x)}
r = apply_transformations((s, t), transformations)
e = (
pd.DataFrame({"d": [2 / 14, 4 / 14, 6 / 14]}),
pd.DataFrame({"d": [8 / 14, 10 / 14, 12 / 14, 14 / 14]}),
)
self.assertEqual(r[0], e[0])
self.assertEqual(r[1], e[1])
# Transformation of a column which does not exist in one of the dataframes
s = pd.DataFrame({"d": [1, 2, 3], "e": [1, 2, 3]})
t = pd.DataFrame({"d": [4, 5, 6, 7]})
transformations = {"e": lambda x: x * 2}
r = apply_transformations((s, t), transformations)
e = (
pd.DataFrame({"e": [2.0, 4.0, 6.0]}),
pd.DataFrame({"e": [np.nan, np.nan, np.nan, np.nan]}),
)
self.assertEqual(r[0], e[0])
self.assertEqual(r[1], e[1])
# Additon of a column based on one which does not exist in one of the dataframes
transformations = {"f": lambda x: x.e * 2}
r = apply_transformations((s, t), transformations)
e = (
pd.DataFrame({"f": [2.0, 4.0, 6.0]}),
pd.DataFrame({"f": [np.nan, np.nan, np.nan, np.nan]}),
)
self.assertEqual(r[0], e[0])
self.assertEqual(r[1], e[1])
# Column which does not exist in one of the dataframes
# and is also specified
s = pd.DataFrame({"d": [1, 2, 3], "e": [0, 0, 0]})
t = pd.DataFrame({"d": [4, 5, 6, 7]})
transformations = {"e": lambda x: x + 1}
r = apply_transformations((s, t), transformations)
e = (
pd.DataFrame({"e": [1.0, 1.0, 1.0]}),
pd.DataFrame({"e": [np.nan, np.nan, np.nan, np.nan]}),
)
self.assertEqual(r[0], e[0])
self.assertEqual(r[1], e[1])
# Test that indices are ignored in splitting dfs
s = pd.DataFrame({"d": [1, 2, 3]}, index=(5, 6, 7))
t = pd.DataFrame({"d": [4, 5, 6, 7]}, index=(0, 1, 2, 3))
transformations = {"d": lambda x: x}
r = apply_transformations((s, t), transformations)
e = (s, t)
self.assertEqual(r[0], e[0])
self.assertEqual(r[1], e[1])
# Test indices are handeled okay (this example reuired reset_index of all_data)
s = pd.DataFrame({"a": (0, 0, 0, 0, 0, 0, 0, 0)})
t = pd.DataFrame({"a": (1, 1, 1, 1)})
r = apply_transformations((s, t), "default")
e = (
pd.DataFrame({"a": ["(-0.001, 0.7]"] * 8}),
pd.DataFrame({"a": ["(0.7, 1.0]"] * 4}),
)
self.assertEqual(r[0].astype(str), e[0])
self.assertEqual(r[1].astype(str), e[1])
# Test default transformations
s = pd.DataFrame({"d": range(0, 100), "e": ["a"] * 96 + ["b"] * 4})
t = pd.DataFrame({"d": range(0, 100), "e": ["a"] * 96 + ["b"] * 4})
r_s, r_t = apply_transformations((s, t), "default")
self.assertEqual(r_s["d"].drop_duplicates().values.shape[0], 10)
self.assertEqual(r_t["d"].drop_duplicates().values.shape[0], 10)
self.assertEqual(r_s["e"].drop_duplicates().values, ("a", "_lumped_other"))
self.assertEqual(r_t["e"].drop_duplicates().values, ("a", "_lumped_other"))
def test_invalid_input_to_apply_transformations(self):
# Test non-existent transformation
self.assertRaisesRegex(
NotImplementedError,
"Unknown transformations",
apply_transformations,
(sample.df,),
"foobar",
)
# Test non-dataframe input
self.assertRaisesRegex(
AssertionError,
"'dfs' must contain DataFrames",
apply_transformations,
(sample,),
"foobar",
)
# Test non-tuple input
self.assertRaisesRegex(
AssertionError,
"'dfs' argument must be a tuple of DataFrames",
apply_transformations,
sample.df,
"foobar",
)
def test__find_adjustment_method(self):
self.assertTrue(
balance.adjustment._find_adjustment_method("ipw") is balance_ipw.ipw
)
self.assertTrue(
balance.adjustment._find_adjustment_method("cbps") is balance_cbps.cbps
)
self.assertTrue(
balance.adjustment._find_adjustment_method("poststratify")
is balance_poststratify.poststratify
)
with self.assertRaisesRegex(ValueError, "Unknown adjustment method*"):
balance.adjustment._find_adjustment_method("some_other_value")
| balance-main | tests/test_adjustment.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import balance.testutil
import pandas as pd
from balance.sample_class import Sample
from balance.weighting_methods import adjust_null as balance_adjust_null
sample = Sample.from_frame(
df=pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "x"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
target = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (-42, 8, 2),
"c": ("x", "y", "z"),
"id": (1, 2, 3),
"w": (2, 0.5, 1),
}
),
id_column="id",
weight_column="w",
)
class TestAdjustmentNull(
balance.testutil.BalanceTestCase,
):
def test_adjust_null(self):
res = balance_adjust_null.adjust_null(
pd.DataFrame({"a": [1, 2, 3]}),
pd.Series([4, 5, 6]),
pd.DataFrame({"a": [7, 8, 9]}),
pd.Series([10, 11, 12]),
)
self.assertEqual(res["weight"], pd.Series([4, 5, 6]))
self.assertEqual(res["model"]["method"], "null_adjustment")
result = sample.adjust(target, method="null")
self.assertEqual(sample.weights().df, result.weights().df)
| balance-main | tests/test_adjust_null.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import tempfile
from copy import deepcopy
import IPython.display
import numpy as np
import pandas as pd
from balance.balancedf_class import ( # noqa
BalanceCovarsDF, # noqa
BalanceDF,
BalanceOutcomesDF, # noqa
BalanceWeightsDF, # noqa
)
from balance.sample_class import Sample
from balance.testutil import BalanceTestCase
# TODO: verify all the objects below are used
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
s3_null_madeup_weights = deepcopy(s3_null)
s3_null_madeup_weights.set_weights((1, 2, 3, 1))
s4 = Sample.from_frame(
pd.DataFrame(
{"a": (0, None, 2), "b": (0, None, 2), "c": ("a", "b", "c"), "id": (1, 2, 3)}
),
outcome_columns=("b", "c"),
)
o = s1.outcomes()
s_o = Sample.from_frame(
pd.DataFrame({"o1": (7, 8, 9, 10), "o2": (7, 8, 9, np.nan), "id": (1, 2, 3, 4)}),
id_column="id",
outcome_columns=("o1", "o2"),
)
t_o = Sample.from_frame(
pd.DataFrame(
{
"o1": (7, 8, 9, 10, 11, 12, 13, 14),
"o2": (7, 8, 9, np.nan, np.nan, 12, 13, 14),
"id": (1, 2, 3, 4, 5, 6, 7, 8),
}
),
id_column="id",
outcome_columns=("o1", "o2"),
)
s_o2 = s_o.set_target(t_o)
c = s1.covars()
w = s1.weights()
s1_bad_columns = Sample.from_frame(
pd.DataFrame(
{
"a$": (1, 2, 3, 1),
"a%": (-42, 8, 2, -42),
"o*": (7, 8, 9, 10),
"c@": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o*",
)
class TestBalanceOutcomesDF(BalanceTestCase):
def test_Sample_outcomes(self):
self.assertTrue(isinstance(s4.outcomes(), BalanceOutcomesDF))
self.assertEqual(
s4.outcomes().df, pd.DataFrame({"b": (0, None, 2), "c": ("a", "b", "c")})
)
# Test with multicharacter string name
s = Sample.from_frame(
pd.DataFrame({"aardvark": (0, None, 2), "id": (1, 2, 3)}),
outcome_columns="aardvark",
)
self.assertEqual(s.outcomes().df, pd.DataFrame({"aardvark": (0, None, 2)}))
# Null outcomes
self.assertTrue(s2.outcomes() is None)
def test_BalanceOutcomesDF_df(self):
# Verify that the @property decorator works properly.
self.assertTrue(isinstance(BalanceOutcomesDF.df, property))
# We can no longer call .df() as if it was a function:
with self.assertRaisesRegex(TypeError, "'DataFrame' object is not callable"):
o.df()
# Here is how we can call it as a function:
self.assertEqual(BalanceOutcomesDF.df.fget(o), o.df)
# Check values are as expected:
# NOTE that values changed from integer to float
self.assertEqual(o.df, pd.DataFrame({"o": (7.0, 8.0, 9.0, 10.0)}))
def test__get_df_and_weights(self):
df, w = BalanceDF._get_df_and_weights(o)
# Check types
self.assertEqual(type(df), pd.DataFrame)
self.assertEqual(type(w), np.ndarray)
# Check values
self.assertEqual(df.to_dict(), {"o": {0: 7.0, 1: 8.0, 2: 9.0, 3: 10.0}})
self.assertEqual(w, np.array([0.5, 2.0, 1.0, 1.0]))
def test_BalanceOutcomesDF_names(self):
self.assertEqual(o.names(), ["o"])
def test_BalanceOutcomesDF__sample(self):
self.assertTrue(o._sample is s1)
def test_BalanceOutcomesDF_weights(self):
pd.testing.assert_series_equal(o._weights, pd.Series((0.5, 2, 1, 1)))
def test_BalanceOutcomesDF_relative_response_rates(self):
self.assertEqual(
s_o.outcomes().relative_response_rates(),
pd.DataFrame({"o1": [100.0, 4], "o2": [75.0, 3]}, index=["%", "n"]),
lazy=True,
)
self.assertEqual(s_o.outcomes().relative_response_rates(target=True), None)
# compared with a larget target
self.assertEqual(
s_o2.outcomes()
.relative_response_rates(True, per_column=True)
.round(3)
.to_dict(),
{"o1": {"n": 4.0, "%": 50.0}, "o2": {"n": 3.0, "%": 50.0}},
)
df_target = pd.DataFrame(
{
"o1": (7, 8, 9, 10, 11, 12, 13, 14),
"o2": (7, 8, 9, np.nan, np.nan, 12, 13, 14),
}
)
# Relative to per column:
self.assertEqual(
s_o2.outcomes()
.relative_response_rates(target=df_target, per_column=True)
.to_dict(),
{"o1": {"n": 4.0, "%": 50.0}, "o2": {"n": 3.0, "%": 50.0}},
)
# Checking that if we force per_column=True
# On a df_target that is not the same column structure as s_o2.outcomes()
# It will lead to a ValueError
with self.assertRaisesRegex(
ValueError, "df and df_target must have the exact same columns*"
):
s_o2.outcomes().relative_response_rates(
df_target.iloc[:, 0:1], per_column=True
)
# Relative to all notnull rows in outcome
self.assertEqual(
s_o2.outcomes().relative_response_rates(target=True).round(3).to_dict(),
{"o1": {"n": 4.0, "%": 66.667}, "o2": {"n": 3.0, "%": 50.0}},
)
self.assertEqual(
s_o2.outcomes()
.relative_response_rates(
target=df_target, per_column=False # This is the default.
)
.round(3)
.to_dict(),
s_o2.outcomes().relative_response_rates(target=True).round(3).to_dict(),
)
# This will also work with different shape of columns (exactly what we need for .summary())
self.assertEqual(
s_o.outcomes()
.relative_response_rates(df_target.iloc[:, 0:1], per_column=False)
.round(3)
.to_dict(),
{"o1": {"n": 4.0, "%": 50.0}, "o2": {"n": 3.0, "%": 37.5}},
)
def test_BalanceOutcomesDF_target_response_rates(self):
self.assertEqual(
s_o2.outcomes().target_response_rates(),
pd.DataFrame({"o1": {"n": 8.0, "%": 100.0}, "o2": {"n": 6.0, "%": 75.0}}),
lazy=True,
)
def test_BalanceOutcomesDF_summary(self):
def _remove_whitespace_and_newlines(s):
return " ".join(s.split())
e_str = """\
2 outcomes: ['o1' 'o2']
Mean outcomes (with 95% confidence intervals):
source self self_ci
_is_na_o2[False] 0.75 (0.326, 1.174)
_is_na_o2[True] 0.25 (-0.174, 0.674)
o1 8.50 (7.404, 9.596)
o2 6.00 (2.535, 9.465)
Response rates (relative to number of respondents in sample):
o1 o2
n 4.0 3.0
% 100.0 75.0
"""
self.assertEqual(
_remove_whitespace_and_newlines(s_o.outcomes().summary()),
_remove_whitespace_and_newlines(e_str),
)
e_str = """\
2 outcomes: ['o1' 'o2']
Mean outcomes (with 95% confidence intervals):
source self target self_ci target_ci
_is_na_o2[False] 0.75 0.750 (0.326, 1.174) (0.45, 1.05)
_is_na_o2[True] 0.25 0.250 (-0.174, 0.674) (-0.05, 0.55)
o1 8.50 10.500 (7.404, 9.596) (8.912, 12.088)
o2 6.00 7.875 (2.535, 9.465) (4.351, 11.399)
Response rates (relative to number of respondents in sample):
o1 o2
n 4.0 3.0
% 100.0 75.0
Response rates (relative to notnull rows in the target):
o1 o2
n 4.000000 3.0
% 66.666667 50.0
Response rates (in the target):
o1 o2
n 8.0 6.0
% 100.0 75.0
"""
self.assertEqual(
_remove_whitespace_and_newlines(s_o2.outcomes().summary()),
_remove_whitespace_and_newlines(e_str),
)
class TestBalanceCovarsDF(BalanceTestCase):
def test_BalanceCovarsDF_df(self):
# Verify that the @property decorator works properly.
self.assertTrue(isinstance(BalanceCovarsDF.df, property))
self.assertEqual(BalanceOutcomesDF.df.fget(c), c.df)
# We can no longer call .df() as if it was a function:
with self.assertRaisesRegex(TypeError, "'DataFrame' object is not callable"):
c.df()
# NOTE: while the original datatype had integers, the stored df has only floats:
self.assertEqual(
c.df,
pd.DataFrame(
{
"a": (1.0, 2.0, 3.0, 1.0),
"b": (-42.0, 8.0, 2.0, -42.0),
"c": ("x", "y", "z", "v"),
}
),
)
def test_BalanceCovarsDF_names(self):
self.assertEqual(c.names(), ["a", "b", "c"])
self.assertEqual(type(c.names()), list)
def test_BalanceCovarsDF__sample(self):
self.assertTrue(c._sample is s1)
def test_BalanceCovarsDF_weights(self):
pd.testing.assert_series_equal(
c._weights, pd.Series(np.array([0.5, 2.0, 1.0, 1.0]))
)
class TestBalanceWeightsDF(BalanceTestCase):
def test_BalanceWeightsDF_df(self):
# Verify that the @property decorator works properly.
self.assertTrue(isinstance(BalanceWeightsDF.df, property))
self.assertEqual(BalanceWeightsDF.df.fget(w), w.df)
# We can no longer call .df() as if it was a function:
with self.assertRaisesRegex(TypeError, "'DataFrame' object is not callable"):
w.df()
# Check values are as expected:
self.assertEqual(w.df, pd.DataFrame({"w": (0.5, 2, 1, 1)}))
def test_BalanceWeightsDF_names(self):
self.assertEqual(w.names(), ["w"])
def test_BalanceWeightsDF__sample(self):
self.assertTrue(c._sample is s1)
def test_BalanceWeightsDF_weights(self):
self.assertTrue(w._weights is None)
def test_BalanceWeightsDF_design_effect(self):
s = Sample.from_frame(
pd.DataFrame({"w": (1, 2, 4), "id": (1, 2, 3)}),
id_column="id",
weight_column="w",
)
self.assertTrue(s.weights().design_effect(), 7 / 3)
def test_BalanceWeightsDF_trim(self):
s = Sample.from_frame(
pd.DataFrame({"w": np.random.uniform(0, 1, 10000), "id": range(0, 10000)}),
id_column="id",
weight_column="w",
)
s.weights().trim(percentile=(0, 0.11), keep_sum_of_weights=False)
print(s.weights().df)
print(max(s.weights().df.iloc[:, 0]))
self.assertTrue(max(s.weights().df.iloc[:, 0]) < 0.9)
def test_BalanceWeightsDF_summary(self):
exp = {
"var": {
0: "design_effect",
1: "effective_sample_proportion",
2: "effective_sample_size",
3: "sum",
4: "describe_count",
5: "describe_mean",
6: "describe_std",
7: "describe_min",
8: "describe_25%",
9: "describe_50%",
10: "describe_75%",
11: "describe_max",
12: "prop(w < 0.1)",
13: "prop(w < 0.2)",
14: "prop(w < 0.333)",
15: "prop(w < 0.5)",
16: "prop(w < 1)",
17: "prop(w >= 1)",
18: "prop(w >= 2)",
19: "prop(w >= 3)",
20: "prop(w >= 5)",
21: "prop(w >= 10)",
22: "nonparametric_skew",
23: "weighted_median_breakdown_point",
},
"val": {
0: 1.23,
1: 0.81,
2: 3.24,
3: 4.5,
4: 4.0,
5: 1.0,
6: 0.56,
7: 0.44,
8: 0.78,
9: 0.89,
10: 1.11,
11: 1.78,
12: 0.0,
13: 0.0,
14: 0.0,
15: 0.25,
16: 0.75,
17: 0.25,
18: 0.0,
19: 0.0,
20: 0.0,
21: 0.0,
22: 0.2,
23: 0.25,
},
}
self.assertEqual(w.summary().round(2).to_dict(), exp)
class TestBalanceDF__BalanceDF_child_from_linked_samples(BalanceTestCase):
def test__BalanceDF_child_from_linked_samples_keys(self):
self.assertEqual(
list(s1.covars()._BalanceDF_child_from_linked_samples().keys()), ["self"]
)
self.assertEqual(
list(s3.covars()._BalanceDF_child_from_linked_samples().keys()),
["self", "target"],
)
self.assertEqual(
list(s3_null.covars()._BalanceDF_child_from_linked_samples().keys()),
["self", "target", "unadjusted"],
)
self.assertEqual(
list(s1.weights()._BalanceDF_child_from_linked_samples().keys()), ["self"]
)
self.assertEqual(
list(s3.weights()._BalanceDF_child_from_linked_samples().keys()),
["self", "target"],
)
self.assertEqual(
list(s3_null.weights()._BalanceDF_child_from_linked_samples().keys()),
["self", "target", "unadjusted"],
)
self.assertEqual(
list(s1.outcomes()._BalanceDF_child_from_linked_samples().keys()), ["self"]
)
self.assertEqual(
list(s3.outcomes()._BalanceDF_child_from_linked_samples().keys()),
["self", "target"],
)
self.assertEqual(
list(s3_null.outcomes()._BalanceDF_child_from_linked_samples().keys()),
["self", "target", "unadjusted"],
)
def test__BalanceDF_child_from_linked_samples_values(self):
# We can get a calss using .__class__
self.assertEqual(s1.covars().__class__, BalanceCovarsDF)
# We get a different number of classes based on the number of linked items:
the_dict = s1.covars()._BalanceDF_child_from_linked_samples()
exp = [BalanceCovarsDF]
self.assertEqual([v.__class__ for (k, v) in the_dict.items()], exp)
the_dict = s3.covars()._BalanceDF_child_from_linked_samples()
exp = 2 * [BalanceCovarsDF]
self.assertEqual([v.__class__ for (k, v) in the_dict.items()], exp)
the_dict = s3_null.covars()._BalanceDF_child_from_linked_samples()
exp = 3 * [BalanceCovarsDF]
self.assertEqual([v.__class__ for (k, v) in the_dict.items()], exp)
# This also works for things other than BalanceCovarsDF:
the_dict = s3_null.weights()._BalanceDF_child_from_linked_samples()
exp = 3 * [BalanceWeightsDF]
self.assertEqual([v.__class__ for (k, v) in the_dict.items()], exp)
# Notice that with something like outcomes, we might get a None in return!
the_dict = s3_null.outcomes()._BalanceDF_child_from_linked_samples()
exp = [
BalanceOutcomesDF,
type(None),
BalanceOutcomesDF,
]
self.assertEqual([v.__class__ for (k, v) in the_dict.items()], exp)
# Verify DataFrame values makes sense:
# for covars
the_dict = s3_null.covars()._BalanceDF_child_from_linked_samples()
exp = [
{
"a": {0: 1, 1: 2, 2: 3, 3: 1},
"b": {0: -42, 1: 8, 2: 2, 3: -42},
"c": {0: "x", 1: "y", 2: "z", 3: "v"},
},
{
"a": {0: 1, 1: 2, 2: 3},
"b": {0: 4, 1: 6, 2: 8},
"c": {0: "x", 1: "y", 2: "z"},
},
{
"a": {0: 1, 1: 2, 2: 3, 3: 1},
"b": {0: -42, 1: 8, 2: 2, 3: -42},
"c": {0: "x", 1: "y", 2: "z", 3: "v"},
},
]
self.assertEqual([v.df.to_dict() for (k, v) in the_dict.items()], exp)
# for outcomes
the_dict = s3_null.outcomes()._BalanceDF_child_from_linked_samples()
exp = [{"o": {0: 7, 1: 8, 2: 9, 3: 10}}, {"o": {0: 7, 1: 8, 2: 9, 3: 10}}]
# need to exclude None v:
self.assertEqual(
[v.df.to_dict() for (k, v) in the_dict.items() if v is not None], exp
)
# for weights
the_dict = s3_null.weights()._BalanceDF_child_from_linked_samples()
exp = [
{"w": {0: 0.5, 1: 2.0, 2: 1.0, 3: 1.0}},
{"w": {0: 0.5, 1: 1.0, 2: 2.0}},
{"w": {0: 0.5, 1: 2.0, 2: 1.0, 3: 1.0}},
]
self.assertEqual([v.df.to_dict() for (k, v) in the_dict.items()], exp)
class TestBalanceDF__call_on_linked(BalanceTestCase):
def test_BalanceDF__call_on_linked(self):
self.assertEqual(
s1.weights()._call_on_linked("mean").values[0][0], (0.5 + 2 + 1 + 1) / 4
)
self.assertEqual(
s1.weights()._call_on_linked("mean"),
s3.weights()._call_on_linked("mean", exclude="target"),
)
self.assertEqual(
# it's tricky to compare nan values, so using fillna
s3.covars()._call_on_linked("mean").fillna(0).round(3).to_dict(),
{
"a": {"self": 1.889, "target": 2.429},
"b": {"self": -10.0, "target": 6.857},
"c[v]": {"self": 0.222, "target": 0},
"c[x]": {"self": 0.111, "target": 0.143},
"c[y]": {"self": 0.444, "target": 0.286},
"c[z]": {"self": 0.222, "target": 0.571},
},
)
self.assertEqual(
# it's tricky to compare nan values, so using fillna
# checking also on std, and on a larger object (with both self, target and unadjusted)
s3_null.covars()._call_on_linked("std").fillna(0).round(3).to_dict(),
{
"a": {"self": 0.886, "target": 0.964, "unadjusted": 0.886},
"b": {"self": 27.355, "target": 1.927, "unadjusted": 27.355},
"c[v]": {"self": 0.5, "target": 0.0, "unadjusted": 0.5},
"c[x]": {"self": 0.378, "target": 0.463, "unadjusted": 0.378},
"c[y]": {"self": 0.598, "target": 0.598, "unadjusted": 0.598},
"c[z]": {"self": 0.5, "target": 0.655, "unadjusted": 0.5},
},
)
# verify exclude works:
self.assertEqual(
s3.covars()._call_on_linked("mean", exclude=("self")).round(3).to_dict(),
{
"a": {"target": 2.429},
"b": {"target": 6.857},
"c[x]": {"target": 0.143},
"c[y]": {"target": 0.286},
"c[z]": {"target": 0.571},
},
)
self.assertEqual(
s3.covars()._call_on_linked("mean", exclude=("target")).round(3).to_dict(),
{
"a": {"self": 1.889},
"b": {"self": -10.0},
"c[v]": {"self": 0.222},
"c[x]": {"self": 0.111},
"c[y]": {"self": 0.444},
"c[z]": {"self": 0.222},
},
)
# Verify we can also access df (i.e.: an attribute)
self.assertEqual(
s3.covars()._call_on_linked("df").round(3).to_dict(),
{
"a": {"self": 1, "target": 3},
"b": {"self": -42, "target": 8},
"c": {"self": "v", "target": "z"},
},
)
class TestBalanceDF__descriptive_stats(BalanceTestCase):
def test_BalanceDF__descriptive_stats(self):
self.assertEqual(
s1.weights()._descriptive_stats("mean", weighted=False).values[0][0], 1.125
)
self.assertAlmostEqual(
s1.weights()._descriptive_stats("std", weighted=False).values[0][0],
0.62915286,
)
# Not that you would ever really want the weighted weights
self.assertEqual(
s1.weights()._descriptive_stats("mean", weighted=True).values[0][0], 1.125
)
self.assertAlmostEqual(
s1.weights()._descriptive_stats("std", weighted=True).values[0][0],
0.62915286,
)
self.assertAlmostEqual(
s1.covars()._descriptive_stats("mean", weighted=True)["a"][0], 1.88888888
)
# Test numeric_only and weighted flags
r = s1.covars()._descriptive_stats("mean", weighted=False, numeric_only=True)
e = pd.DataFrame({"a": [(1 + 2 + 3 + 1) / 4], "b": [(-42 + 8 + 2 - 42) / 4]})
self.assertEqual(r, e)
r = (
s1.covars()
._descriptive_stats("mean", weighted=False, numeric_only=False)
.sort_index(axis=1)
)
e = pd.DataFrame(
{
"a": [(1 + 2 + 3 + 1) / 4],
"b": [(-42 + 8 + 2 - 42) / 4],
"c[v]": [0.25],
"c[x]": [0.25],
"c[y]": [0.25],
"c[z]": [0.25],
}
)
self.assertEqual(r, e)
r = (
s1.covars()
._descriptive_stats("mean", weighted=True, numeric_only=True)
.sort_index(axis=1)
)
e = pd.DataFrame(
{
"a": [(1 * 0.5 + 2 * 2 + 3 + 1) / 4.5],
"b": [(-42 * 0.5 + 8 * 2 + 2 - 42) / 4.5],
}
)
self.assertEqual(r, e)
r = (
s1.covars()
._descriptive_stats("mean", weighted=True, numeric_only=False)
.sort_index(axis=1)
)
e = pd.DataFrame(
{
"a": [(1 * 0.5 + 2 * 2 + 3 + 1) / 4.5],
"b": [(-42 * 0.5 + 8 * 2 + 2 - 42) / 4.5],
"c[v]": [1 / 4.5],
"c[x]": [0.5 / 4.5],
"c[y]": [2 / 4.5],
"c[z]": [1 / 4.5],
}
)
self.assertEqual(r, e)
# Test with missing values and weights
s_ds = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, np.nan),
"c": ("a", "b", "c", "a"),
"id": (1, 2, 3, 4),
"w": (np.nan, 2, 1, 1), # np.nan makes it to a float64 dtype
}
),
id_column="id",
weight_column="w",
)
r = (
s_ds.covars()
._descriptive_stats("mean", weighted=True, numeric_only=False)
.sort_index(axis=1)
)
e = pd.DataFrame(
{
"_is_na_b[T.True]": [(1 * 1) / (2 + 1 + 1)],
"a": [(2 * 2 + 3 + 1) / (2 + 1 + 1)],
"b": [(8 * 2 + 2 * 1) / (2 + 1 + 1)],
"c[a]": [(1 * 1) / (2 + 1 + 1)],
"c[b]": [(1 * 2) / (2 + 1 + 1)],
"c[c]": [(1 * 1) / (2 + 1 + 1)],
}
)
self.assertEqual(r, e)
def test_Balance_df_summary_stats_numeric_only(self):
# Test that the asmd, std, and mean methods pass the `numeric_only`
# argument to _descriptive_stats
# Default is numeric_only=False
e_all = pd.Index(("a", "b", "c[x]", "c[y]", "c[z]", "c[v]"))
e_numeric_only = pd.Index(("a", "b"))
self.assertEqual(s1.covars().mean().columns, e_all, lazy=True)
self.assertEqual(s1.covars().mean(numeric_only=True).columns, e_numeric_only)
self.assertEqual(s1.covars().mean(numeric_only=False).columns, e_all, lazy=True)
self.assertEqual(s1.covars().std().columns, e_all, lazy=True)
self.assertEqual(s1.covars().std(numeric_only=True).columns, e_numeric_only)
self.assertEqual(s1.covars().std(numeric_only=False).columns, e_all, lazy=True)
class TestBalanceDF_mean(BalanceTestCase):
def test_BalanceDF_mean(self):
self.assertEqual(
s1.weights().mean(),
pd.DataFrame({"w": [1.125], "source": "self"}).set_index("source"),
)
self.assertEqual(
s3_null.covars().mean().fillna(0).round(3).to_dict(),
{
"a": {"self": 1.889, "target": 2.429, "unadjusted": 1.889},
"b": {"self": -10.0, "target": 6.857, "unadjusted": -10.0},
"c[v]": {"self": 0.222, "target": 0.0, "unadjusted": 0.222},
"c[x]": {"self": 0.111, "target": 0.143, "unadjusted": 0.111},
"c[y]": {"self": 0.444, "target": 0.286, "unadjusted": 0.444},
"c[z]": {"self": 0.222, "target": 0.571, "unadjusted": 0.222},
},
)
# test it works when we have columns with special characters
self.assertEqual(
s1_bad_columns.covars().mean().round(2).to_dict(),
{
"a_": {"self": 1.89},
"a__1": {"self": -10.0},
"c_[v]": {"self": 0.22},
"c_[x]": {"self": 0.11},
"c_[y]": {"self": 0.44},
"c_[z]": {"self": 0.22},
},
)
class TestBalanceDF_std(BalanceTestCase):
def test_BalanceDF_std(self):
self.assertEqual(
s1.weights().std(),
pd.DataFrame({"w": [0.6291529], "source": "self"}).set_index("source"),
)
self.assertEqual(
s3_null.covars().std().fillna(0).round(3).to_dict(),
{
"a": {"self": 0.886, "target": 0.964, "unadjusted": 0.886},
"b": {"self": 27.355, "target": 1.927, "unadjusted": 27.355},
"c[v]": {"self": 0.5, "target": 0.0, "unadjusted": 0.5},
"c[x]": {"self": 0.378, "target": 0.463, "unadjusted": 0.378},
"c[y]": {"self": 0.598, "target": 0.598, "unadjusted": 0.598},
"c[z]": {"self": 0.5, "target": 0.655, "unadjusted": 0.5},
},
)
class TestBalanceDF_var_of_mean(BalanceTestCase):
def test_BalanceDF_var_of_mean(self):
self.assertEqual(
s3_null.covars().var_of_mean().fillna(0).round(3).to_dict(),
{
"a": {"self": 0.112, "target": 0.163, "unadjusted": 0.112},
"b": {"self": 134.321, "target": 0.653, "unadjusted": 134.321},
"c[v]": {"self": 0.043, "target": 0.0, "unadjusted": 0.043},
"c[x]": {"self": 0.013, "target": 0.023, "unadjusted": 0.013},
"c[y]": {"self": 0.083, "target": 0.07, "unadjusted": 0.083},
"c[z]": {"self": 0.043, "target": 0.093, "unadjusted": 0.043},
},
)
class TestBalanceDF_ci(BalanceTestCase):
def test_BalanceDF_ci_of_mean(self):
self.assertEqual(
s3_null.covars().ci_of_mean(round_ndigits=3).fillna(0).to_dict(),
{
"a": {
"self": (1.232, 2.545),
"target": (1.637, 3.221),
"unadjusted": (1.232, 2.545),
},
"b": {
"self": (-32.715, 12.715),
"target": (5.273, 8.441),
"unadjusted": (-32.715, 12.715),
},
"c[v]": {
"self": (-0.183, 0.627),
"target": 0,
"unadjusted": (-0.183, 0.627),
},
"c[x]": {
"self": (-0.116, 0.338),
"target": (-0.156, 0.442),
"unadjusted": (-0.116, 0.338),
},
"c[y]": {
"self": (-0.12, 1.009),
"target": (-0.233, 0.804),
"unadjusted": (-0.12, 1.009),
},
"c[z]": {
"self": (-0.183, 0.627),
"target": (-0.027, 1.17),
"unadjusted": (-0.183, 0.627),
},
},
)
def test_BalanceDF_mean_with_ci(self):
self.assertEqual(
s_o2.outcomes().mean_with_ci().to_dict(),
{
"self": {
"_is_na_o2[False]": 0.75,
"_is_na_o2[True]": 0.25,
"o1": 8.5,
"o2": 6.0,
},
"target": {
"_is_na_o2[False]": 0.75,
"_is_na_o2[True]": 0.25,
"o1": 10.5,
"o2": 7.875,
},
"self_ci": {
"_is_na_o2[False]": (0.326, 1.174),
"_is_na_o2[True]": (-0.174, 0.674),
"o1": (7.404, 9.596),
"o2": (2.535, 9.465),
},
"target_ci": {
"_is_na_o2[False]": (0.45, 1.05),
"_is_na_o2[True]": (-0.05, 0.55),
"o1": (8.912, 12.088),
"o2": (4.351, 11.399),
},
},
)
class TestBalanceDF_asmd(BalanceTestCase):
def test_BalanceDF_asmd(self):
# Test with BalanceDF
r = BalanceDF._asmd_BalanceDF(
Sample.from_frame(
pd.DataFrame(
{"id": (1, 2), "a": (1, 2), "b": (-1, 12), "weight": (1, 2)}
)
).covars(),
Sample.from_frame(
pd.DataFrame(
{"id": (1, 2), "a": (3, 4), "b": (0, 42), "weight": (1, 2)}
)
).covars(),
).sort_index()
e_asmd = pd.Series(
(2.828_427_1, 0.684_658_9, (2.828_427_1 + 0.684_658_9) / 2),
index=("a", "b", "mean(asmd)"),
)
self.assertEqual(r, e_asmd)
with self.assertRaisesRegex(ValueError, "has no target set"):
s1.weights().asmd()
with self.assertRaisesRegex(ValueError, "has no target set"):
s3_null.outcomes().asmd()
self.assertEqual(
s3.covars().asmd().loc["self"],
pd.Series(
(
0.560055,
8.746742,
np.nan,
0.068579,
0.265606,
0.533422,
(
0.560055
+ 8.746742
+ 0.068579 * 0.25
+ 0.265606 * 0.25
+ 0.533422 * 0.25
)
/ 3,
),
index=("a", "b", "c[v]", "c[x]", "c[y]", "c[z]", "mean(asmd)"),
name="self",
),
)
self.assertEqual(
s3_null.covars().asmd().fillna(0).round(3).to_dict(),
{
"a": {"self": 0.56, "unadjusted": 0.56, "unadjusted - self": 0.0},
"b": {"self": 8.747, "unadjusted": 8.747, "unadjusted - self": 0.0},
"c[v]": {"self": 0.0, "unadjusted": 0.0, "unadjusted - self": 0.0},
"c[x]": {"self": 0.069, "unadjusted": 0.069, "unadjusted - self": 0.0},
"c[y]": {"self": 0.266, "unadjusted": 0.266, "unadjusted - self": 0.0},
"c[z]": {"self": 0.533, "unadjusted": 0.533, "unadjusted - self": 0.0},
"mean(asmd)": {
"self": 3.175,
"unadjusted": 3.175,
"unadjusted - self": 0.0,
},
},
)
# also check that on_linked_samples = False works:
self.assertEqual(
s3_null.covars().asmd(on_linked_samples=False).fillna(0).round(3).to_dict(),
{
"a": {"covars": 0.56},
"b": {"covars": 8.747},
"c[v]": {"covars": 0.0},
"c[x]": {"covars": 0.069},
"c[y]": {"covars": 0.266},
"c[z]": {"covars": 0.533},
"mean(asmd)": {"covars": 3.175},
},
)
self.assertEqual(
s3_null_madeup_weights.covars().asmd().fillna(0).round(3).to_dict(),
{
"a": {"self": 0.296, "unadjusted": 0.56, "unadjusted - self": 0.264},
"b": {"self": 8.154, "unadjusted": 8.747, "unadjusted - self": 0.593},
"c[v]": {"self": 0.0, "unadjusted": 0.0, "unadjusted - self": 0.0},
"c[x]": {"self": 0.0, "unadjusted": 0.069, "unadjusted - self": 0.069},
"c[y]": {"self": 0.0, "unadjusted": 0.266, "unadjusted - self": 0.266},
"c[z]": {
"self": 0.218,
"unadjusted": 0.533,
"unadjusted - self": 0.315,
},
"mean(asmd)": {
"self": 2.835,
"unadjusted": 3.175,
"unadjusted - self": 0.34,
},
},
)
def test_BalanceDF_asmd_improvement(self):
with self.assertRaisesRegex(
ValueError, "has no unadjusted set or unadjusted has no covars"
):
s3.covars().asmd_improvement()
s3_unadjusted = deepcopy(s3)
s3_unadjusted.set_weights((1, 1, 1, 1))
s3_2 = s3.set_unadjusted(s3_unadjusted)
self.assertEqual(s3_2.covars().asmd_improvement(), 0.3224900694460681)
s1_with_unadjusted = deepcopy(s1)
s1_with_unadjusted = s1.set_unadjusted(s3_unadjusted)
with self.assertRaisesRegex(
ValueError, "has no target set or target has no covars"
):
s1_with_unadjusted.covars().asmd_improvement()
self.assertEqual(s3_null.covars().asmd_improvement().round(3), 0)
self.assertEqual(
s3_null_madeup_weights.covars().asmd_improvement().round(3), 0.107
)
asmd_df = s3_null_madeup_weights.covars().asmd()
exp = round(
(asmd_df["mean(asmd)"][1] - asmd_df["mean(asmd)"][0])
/ asmd_df["mean(asmd)"][1],
3,
)
self.assertEqual(exp, 0.107)
self.assertEqual(
s3_null_madeup_weights.covars().asmd_improvement().round(3), exp
)
def test_BalanceDF_asmd_aggregate_by_main_covar(self):
# TODO: re-use this example across tests
# TODO: bugfix - adjust fails with apply_transform when inputting a df with categorical column :(
# Prepare dummy data
np.random.seed(112358)
d = pd.DataFrame(np.random.rand(1000, 3))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abc"[i] for i in range(0, 3)})
# make 'a' a categorical column in d
# d = d.assign(a=lambda x: pd.cut(x.a,[0,.25,.5,.75,1]))
d["a"] = pd.cut(d["a"], [0, 0.25, 0.5, 0.75, 1]).astype(str)
# make b "interesting" (so that the model would have something to do)
d["b"] = np.sqrt(d["b"])
s = Sample.from_frame(d)
d = pd.DataFrame(np.random.rand(1000, 3))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abc"[i] for i in range(0, 3)})
# make 'a' a categorical column in d
# d = d.assign(a=lambda x: pd.cut(x.a,[0,.25,.5,.75,1]))
d["a"] = pd.cut(d["a"], [0, 0.25, 0.5, 0.75, 1]).astype(str)
t = Sample.from_frame(d)
st = s.set_target(t)
# Fit IPW
a = st.adjust(max_de=1.5)
# Check ASMD
tmp_asmd_default = a.covars().asmd()
tmp_asmd_main_covar = a.covars().asmd(aggregate_by_main_covar=True)
outcome_default = tmp_asmd_default.round(2).to_dict()
outcome_main_covar = tmp_asmd_main_covar.round(2).to_dict()
expected_default = {
"a[(0.0, 0.25]]": {
"self": 0.04,
"unadjusted": 0.09,
"unadjusted - self": 0.05,
},
"a[(0.25, 0.5]]": {
"self": 0.0,
"unadjusted": 0.06,
"unadjusted - self": 0.06,
},
"a[(0.5, 0.75]]": {
"self": 0.0,
"unadjusted": 0.01,
"unadjusted - self": 0.01,
},
"a[(0.75, 1.0]]": {
"self": 0.04,
"unadjusted": 0.02,
"unadjusted - self": -0.02,
},
"c": {"self": 0.02, "unadjusted": 0.03, "unadjusted - self": 0.01},
"b": {"self": 0.14, "unadjusted": 0.6, "unadjusted - self": 0.46},
"mean(asmd)": {"self": 0.06, "unadjusted": 0.23, "unadjusted - self": 0.17},
}
expected_main_covar = {
"a": {"self": 0.02, "unadjusted": 0.05, "unadjusted - self": 0.02},
"b": {"self": 0.14, "unadjusted": 0.6, "unadjusted - self": 0.46},
"c": {"self": 0.02, "unadjusted": 0.03, "unadjusted - self": 0.01},
"mean(asmd)": {"self": 0.06, "unadjusted": 0.23, "unadjusted - self": 0.17},
}
self.assertEqual(outcome_default, expected_default)
self.assertEqual(outcome_main_covar, expected_main_covar)
class TestBalanceDF_to_download(BalanceTestCase):
def test_BalanceDF_to_download(self):
r = s1.covars().to_download()
self.assertIsInstance(r, IPython.display.FileLink)
class TestBalanceDF_to_csv(BalanceTestCase):
def test_BalanceDF_to_csv(self):
with tempfile.NamedTemporaryFile() as tf:
s1.weights().to_csv(path_or_buf=tf.name)
r = tf.read()
e = b"id,w\n1,0.5\n2,2.0\n3,1.0\n4,1.0\n"
self.assertEqual(r, e)
def test_BalanceDF_to_csv_first_default_argument_is_path(self):
with tempfile.NamedTemporaryFile() as tf:
s1.weights().to_csv(tf.name)
r = tf.read()
e = b"id,w\n1,0.5\n2,2.0\n3,1.0\n4,1.0\n"
self.assertEqual(r, e)
def test_BalanceDF_to_csv_output_with_no_path(self):
with tempfile.NamedTemporaryFile():
out = s1.weights().to_csv()
self.assertEqual(out, "id,w\n1,0.5\n2,2.0\n3,1.0\n4,1.0\n")
def test_BalanceDF_to_csv_output_with_path(self):
with tempfile.NamedTemporaryFile() as tf:
out = s1.weights().to_csv(path_or_buf=tf.name)
self.assertEqual(out, None)
class TestBalanceDF__df_with_ids(BalanceTestCase):
def test_BalanceDF__df_with_ids(self):
# Test it has an id column:
self.assertTrue("id" in s1.weights()._df_with_ids().columns)
self.assertTrue("id" in s1.covars()._df_with_ids().columns)
self.assertTrue("id" in s_o.outcomes()._df_with_ids().columns)
# Test it has df columns:
self.assertTrue("w" in s1.weights()._df_with_ids().columns)
self.assertEqual(
["id", "a", "b", "c"], s1.covars()._df_with_ids().columns.tolist()
)
self.assertEqual((4, 4), s1.covars()._df_with_ids().shape)
class TestBalanceDF_summary(BalanceTestCase):
def testBalanceDF_summary(self):
self.assertEqual(
s1.covars().summary().to_dict(),
{
"self": {
"a": 1.889,
"b": -10.0,
"c[v]": 0.222,
"c[x]": 0.111,
"c[y]": 0.444,
"c[z]": 0.222,
},
"self_ci": {
"a": (1.232, 2.545),
"b": (-32.715, 12.715),
"c[v]": (-0.183, 0.627),
"c[x]": (-0.116, 0.338),
"c[y]": (-0.12, 1.009),
"c[z]": (-0.183, 0.627),
},
},
)
s3_2 = s1.adjust(s2, method="null")
self.assertEqual(
s3_2.covars().summary().sort_index(axis=1).fillna(0).to_dict(),
{
"self": {
"a": 1.889,
"b": -10.0,
"c[v]": 0.222,
"c[x]": 0.111,
"c[y]": 0.444,
"c[z]": 0.222,
},
"self_ci": {
"a": (1.232, 2.545),
"b": (-32.715, 12.715),
"c[v]": (-0.183, 0.627),
"c[x]": (-0.116, 0.338),
"c[y]": (-0.12, 1.009),
"c[z]": (-0.183, 0.627),
},
"target": {
"a": 2.429,
"b": 6.857,
"c[v]": 0.0,
"c[x]": 0.143,
"c[y]": 0.286,
"c[z]": 0.571,
},
"target_ci": {
"a": (1.637, 3.221),
"b": (5.273, 8.441),
"c[v]": 0,
"c[x]": (-0.156, 0.442),
"c[y]": (-0.233, 0.804),
"c[z]": (-0.027, 1.17),
},
"unadjusted": {
"a": 1.889,
"b": -10.0,
"c[v]": 0.222,
"c[x]": 0.111,
"c[y]": 0.444,
"c[z]": 0.222,
},
"unadjusted_ci": {
"a": (1.232, 2.545),
"b": (-32.715, 12.715),
"c[v]": (-0.183, 0.627),
"c[x]": (-0.116, 0.338),
"c[y]": (-0.12, 1.009),
"c[z]": (-0.183, 0.627),
},
},
)
self.assertEqual(
s3_2.covars().summary(on_linked_samples=False).to_dict(),
{
0: {
"a": 1.889,
"b": -10.0,
"c[v]": 0.222,
"c[x]": 0.111,
"c[y]": 0.444,
"c[z]": 0.222,
},
"0_ci": {
"a": (1.232, 2.545),
"b": (-32.715, 12.715),
"c[v]": (-0.183, 0.627),
"c[x]": (-0.116, 0.338),
"c[y]": (-0.12, 1.009),
"c[z]": (-0.183, 0.627),
},
},
)
class TestBalanceDF__str__(BalanceTestCase):
def testBalanceDF__str__(self):
self.assertTrue(s1.outcomes().df.__str__() in s1.outcomes().__str__())
def test_BalanceOutcomesDF___str__(self):
# NOTE how the type is float even though the original input was integer.
self.assertTrue(
pd.DataFrame({"o": (7.0, 8.0, 9.0, 10.0)}).__str__() in o.__str__()
)
class TestBalanceDF__repr__(BalanceTestCase):
def test_BalanceWeightsDF___repr__(self):
repr = w.__repr__()
self.assertTrue("weights from" in repr)
self.assertTrue(object.__repr__(s1) in repr)
def test_BalanceCovarsDF___repr__(self):
repr = c.__repr__()
self.assertTrue("covars from" in repr)
self.assertTrue(object.__repr__(s1) in repr)
def test_BalanceOutcomesDF___repr__(self):
repr = o.__repr__()
self.assertTrue("outcomes from" in repr)
self.assertTrue(object.__repr__(s1) in repr)
class TestBalanceDF(BalanceTestCase):
def testBalanceDF_model_matrix(self):
self.assertEqual(
s1.covars().model_matrix().sort_index(axis=1).columns.values,
("a", "b", "c[v]", "c[x]", "c[y]", "c[z]"),
)
self.assertEqual(
s1.covars().model_matrix().to_dict(),
{
"a": {0: 1.0, 1: 2.0, 2: 3.0, 3: 1.0},
"b": {0: -42.0, 1: 8.0, 2: 2.0, 3: -42.0},
"c[v]": {0: 0.0, 1: 0.0, 2: 0.0, 3: 1.0},
"c[x]": {0: 1.0, 1: 0.0, 2: 0.0, 3: 0.0},
"c[y]": {0: 0.0, 1: 1.0, 2: 0.0, 3: 0.0},
"c[z]": {0: 0.0, 1: 0.0, 2: 1.0, 3: 0.0},
},
)
def test_check_if_not_BalanceDF(self):
with self.assertRaisesRegex(ValueError, "number must be balancedf_class"):
BalanceDF._check_if_not_BalanceDF(5, "number")
self.assertTrue(BalanceDF._check_if_not_BalanceDF(s3.covars()) is None)
| balance-main | tests/test_balancedf.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from copy import deepcopy
import balance.testutil
import numpy as np
import numpy.testing
import pandas as pd
# TODO: remove the use of balance_util in most cases, and just import the functions to be tested directly
from balance import util as balance_util
from balance.sample_class import Sample
from numpy import dtype
from patsy import dmatrix # pyre-ignore[21]: this module exists
from scipy.sparse import csc_matrix
class TestUtil(
balance.testutil.BalanceTestCase,
):
def test__check_weighting_methods_input(self):
self.assertRaisesRegex(
TypeError,
"sample_df must be a pandas DataFrame",
balance_util._check_weighting_methods_input,
df=1,
weights=pd.Series(1),
object_name="sample",
)
self.assertRaisesRegex(
TypeError,
"sample_weights must be a pandas Series",
balance_util._check_weighting_methods_input,
df=pd.DataFrame({"a": [1]}),
weights="a",
object_name="sample",
)
self.assertRaisesRegex(
ValueError,
"sample_weights must be the same length as sample_df",
balance_util._check_weighting_methods_input,
df=pd.DataFrame({"a": [1, 2]}),
weights=pd.Series([1]),
object_name="sample",
)
self.assertRaisesRegex(
ValueError,
"sample_df index must be the same as sample_weights index",
balance_util._check_weighting_methods_input,
df=pd.DataFrame({"a": [1, 2]}, index=[1, 2]),
weights=pd.Series([1, 1], index=[3, 4]),
object_name="sample",
)
def test_guess_id_column(self):
# test when id column is presented
df = pd.DataFrame(
{
"a": (0, 1, 2),
"id": (1, 2, 3),
}
)
self.assertEqual(balance_util.guess_id_column(df), "id")
self.assertWarnsRegexp(
"Guessed id column name id for the data",
balance_util.guess_id_column,
df,
)
# test when column_name is passed
df = pd.DataFrame(
{
"a": (0, 1, 2),
"b": (1, 2, 3),
}
)
self.assertEqual(balance_util.guess_id_column(df, column_name="b"), "b")
with self.assertRaisesRegex(
ValueError,
"Dataframe does not have column*",
):
balance_util.guess_id_column(df, column_name="c")
# test when no id column is passed and no id column in dataframe
with self.assertRaisesRegex(
ValueError,
"Cannot guess id column name for this DataFrame. Please provide a value in id_column",
):
balance_util.guess_id_column(df)
def test__isinstance_sample(self):
from balance.util import _isinstance_sample
s_df = pd.DataFrame(
{
"a": (0, 1, 2),
"b": (0, None, 2),
"c": ("a", "b", "a"),
"id": (1, 2, 3),
}
)
s = Sample.from_frame(s_df)
self.assertFalse(_isinstance_sample(s_df))
self.assertTrue(_isinstance_sample(s))
def test_add_na_indicator(self):
df = pd.DataFrame({"a": (0, None, 2, np.nan), "b": (None, "b", "", np.nan)})
e = pd.DataFrame(
{
"a": (0, 0, 2.0, 0),
"b": ("_NA", "b", "", "_NA"),
"_is_na_a": (False, True, False, True),
"_is_na_b": (True, False, False, True),
},
columns=("a", "b", "_is_na_a", "_is_na_b"),
)
r = balance_util.add_na_indicator(df)
self.assertEqual(r, e)
# No change if no missing variables
df = pd.DataFrame(
{"a": (0, 1, 2), "b": ("a", "b", ""), "c": pd.Categorical(("a", "b", "a"))}
)
self.assertEqual(balance_util.add_na_indicator(df), df)
# Test that it works with categorical variables
df = pd.DataFrame(
{
"c": pd.Categorical(("a", "b", "a", "b")),
"d": pd.Categorical(("a", "b", None, np.nan)),
}
)
e = pd.DataFrame(
{
"c": pd.Categorical(("a", "b", "a", "b")),
"d": pd.Categorical(
("a", "b", "_NA", "_NA"), categories=("a", "b", "_NA")
),
"_is_na_d": (False, False, True, True),
},
columns=("c", "d", "_is_na_d"),
)
self.assertEqual(balance_util.add_na_indicator(df), e)
# test arguments
df = pd.DataFrame({"a": (0, None, 2, np.nan), "b": (None, "b", "", np.nan)})
e = pd.DataFrame(
{
"a": (0.0, 42.0, 2.0, 42.0),
"b": ("AAA", "b", "", "AAA"),
"_is_na_a": (False, True, False, True),
"_is_na_b": (True, False, False, True),
},
columns=("a", "b", "_is_na_a", "_is_na_b"),
)
r = balance_util.add_na_indicator(df, replace_val_obj="AAA", replace_val_num=42)
self.assertEqual(r, e)
# check exceptions
d = pd.DataFrame({"a": [0, 1, np.nan, None], "b": ["x", "y", "_NA", None]})
self.assertRaisesRegex(
Exception,
"Can't add NA indicator to columns containing NAs and the value '_NA', ",
balance_util.add_na_indicator,
d,
)
d = pd.DataFrame({"a": [0, 1, np.nan, None], "_is_na_b": ["x", "y", "z", None]})
self.assertRaisesRegex(
Exception,
"Can't add NA indicator to DataFrame which contains",
balance_util.add_na_indicator,
d,
)
def test_drop_na_rows(self):
sample_df = pd.DataFrame(
{"a": (0, None, 2, np.nan), "b": (None, "b", "c", np.nan)}
)
sample_weights = pd.Series([1, 2, 3, 4])
(
sample_df,
sample_weights,
) = balance_util.drop_na_rows(sample_df, sample_weights, "sample")
self.assertEqual(sample_df, pd.DataFrame({"a": (2.0), "b": ("c")}, index=[2]))
self.assertEqual(sample_weights, pd.Series([3], index=[2]))
# check exceptions
sample_df = pd.DataFrame({"a": (None), "b": ("b")}, index=[1])
sample_weights = pd.Series([1])
self.assertRaisesRegex(
ValueError,
"Dropping rows led to empty",
balance_util.drop_na_rows,
sample_df,
sample_weights,
"sample",
)
def test_formula_generator(self):
self.assertEqual(balance_util.formula_generator("a"), "a")
self.assertEqual(balance_util.formula_generator(["a", "b", "c"]), "c + b + a")
# check exceptions
self.assertRaisesRegex(
Exception,
"This formula type is not supported",
balance_util.formula_generator,
["a", "b"],
"interaction",
)
def test_dot_expansion(self):
self.assertEqual(
balance_util.dot_expansion(".", ["a", "b", "c", "d"]), "(a+b+c+d)"
)
self.assertEqual(
balance_util.dot_expansion("b:(. - a)", ["a", "b", "c", "d"]),
"b:((a+b+c+d) - a)",
)
self.assertEqual(balance_util.dot_expansion("a*b", ["a", "b", "c", "d"]), "a*b")
d = {"a": ["a1", "a2", "a1", "a1"]}
df = pd.DataFrame(data=d)
self.assertEqual(balance_util.dot_expansion(".", list(df.columns)), "(a)")
# check exceptions
self.assertRaisesRegex(
Exception,
"Variables should not be empty. Please provide a list of strings.",
balance_util.dot_expansion,
".",
None,
)
self.assertRaisesRegex(
Exception,
"Variables should be a list of strings and have to be included.",
balance_util.dot_expansion,
".",
df,
)
def test_process_formula(self):
from patsy import EvalFactor, Term # pyre-ignore[21]: this module exists
f1 = balance_util.process_formula("a:(b+aab)", ["a", "b", "aab"])
self.assertEqual(
f1.rhs_termlist,
[
Term([EvalFactor("a"), EvalFactor("b")]),
Term([EvalFactor("a"), EvalFactor("aab")]),
],
)
f2 = balance_util.process_formula("a:(b+aab)", ["a", "b", "aab"], ["a", "b"])
self.assertEqual(
f2.rhs_termlist,
[
Term(
[
EvalFactor("C(a, one_hot_encoding_greater_2)"),
EvalFactor("C(b, one_hot_encoding_greater_2)"),
]
),
Term(
[EvalFactor("C(a, one_hot_encoding_greater_2)"), EvalFactor("aab")]
),
],
)
# check exceptions
self.assertRaisesRegex(
Exception,
"Not all factor variables are contained in variables",
balance_util.process_formula,
formula="a:(b+aab)",
variables=["a", "b", "aab"],
factor_variables="c",
)
def test_build_model_matrix(self):
df = pd.DataFrame(
{"a": ["a1", "a2", "a1", "a1"], "b": ["b1", "b2", "b3", "b3"]}
)
res = pd.DataFrame(
{"a[a1]": (1.0, 0.0, 1.0, 1.0), "a[a2]": (0.0, 1.0, 0.0, 0.0)}
)
# explicit formula
x_matrix = balance_util.build_model_matrix(df, "a")
self.assertEqual(x_matrix["model_matrix"], res)
self.assertEqual(x_matrix["model_matrix_columns"], res.columns.tolist())
# formula with dot
x_matrix = balance_util.build_model_matrix(df, ".")
res = pd.DataFrame(
{
"a[a1]": (1.0, 0.0, 1.0, 1.0),
"a[a2]": (0.0, 1.0, 0.0, 0.0),
"b[T.b2]": (0.0, 1.0, 0.0, 0.0),
"b[T.b3]": (0.0, 0.0, 1.0, 1.0),
}
)
self.assertEqual(x_matrix["model_matrix"], res)
self.assertEqual(x_matrix["model_matrix_columns"], res.columns.tolist())
# formula with factor_variables
x_matrix = balance_util.build_model_matrix(df, ".", factor_variables=["a"])
res = pd.DataFrame(
{
"C(a, one_hot_encoding_greater_2)[a2]": (0.0, 1.0, 0.0, 0.0),
"b[T.b2]": (0.0, 1.0, 0.0, 0.0),
"b[T.b3]": (0.0, 0.0, 1.0, 1.0),
}
)
self.assertEqual(x_matrix["model_matrix"], res)
self.assertEqual(x_matrix["model_matrix_columns"], res.columns.tolist())
# Sparse output
x_matrix = balance_util.build_model_matrix(df, "a", return_sparse=True)
res = [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 0.0]]
self.assertEqual(x_matrix["model_matrix"].toarray(), res)
self.assertEqual(x_matrix["model_matrix_columns"], ["a[a1]", "a[a2]"])
self.assertTrue(type(x_matrix["model_matrix"]) is csc_matrix)
# Check exceptions
self.assertRaisesRegex(
Exception,
"Not all factor variables are contained in df",
balance_util.build_model_matrix,
df,
formula="a",
factor_variables="c",
)
df = pd.DataFrame({"[a]": ["a1", "a2", "a1", "a1"]})
self.assertRaisesRegex(
Exception,
"Variable names cannot contain characters",
balance_util.build_model_matrix,
df,
"a",
)
# Int64Dtype input
df = pd.DataFrame({"a": [1, 2, 3, 4]})
df = df.astype(dtype={"a": "Int64"})
res = pd.DataFrame({"a": (1.0, 2.0, 3.0, 4.0)})
# explicit formula
x_matrix = balance_util.build_model_matrix(df, "a")
self.assertEqual(x_matrix["model_matrix"], res)
self.assertEqual(x_matrix["model_matrix_columns"], res.columns.tolist())
def test_model_matrix(self):
s_df = pd.DataFrame(
{
"a": (0, 1, 2),
"b": (0, None, 2),
"c": ("a", "b", "a"),
"id": (1, 2, 3),
}
)
s = Sample.from_frame(s_df)
# Tests on a single sample
e = pd.DataFrame(
{
"a": (0.0, 1.0, 2.0),
"b": (0.0, 0.0, 2.0),
"_is_na_b[T.True]": (0.0, 1.0, 0.0),
"c[a]": (1.0, 0.0, 1.0),
"c[b]": (0.0, 1.0, 0.0),
}
)
r = balance_util.model_matrix(s)
self.assertEqual(r["sample"], e, lazy=True)
self.assertTrue(r["target"] is None)
# Tests on a single sample dataframe
e = pd.DataFrame(
{
"a": (0.0, 1.0, 2.0),
"b": (0.0, 0.0, 2.0),
"_is_na_b[T.True]": (0.0, 1.0, 0.0),
"c[a]": (1.0, 0.0, 1.0),
"c[b]": (0.0, 1.0, 0.0),
}
)
r = balance_util.model_matrix(s_df[["a", "b", "c"]])
self.assertEqual(r["sample"].sort_index(axis=1), e, lazy=True)
# Tests on a single sample with a target
t = Sample.from_frame(
pd.DataFrame(
{
"a": (0, 1, 2, None),
"d": (0, 2, 2, 1),
"c": ("a", "b", "a", "c"),
"id": (1, 2, 3, 5),
}
)
)
r = balance_util.model_matrix(s, t)
e_s = pd.DataFrame(
{
"a": (0.0, 1.0, 2.0),
"_is_na_a[T.True]": (0.0, 0.0, 0.0),
"c[a]": (1.0, 0.0, 1.0),
"c[b]": (0.0, 1.0, 0.0),
"c[c]": (0.0, 0.0, 0.0),
}
)
e_t = pd.DataFrame(
{
"a": (0.0, 1.0, 2.0, 0.0),
"_is_na_a[T.True]": (0.0, 0.0, 0.0, 1.0),
"c[a]": (1.0, 0.0, 1.0, 0.0),
"c[b]": (0.0, 1.0, 0.0, 0.0),
"c[c]": (0.0, 0.0, 0.0, 1.0),
}
)
self.assertEqual(r["sample"].sort_index(axis=1), e_s, lazy=True)
self.assertEqual(r["target"].sort_index(axis=1), e_t, lazy=True)
# Test passing DataFrames rather than Samples
r = balance_util.model_matrix(
pd.DataFrame({"a": (0, 1, 2), "b": (0, None, 2), "c": ("a", "b", "a")}),
pd.DataFrame(
{"a": (0, 1, 2, None), "d": (0, 2, 2, 1), "c": ("a", "b", "a", "c")}
),
)
self.assertEqual(r["sample"].sort_index(axis=1), e_s, lazy=True)
self.assertEqual(r["target"].sort_index(axis=1), e_t, lazy=True)
# Check warnings for variables not present in both
self.assertWarnsRegexp(
"Ignoring variables not present in all Samples",
balance_util.model_matrix,
s,
t,
)
# Test zero rows warning:
self.assertRaisesRegex(
AssertionError,
"sample must have more than zero rows",
balance_util.model_matrix,
pd.DataFrame(),
)
# Tests on a single DataFrame with bad column names
s_df_bad_col_names = pd.DataFrame(
{
"a * / |a": (0, 1, 2),
"b b": (0, None, 2),
"c._$c": ("a", "b", "a"),
"id": (1, 2, 3),
}
)
r = balance_util.model_matrix(s_df_bad_col_names)
exp = ["_is_na_b__b[T.True]", "a______a", "b__b", "c___c[a]", "c___c[b]", "id"]
self.assertEqual(r["model_matrix_columns_names"], exp)
exp = {
"_is_na_b__b[T.True]": {0: 0.0, 1: 1.0, 2: 0.0},
"a______a": {0: 0.0, 1: 1.0, 2: 2.0},
"b__b": {0: 0.0, 1: 0.0, 2: 2.0},
"c___c[a]": {0: 1.0, 1: 0.0, 2: 1.0},
"c___c[b]": {0: 0.0, 1: 1.0, 2: 0.0},
"id": {0: 1.0, 1: 2.0, 2: 3.0},
}
self.assertEqual(r["sample"].to_dict(), exp)
# Tests that we can handle multiple columns what would be turned to have the same column name
s_df_bad_col_names = pd.DataFrame(
{
"b1 ": (0, 1, 2),
"b1*": (0, None, 2000),
"b1_": (3, 30, 300),
"b1$": ["a", "b", "c"],
"id": (1, 2, 3),
}
)
r = balance_util.model_matrix(s_df_bad_col_names)
exp = [
"_is_na_b1_[T.True]",
"b1_",
"b1__1",
"b1__2",
"b1__3[a]",
"b1__3[b]",
"b1__3[c]",
"id",
]
self.assertEqual(r["model_matrix_columns_names"], exp)
# r["sample"].to_dict()
exp = {
"_is_na_b1_[T.True]": {0: 0.0, 1: 1.0, 2: 0.0},
"b1_": {0: 0.0, 1: 1.0, 2: 2.0},
"b1__1": {0: 0.0, 1: 0.0, 2: 2000.0},
"b1__2": {0: 3.0, 1: 30.0, 2: 300.0},
"b1__3[a]": {0: 1.0, 1: 0.0, 2: 0.0},
"b1__3[b]": {0: 0.0, 1: 1.0, 2: 0.0},
"b1__3[c]": {0: 0.0, 1: 0.0, 2: 1.0},
"id": {0: 1.0, 1: 2.0, 2: 3.0},
}
self.assertEqual(r["sample"].to_dict(), exp)
def test_model_matrix_arguments(self):
s_df = pd.DataFrame(
{
"a": (0, 1, 2),
"b": (0, None, 2),
"c": ("a", "b", "a"),
"id": (1, 2, 3),
}
)
s = Sample.from_frame(s_df)
t = Sample.from_frame(
pd.DataFrame(
{
"a": (0, 1, 2, None),
"d": (0, 2, 2, 1),
"c": ("a", "b", "a", "c"),
"id": (1, 2, 3, 5),
}
)
)
# Test variables argument
r = balance_util.model_matrix(s, variables="c")
e = pd.DataFrame({"c[a]": (1.0, 0.0, 1.0), "c[b]": (0.0, 1.0, 0.0)})
self.assertEqual(r["sample"], e)
self.assertTrue(r["target"] is None)
# Single covariate which doesn't exist in both should raise error
self.assertRaisesRegex(
Exception,
"requested variables are not in all Samples",
balance_util.model_matrix,
s,
t,
"b",
)
# Test add_na argument
e = pd.DataFrame(
{"a": (0.0, 2.0), "b": (0.0, 2.0), "c[a]": (1.0, 1.0), "c[b]": (0.0, 0.0)},
index=(0, 2),
)
r = balance_util.model_matrix(s, add_na=False)
self.assertWarnsRegexp(
"Dropping all rows with NAs", balance_util.model_matrix, s, add_na=False
)
self.assertEqual(r["sample"].sort_index(axis=1), e)
self.assertTrue(r["target"] is None)
# Test return_type argument
r = balance_util.model_matrix(s, t, return_type="one")["model_matrix"]
e_s = pd.DataFrame(
{
"a": (0.0, 1.0, 2.0),
"_is_na_a[T.True]": (0.0, 0.0, 0.0),
"c[a]": (1.0, 0.0, 1.0),
"c[b]": (0.0, 1.0, 0.0),
"c[c]": (0.0, 0.0, 0.0),
}
)
e_t = pd.DataFrame(
{
"a": (0.0, 1.0, 2.0, 0.0),
"_is_na_a[T.True]": (0.0, 0.0, 0.0, 1.0),
"c[a]": (1.0, 0.0, 1.0, 0.0),
"c[b]": (0.0, 1.0, 0.0, 0.0),
"c[c]": (0.0, 0.0, 0.0, 1.0),
}
)
self.assertEqual(r.sort_index(axis=1), pd.concat((e_s, e_t)), lazy=True)
# Test return_var_type argument
r = balance_util.model_matrix(
s, t, return_type="one", return_var_type="dataframe"
)["model_matrix"]
self.assertEqual(r.sort_index(axis=1), pd.concat((e_s, e_t)), lazy=True)
r = balance_util.model_matrix(s, t, return_type="one", return_var_type="matrix")
self.assertEqual(
r["model_matrix"],
pd.concat((e_s, e_t))
.reindex(columns=r["model_matrix_columns_names"])
.values,
)
r = balance_util.model_matrix(s, t, return_type="one", return_var_type="sparse")
self.assertEqual(
r["model_matrix"].toarray(),
pd.concat((e_s, e_t))
.reindex(columns=r["model_matrix_columns_names"])
.values,
)
self.assertEqual(
r["model_matrix_columns_names"],
["_is_na_a[T.True]", "a", "c[a]", "c[b]", "c[c]"],
)
self.assertTrue(type(r["model_matrix"]) is csc_matrix)
# Test formula argument
self.assertEqual(
balance_util.model_matrix(s, formula="a + b")["sample"].sort_index(axis=1),
pd.DataFrame({"a": (0.0, 1.0, 2.0), "b": (0.0, 0.0, 2.0)}),
)
self.assertEqual(
balance_util.model_matrix(s, formula="b ")["sample"].sort_index(axis=1),
pd.DataFrame({"b": (0.0, 0.0, 2.0)}),
)
self.assertEqual(
balance_util.model_matrix(s, formula="a * c ")["sample"].sort_index(axis=1),
pd.DataFrame(
{
"a": (0.0, 1.0, 2.0),
"a:c[T.b]": (0.0, 1.0, 0.0),
"c[a]": (1.0, 0.0, 1.0),
"c[b]": (0.0, 1.0, 0.0),
}
),
)
self.assertEqual(
balance_util.model_matrix(s, formula=["a", "b"])["sample"].sort_index(
axis=1
),
pd.DataFrame({"a": (0.0, 1.0, 2.0), "b": (0.0, 0.0, 2.0)}),
)
# Test penalty_factor argument
self.assertEqual(
balance_util.model_matrix(s, formula=["a", "b"])["penalty_factor"],
np.array([1, 1]),
)
self.assertEqual(
balance_util.model_matrix(s, formula=["a", "b"], penalty_factor=[1, 2])[
"penalty_factor"
],
np.array([1, 2]),
)
self.assertEqual(
balance_util.model_matrix(s, formula="a+b", penalty_factor=[2])[
"penalty_factor"
],
np.array([2, 2]),
)
self.assertRaisesRegex(
AssertionError,
"penalty factor and formula must have the same length",
balance_util.model_matrix,
s,
formula="a+b",
penalty_factor=[1, 2],
)
# Test one_hot_encoding argument
e = pd.DataFrame(
{
"C(_is_na_b, one_hot_encoding_greater_2)[True]": (0.0, 1.0, 0.0),
"C(c, one_hot_encoding_greater_2)[b]": (0.0, 1.0, 0.0),
"a": (0.0, 1.0, 2.0),
"b": (0.0, 0.0, 2.0),
}
)
r = balance_util.model_matrix(s, one_hot_encoding=True)
self.assertEqual(r["sample"].sort_index(axis=1), e, lazy=True)
def test_qcut(self):
d = pd.Series([0, 1, 2, 3, 4])
self.assertEqual(
balance_util.qcut(d, 4).astype(str),
pd.Series(
[
"(-0.001, 1.0]",
"(-0.001, 1.0]",
"(1.0, 2.0]",
"(2.0, 3.0]",
"(3.0, 4.0]",
]
),
)
self.assertEqual(balance_util.qcut(d, 6), d)
self.assertWarnsRegexp(
"Not quantizing, too few values",
balance_util.qcut,
d,
6,
)
def test_quantize(self):
d = pd.DataFrame(np.random.rand(1000, 2))
d = d.rename(columns={i: "ab"[i] for i in range(0, 2)})
d["c"] = ["x"] * 1000
r = balance_util.quantize(d, variables=("a"))
self.assertTrue(isinstance(r["a"][0], pd.Interval))
self.assertTrue(isinstance(r["b"][0], float))
self.assertTrue(r["c"][0] == "x")
r = balance_util.quantize(d)
self.assertTrue(isinstance(r["a"][0], pd.Interval))
self.assertTrue(isinstance(r["b"][0], pd.Interval))
self.assertTrue(r["c"][0] == "x")
# Test that it does not affect categorical columns
d["d"] = pd.Categorical(["y"] * 1000)
r = balance_util.quantize(d)
self.assertTrue(r["d"][0] == "y")
# Test on Series input
r = balance_util.quantize(pd.Series(np.random.uniform(0, 1, 100)), 7)
self.assertTrue(len(set(r.values)) == 7)
# Test on numpy array input
r = balance_util.quantize(np.random.uniform(0, 1, 100), 7)
self.assertTrue(len(set(r.values)) == 7)
# Test on single integer input
r = balance_util.quantize(1, 1)
self.assertTrue(len(set(r.values)) == 1)
def test_row_pairwise_diffs(self):
d = pd.DataFrame({"a": (1, 2, 3), "b": (-42, 8, 2)})
e = pd.DataFrame(
{"a": (1, 2, 3, 1, 2, 1), "b": (-42, 8, 2, 50, 44, -6)},
index=(0, 1, 2, "1 - 0", "2 - 0", "2 - 1"),
)
self.assertEqual(balance_util.row_pairwise_diffs(d), e)
def test_isarraylike(self):
self.assertFalse(balance_util._is_arraylike(""))
self.assertFalse(balance_util._is_arraylike("test"))
self.assertTrue(balance_util._is_arraylike(()))
self.assertTrue(balance_util._is_arraylike([]))
self.assertTrue(balance_util._is_arraylike([1, 2]))
self.assertTrue(balance_util._is_arraylike(range(10)))
self.assertTrue(balance_util._is_arraylike(np.array([1, 2, "a"])))
self.assertTrue(balance_util._is_arraylike(pd.Series((1, 2, 3))))
def test_rm_mutual_nas(self):
from balance.util import rm_mutual_nas
self.assertEqual(rm_mutual_nas([1, 2, 3], [2, 3, None]), [[1, 2], [2.0, 3.0]])
d = np.array((0, 1, 2))
numpy.testing.assert_array_equal(rm_mutual_nas(d), d)
d2 = np.array((5, 6, 7))
numpy.testing.assert_array_equal(rm_mutual_nas(d, d2), (d, d2))
r = rm_mutual_nas(d, d2, None)
for i, j in zip(r, (d, d2, None)):
numpy.testing.assert_array_equal(i, j)
# test exceptions
d3a = np.array((5, 6, 7, 8))
self.assertRaisesRegex(
ValueError,
"All arrays must be of same length",
rm_mutual_nas,
d,
d3a,
)
d3b = "a"
self.assertRaisesRegex(
ValueError,
"All arguments must be arraylike",
rm_mutual_nas,
d3b,
d3b,
)
d4 = np.array((np.nan, 9, -np.inf))
e = [np.array((1,)), np.array((6,)), np.array((9,))]
r = rm_mutual_nas(d, d2, d4)
for i, j in zip(r, e):
print("A", i, j)
numpy.testing.assert_array_equal(i, j)
r = rm_mutual_nas(d, d2, d4, None)
for i, j in zip(r, e):
numpy.testing.assert_array_equal(i, j)
d5 = np.array(("a", "b", "c"))
numpy.testing.assert_array_equal(rm_mutual_nas(d5), d5)
e = [np.array((9,)), np.array(("b",))]
r = rm_mutual_nas(d4, d5)
for i, j in zip(r, e):
numpy.testing.assert_array_equal(i, j)
# Single arraylike
d = np.array((0, 1, 2, None))
numpy.testing.assert_array_equal(rm_mutual_nas(d), (0, 1, 2))
d = np.array((0, 1, 2, np.nan))
numpy.testing.assert_array_equal(rm_mutual_nas(d), (0, 1, 2))
d = np.array(("a", "b", None))
numpy.testing.assert_array_equal(rm_mutual_nas(d), ("a", "b"))
d = np.array(("a", 1, None))
# NOTE: In the next test we must define that `dtype=object`
# since this dtype is preserved from d. Otherwise, using np.array(("a", 1)) will have
# a dtype of '<U1'
numpy.testing.assert_array_equal(
rm_mutual_nas(d), np.array(("a", 1), dtype=object)
)
self.assertTrue(isinstance(rm_mutual_nas(d), np.ndarray))
d = (0, 1, 2, None)
numpy.testing.assert_array_equal(rm_mutual_nas(d), (0, 1, 2))
d = ("a", "b", None)
numpy.testing.assert_array_equal(rm_mutual_nas(d), ("a", "b"))
d = ("a", 1, None)
numpy.testing.assert_array_equal(rm_mutual_nas(d), ("a", 1))
self.assertTrue(isinstance(rm_mutual_nas(d), tuple))
# Should only accept array like or none arguments
self.assertRaises(ValueError, rm_mutual_nas, d, "a")
# Make sure we can deal with various np and pd arrays
x1 = pd.array([1, 2, None, np.nan, pd.NA, 3])
x2 = pd.array([1.1, 2, 3, None, np.nan, pd.NA])
x3 = pd.array([1.1, 2, 3, 4, 5, 6])
x4 = pd.array(["1.1", 2, 3, None, np.nan, pd.NA])
x5 = pd.array(["1.1", "2", "3", None, np.nan, pd.NA], dtype="string")
x6 = np.array([1, 2, 3.3, 4, 5, 6])
x7 = np.array([1, 2, 3.3, 4, "5", "6"])
x8 = [1, 2, 3.3, 4, "5", "6"]
# The values we expect to see after using rm_mutual_nas:
self.assertEqual(
[list(x) for x in rm_mutual_nas(x1, x2, x3, x4, x5, x6, x7, x8)],
[
[1, 2],
[1.1, 2],
[1.1, 2.0],
["1.1", 2],
["1.1", "2"],
[1.0, 2.0],
["1", "2"],
[1, 2],
],
)
# The types before and after the na removal will remain the same:
self.assertEqual(
[type(x) for x in rm_mutual_nas(x1, x2, x3, x4, x5, x6, x7, x8)],
[type(x) for x in (x1, x2, x3, x4, x5, x6, x7, x8)],
)
self.assertEqual(
[type(x) for x in rm_mutual_nas(x1, x4, x5, x6, x7, x8)],
[
pd.core.arrays.integer.IntegerArray,
pd.core.arrays.numpy_.PandasArray,
pd.core.arrays.string_.StringArray,
np.ndarray,
np.ndarray,
list,
],
)
# NOTE: pd.FloatingArray were only added in pandas version 1.2.0.
# Before that, they were called PandasArray. For details, see:
# https://pandas.pydata.org/docs/dev/reference/api/pandas.arrays.FloatingArray.html
if pd.__version__ < "1.2.0":
e = [
pd.core.arrays.numpy_.PandasArray,
pd.core.arrays.numpy_.PandasArray,
]
else:
e = [
pd.core.arrays.floating.FloatingArray,
pd.core.arrays.floating.FloatingArray,
]
self.assertEqual([type(x) for x in rm_mutual_nas(x2, x3)], e)
# The dtype before and after the na removal will remain the same: (only relevant for np and pd arrays)
self.assertEqual(
[x.dtype for x in rm_mutual_nas(x1, x2, x3, x4, x5, x6, x7)],
[x.dtype for x in (x1, x2, x3, x4, x5, x6, x7)],
)
# The dtypes:
# [Int64Dtype(),
# PandasDtype('object'),
# PandasDtype('float64'),
# PandasDtype('object'),
# StringDtype,
# dtype('float64'),
# dtype('<U32')]
# Preserve index in pd.Series input
x1 = pd.Series([1, 2, 3, 4])
x2 = pd.Series([np.nan, 2, 3, 4])
x3 = np.array([1, 2, 3, 4])
# When there is nothing to remove, the original pd.Series will be returned with proper index:
self.assertEqual(rm_mutual_nas(x1, x3)[0].to_dict(), {0: 1, 1: 2, 2: 3, 3: 4})
self.assertEqual(
rm_mutual_nas(x1.sort_values(ascending=False), x3)[0].to_dict(),
{3: 4, 2: 3, 1: 2, 0: 1},
)
# Index is not changed also when na values are omitted:
self.assertEqual(rm_mutual_nas(x1, x2)[0].to_dict(), {1: 2, 2: 3, 3: 4})
# The order of the Series can be is changed, but the indexes remain the same
self.assertEqual(
rm_mutual_nas(x1.sort_values(ascending=False), x2)[0].to_dict(),
{3: 4, 2: 3, 1: 2},
)
def test_choose_variables(self):
from balance.util import choose_variables
# For one dataframe
self.assertEqual(
choose_variables(pd.DataFrame({"a": [1], "b": [2]})),
["a", "b"],
)
# For two dataframes
# Not providing variables
self.assertEqual(
choose_variables(
pd.DataFrame({"a": [1], "b": [2]}),
pd.DataFrame({"c": [1], "b": [2]}),
variables="",
),
["b"],
)
self.assertEqual(
choose_variables(
pd.DataFrame({"a": [1], "b": [2]}), pd.DataFrame({"c": [1], "b": [2]})
),
["b"],
)
self.assertWarnsRegexp(
"Ignoring variables not present in all Samples",
choose_variables,
pd.DataFrame({"a": [1], "b": [2]}),
pd.DataFrame({"c": [1], "d": [2]}),
)
self.assertWarnsRegexp(
"Sample and target have no variables in common",
choose_variables,
pd.DataFrame({"a": [1], "b": [2]}),
pd.DataFrame({"c": [1], "d": [2]}),
)
self.assertEqual(
choose_variables(
pd.DataFrame({"a": [1], "b": [2]}), pd.DataFrame({"c": [1], "d": [2]})
),
[],
)
with self.assertRaisesRegex(
ValueError, "requested variables are not in all Samples"
):
choose_variables(
pd.DataFrame({"a": [1], "b": [2]}),
pd.DataFrame({"c": [1], "b": [2]}),
variables="a",
)
# Three dataframes
self.assertEqual(
choose_variables(
pd.DataFrame({"a": [1], "b": [2], "c": [2]}),
pd.DataFrame({"c": [1], "b": [2]}),
pd.DataFrame({"a": [1], "b": [2]}),
),
["b"],
)
df1 = pd.DataFrame({"a": [1], "b": [2], "c": [2]})
df2 = pd.DataFrame({"c": [1], "b": [2]})
with self.assertRaisesRegex(
ValueError, "requested variables are not in all Samples: {'a'}"
):
choose_variables(df1, df2, variables=("a", "b", "c"))
# Control order
df1 = pd.DataFrame(
{"A": [1, 2], "B": [3, 4], "C": [5, 6], "E": [1, 1], "F": [1, 1]}
)
df2 = pd.DataFrame(
{"C": [7, 8], "J": [9, 10], "B": [11, 12], "K": [1, 1], "A": [1, 1]}
)
self.assertEqual(
choose_variables(df1, df2),
["A", "B", "C"],
)
self.assertEqual(
choose_variables(df1, df2, df_for_var_order=1),
["C", "B", "A"],
)
self.assertEqual(
choose_variables(df1, df2, variables=["B", "A"]),
["B", "A"],
)
def test_auto_spread(self):
data = pd.DataFrame(
{
"id": (1, 1, 2, 2, 3),
"key": ("a", "b", "b", "a", "a"),
"value": (1, 1, 2, 2, 4),
}
)
expected = pd.DataFrame(
{
"id": (1, 2, 3),
"key_a_value": (1.0, 2.0, 4.0),
"key_b_value": (1.0, 2.0, np.nan),
},
columns=("id", "key_a_value", "key_b_value"),
)
self.assertEqual(expected, balance_util.auto_spread(data))
data = pd.DataFrame(
{
"id": (1, 1, 2, 2, 3),
"key": ("a", "b", "b", "a", "a"),
"value": (1, 1, 2, 2, 4),
"other_value": (2, 2, 4, 4, 6),
}
)
self.assertEqual(
expected, balance_util.auto_spread(data, features=["key", "value"])
)
expected = pd.DataFrame(
{
"id": (1, 2, 3),
"key_a_value": (1.0, 2.0, 4.0),
"key_b_value": (1.0, 2.0, np.nan),
"key_a_other_value": (2.0, 4.0, 6.0),
"key_b_other_value": (2.0, 4.0, np.nan),
},
columns=(
"id",
"key_a_other_value",
"key_b_other_value",
"key_a_value",
"key_b_value",
),
)
self.assertEqual(expected, balance_util.auto_spread(data), lazy=True)
data = pd.DataFrame(
{
"id": (1, 1, 2, 2, 3),
"key": ("a", "a", "c", "d", "a"),
"value": (1, 1, 2, 4, 1),
}
)
self.assertWarnsRegexp("no unique groupings", balance_util.auto_spread, data)
def test_auto_spread_multiple_groupings(self):
# Multiple possible groupings
data = pd.DataFrame(
{
"id": (1, 1, 2, 2, 3),
"key": ("a", "b", "b", "a", "a"),
"value": (1, 3, 2, 4, 1),
}
)
expected = pd.DataFrame(
{
"id": (1, 2, 3),
"key_a_value": (1.0, 4.0, 1.0),
"key_b_value": (3.0, 2.0, np.nan),
},
columns=("id", "key_a_value", "key_b_value"),
)
self.assertEqual(expected, balance_util.auto_spread(data))
self.assertWarnsRegexp("2 possible groupings", balance_util.auto_spread, data)
def test_auto_aggregate(self):
r = balance_util.auto_aggregate(
pd.DataFrame(
{"x": [1, 2, 3, 4], "y": [1, 1, 1, np.nan], "id": [1, 1, 2, 3]}
)
)
e = pd.DataFrame({"id": [1, 2, 3], "x": [3, 3, 4], "y": [2, 1, np.nan]})
self.assertEqual(r, e, lazy=True)
self.assertRaises(
ValueError,
balance_util.auto_aggregate,
pd.DataFrame({"b": ["a", "b", "b"], "id": [1, 1, 2]}),
)
self.assertRaises(
ValueError,
balance_util.auto_aggregate,
r,
None,
"id2",
)
self.assertRaises(
ValueError,
balance_util.auto_aggregate,
r,
None,
aggfunc="not_sum",
)
def test_fct_lump(self):
# Count above the threshold, value preserved
s = pd.Series(["a"] * 95 + ["b"] * 5)
self.assertEqual(balance_util.fct_lump(s), s)
# Move the threshold up
self.assertEqual(
balance_util.fct_lump(s, 0.10),
pd.Series(["a"] * 95 + ["_lumped_other"] * 5),
)
# Default threshold, slightly below number of values
self.assertEqual(
balance_util.fct_lump(pd.Series(["a"] * 96 + ["b"] * 4)),
pd.Series(["a"] * 96 + ["_lumped_other"] * 4),
)
# Multiple categories combined
self.assertEqual(
balance_util.fct_lump(pd.Series(["a"] * 96 + ["b"] * 2 + ["c"] * 2)),
pd.Series(["a"] * 96 + ["_lumped_other"] * 4),
)
# Category already called '_lumped_other' is handled
self.assertEqual(
balance_util.fct_lump(pd.Series(["a"] * 96 + ["_lumped_other"] * 4)),
pd.Series(["a"] * 96 + ["_lumped_other_lumped_other"] * 4),
)
# Categorical series type
self.assertEqual(
balance_util.fct_lump(pd.Series(["a"] * 96 + ["b"] * 4, dtype="category")),
pd.Series(["a"] * 96 + ["_lumped_other"] * 4),
)
# Categorical model matrix is equal to string model matrix
# Load and process test data
from sklearn import datasets
wine_df = pd.DataFrame(datasets.load_wine().data)
wine_df.columns = datasets.load_wine().feature_names
wine_df = wine_df.rename(
columns={"od280/od315_of_diluted_wines": "od280_od315_of_diluted_wines"}
)
wine_df["id"] = pd.Series(
range(1, len(wine_df) + 1)
) # Create a fake id variable, required by balance
wine_df.alcohol = pd.cut(
wine_df.alcohol, bins=[0, 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 100]
)
# Create a version of the dataset that treats factor variable as character
wine_df_copy = wine_df.copy(deep=True)
wine_df_copy.alcohol = wine_df_copy.alcohol.astype("object")
# Split into "survey" and "population" datasets based on "wine class"
wine_class = pd.Series(datasets.load_wine().target)
wine_survey = Sample.from_frame(wine_df.loc[wine_class == 0, :])
wine_pop = Sample.from_frame(wine_df.loc[wine_class != 0, :])
wine_survey = wine_survey.set_target(wine_pop)
wine_survey_copy = Sample.from_frame(wine_df_copy.loc[wine_class == 0, :])
wine_pop_copy = Sample.from_frame(wine_df_copy.loc[wine_class != 0, :])
wine_survey_copy = wine_survey_copy.set_target(wine_pop_copy)
# Generate weights
output_cat_var = wine_survey.adjust(
transformations={
"alcohol": lambda x: balance_util.fct_lump(x, prop=0.05),
"flavanoids": balance_util.quantize,
"total_phenols": balance_util.quantize,
"nonflavanoid_phenols": balance_util.quantize,
"color_intensity": balance_util.quantize,
"hue": balance_util.quantize,
"ash": balance_util.quantize,
"alcalinity_of_ash": balance_util.quantize,
"malic_acid": balance_util.quantize,
"magnesium": balance_util.quantize,
}
)
output_string_var = wine_survey_copy.adjust(
transformations={
"alcohol": lambda x: balance_util.fct_lump(x, prop=0.05),
"flavanoids": balance_util.quantize,
"total_phenols": balance_util.quantize,
"nonflavanoid_phenols": balance_util.quantize,
"color_intensity": balance_util.quantize,
"hue": balance_util.quantize,
"ash": balance_util.quantize,
"alcalinity_of_ash": balance_util.quantize,
"malic_acid": balance_util.quantize,
"magnesium": balance_util.quantize,
}
)
# Check that model coefficients are identical in categorical and string variable coding
self.assertEqual(
output_cat_var.model()["perf"]["coefs"],
output_string_var.model()["perf"]["coefs"],
)
def test_fct_lump_by(self):
# test by argument works
s = pd.Series([1, 1, 1, 2, 3, 1, 2])
by = pd.Series(["a", "a", "a", "a", "a", "b", "b"])
self.assertEqual(
balance_util.fct_lump_by(s, by, 0.5),
pd.Series([1, 1, 1, "_lumped_other", "_lumped_other", 1, 2]),
)
# test case where all values in 'by' are the same
s = pd.Series([1, 1, 1, 2, 3, 1, 2])
by = pd.Series(["a", "a", "a", "a", "a", "a", "a"])
self.assertEqual(
balance_util.fct_lump_by(s, by, 0.5),
pd.Series(
[1, 1, 1, "_lumped_other", "_lumped_other", 1, "_lumped_other"],
name="a",
),
)
# test fct_lump_by doesn't affect indices when combining dataframes
s = pd.DataFrame({"d": [1, 1, 1], "e": ["a1", "a2", "a1"]}, index=(0, 6, 7))
t = pd.DataFrame(
{"d": [2, 3, 1, 2], "e": ["a2", "a2", "a1", "a2"]}, index=(0, 1, 2, 3)
)
df = pd.concat([s, t])
r = balance_util.fct_lump_by(df.d, df.e, 0.5)
e = pd.Series(
[1, "_lumped_other", 1, 2, "_lumped_other", 1, 2],
index=(0, 6, 7, 0, 1, 2, 3),
name="d",
)
self.assertEqual(r, e)
def test_one_hot_encoding_greater_2(self):
from balance.util import one_hot_encoding_greater_2 # noqa
d = {
"a": ["a1", "a2", "a1", "a1"],
"b": ["b1", "b2", "b3", "b3"],
"c": ["c1", "c1", "c1", "c1"],
}
df = pd.DataFrame(data=d)
res = dmatrix("C(a, one_hot_encoding_greater_2)", df, return_type="dataframe")
expected = {
"Intercept": [1.0, 1.0, 1.0, 1.0],
"C(a, one_hot_encoding_greater_2)[a2]": [0.0, 1.0, 0.0, 0.0],
}
expected = pd.DataFrame(data=expected)
self.assertEqual(res, expected)
res = dmatrix("C(b, one_hot_encoding_greater_2)", df, return_type="dataframe")
expected = {
"Intercept": [1.0, 1.0, 1.0, 1.0],
"C(b, one_hot_encoding_greater_2)[b1]": [1.0, 0.0, 0.0, 0.0],
"C(b, one_hot_encoding_greater_2)[b2]": [0.0, 1.0, 0.0, 0.0],
"C(b, one_hot_encoding_greater_2)[b3]": [0.0, 0.0, 1.0, 1.0],
}
expected = pd.DataFrame(data=expected)
self.assertEqual(res, expected)
res = dmatrix("C(c, one_hot_encoding_greater_2)", df, return_type="dataframe")
expected = {
"Intercept": [1.0, 1.0, 1.0, 1.0],
"C(c, one_hot_encoding_greater_2)[c1]": [1.0, 1.0, 1.0, 1.0],
}
expected = pd.DataFrame(data=expected)
self.assertEqual(res, expected)
def test_truncate_text(self):
self.assertEqual(
balance_util._truncate_text("a" * 6, length=5), "a" * 5 + "..."
)
self.assertEqual(balance_util._truncate_text("a" * 4, length=5), "a" * 4)
self.assertEqual(balance_util._truncate_text("a" * 5, length=5), "a" * 5)
def test__dict_intersect(self):
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "b": 2222}
self.assertEqual(balance_util._dict_intersect(d1, d2), {"b": 2})
def test__astype_in_df_from_dtypes(self):
df = pd.DataFrame({"id": ("1", "2"), "a": (1.0, 2.0), "weight": (1.0, 2.0)})
df_orig = pd.DataFrame(
{"id": (1, 2), "a": (1, 2), "forest": ("tree", "banana")}
)
self.assertEqual(
df.dtypes.to_dict(),
{"id": dtype("O"), "a": dtype("float64"), "weight": dtype("float64")},
)
self.assertEqual(
df_orig.dtypes.to_dict(),
{"id": dtype("int64"), "a": dtype("int64"), "forest": dtype("O")},
)
df_fixed = balance_util._astype_in_df_from_dtypes(df, df_orig.dtypes)
self.assertEqual(
df_fixed.dtypes.to_dict(),
{"id": dtype("int64"), "a": dtype("int64"), "weight": dtype("float64")},
)
def test__true_false_str_to_bool(self):
self.assertFalse(balance_util._true_false_str_to_bool("falsE"))
self.assertTrue(balance_util._true_false_str_to_bool("TrUe"))
with self.assertRaisesRegex(
ValueError,
"Banana is not an accepted value, please pass either 'True' or 'False'*",
):
balance_util._true_false_str_to_bool("Banana")
def test__are_dtypes_equal(self):
df1 = pd.DataFrame({"int": np.arange(5), "flt": np.random.randn(5)})
df2 = pd.DataFrame({"flt": np.random.randn(5), "int": np.random.randn(5)})
df11 = pd.DataFrame(
{"int": np.arange(5), "flt": np.random.randn(5), "miao": np.random.randn(5)}
)
self.assertTrue(
balance_util._are_dtypes_equal(df1.dtypes, df1.dtypes)["is_equal"]
)
self.assertFalse(
balance_util._are_dtypes_equal(df1.dtypes, df2.dtypes)["is_equal"]
)
self.assertFalse(
balance_util._are_dtypes_equal(df11.dtypes, df2.dtypes)["is_equal"]
)
def test__warn_of_df_dtypes_change(self):
df = pd.DataFrame({"int": np.arange(5), "flt": np.random.randn(5)})
new_df = deepcopy(df)
new_df.int = new_df.int.astype(float)
new_df.flt = new_df.flt.astype(int)
self.assertWarnsRegexp(
"The dtypes of new_df were changed from the original dtypes of the input df, here are the differences - ",
balance_util._warn_of_df_dtypes_change,
df.dtypes,
new_df.dtypes,
)
def test__make_df_column_names_unique(self):
# Sample DataFrame with duplicate column names
data = {
"A": [1, 2, 3],
"B": [4, 5, 6],
"A2": [7, 8, 9],
"C": [10, 11, 12],
}
df1 = pd.DataFrame(data)
df1.columns = ["A", "B", "A", "A"]
# TODO: understand in the future why the names here appear to be consistent while when using the function in
# `model_matrix` it does not appear to work.
self.assertEqual(
balance_util._make_df_column_names_unique(df1).to_dict(),
{
"A": {0: 1, 1: 2, 2: 3},
"B": {0: 4, 1: 5, 2: 6},
"A_1": {0: 7, 1: 8, 2: 9},
"A_2": {0: 10, 1: 11, 2: 12},
},
)
| balance-main | tests/test_util.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import logging
import sys
import balance.testutil
import numpy as np
import pandas as pd
class TestTestUtil(
balance.testutil.BalanceTestCase,
):
def test_testutil(self):
# _assert_frame_equal_lazy
self.assertRaises(
AssertionError,
balance.testutil._assert_frame_equal_lazy,
pd.DataFrame({"a": (1, 2, 3)}),
pd.DataFrame({"a": (1, 2, 4)}),
)
self.assertRaises(
AssertionError,
balance.testutil._assert_frame_equal_lazy,
pd.DataFrame({"a": (1, 2, 3), "b": (1, 2, 3)}),
pd.DataFrame({"a": (1, 2, 4), "c": (1, 2, 3)}),
)
a = pd.DataFrame({"a": (1, 2, 3), "b": (4, 5, 6)})
b = pd.DataFrame({"a": (1, 2, 3), "b": (4, 5, 6)}, columns=("b", "a"))
# Doesn't raise an error
balance.testutil._assert_frame_equal_lazy(a, b)
self.assertRaises(
AssertionError, balance.testutil._assert_frame_equal_lazy, a, b, False
)
# _assert_index_equal_lazy
self.assertRaises(
AssertionError,
balance.testutil._assert_index_equal_lazy,
pd.Index([1, 2, 3]),
pd.Index([1, 2, 4]),
)
a = pd.Index([1, 2, 3])
b = pd.Index([1, 3, 2])
# Doesn't raise an error
balance.testutil._assert_index_equal_lazy(a, b)
self.assertRaises(
AssertionError, balance.testutil._assert_index_equal_lazy, a, b, False
)
class TestTestUtil_BalanceTestCase_Equal(
balance.testutil.BalanceTestCase,
):
def test_additional_equality_tests_mixin(self):
# np.array
self.assertRaises(AssertionError, self.assertEqual, 1, 2)
self.assertRaises(
AssertionError, self.assertEqual, np.array((1, 2)), np.array((2, 1))
)
# Does not raise
self.assertEqual(1, 1)
self.assertEqual(np.array((1, 2)), np.array((1, 2)))
# pd.DataFrames
# The default is for non-lazy testing of pandas DataFrames
a = pd.DataFrame({"a": (1, 2, 3), "b": (4, 5, 6)})
b = pd.DataFrame({"a": (1, 2, 3), "b": (4, 5, 6)}, columns=("b", "a"))
# Does raise an error by default or if lazy=False
self.assertRaises(AssertionError, self.assertEqual, a, b)
self.assertRaises(AssertionError, self.assertEqual, a, b, lazy=False)
# Doesn't raise an error
self.assertEqual(a, b, lazy=True)
# pd.Series
self.assertEqual(pd.Series([1, 2]), pd.Series([1, 2]))
self.assertRaises(
AssertionError, self.assertEqual, pd.Series([1, 2]), pd.Series([2, 1])
)
# Indices
self.assertEqual(pd.Index((1, 2)), pd.Index((1, 2)))
self.assertRaises(
AssertionError, self.assertEqual, pd.Index((1, 2)), pd.Index((2, 1))
)
self.assertRaises(
AssertionError,
self.assertEqual,
pd.Index((1, 2)),
pd.Index((2, 1)),
lazy=False,
)
self.assertEqual(pd.Index((1, 2)), pd.Index((2, 1)), lazy=True)
# Other types
self.assertEqual("a", "a")
self.assertRaises(AssertionError, self.assertEqual, "a", "b")
class TestTestUtil_BalanceTestCase_Warns(
balance.testutil.BalanceTestCase,
):
def test_unit_test_warning_mixin(self):
logger = logging.getLogger(__package__)
self.assertIfWarns(lambda: logger.warning("test"))
self.assertNotWarns(lambda: "x")
self.assertWarnsRegexp("abc", lambda: logger.warning("abcde"))
self.assertRaises(
AssertionError,
self.assertWarnsRegexp,
"abcdef",
lambda: logger.warning("abcde"),
)
self.assertNotWarnsRegexp("abcdef", lambda: logger.warning("abcde"))
class TestTestUtil_BalanceTestCase_Print(
balance.testutil.BalanceTestCase,
):
def test_unit_test_print_mixin(self):
self.assertPrints(lambda: print("x"))
self.assertNotPrints(lambda: "x")
self.assertPrintsRegexp("abc", lambda: print("abcde"))
self.assertRaises(
AssertionError, self.assertPrintsRegexp, "abcdef", lambda: print("abcde")
)
# assertPrintsRegexp() doesn't necessarily work with logging.warning(),
# as logging handlers can change (e.g. in PyTest)
self.assertPrintsRegexp("abc", lambda: print("abcde", file=sys.stderr))
| balance-main | tests/test_testutil.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
from unittest.mock import patch
import balance.testutil
import glmnet_python # noqa # Required so that cvglmnet import works
import numpy as np
import pandas as pd
from balance.sample_class import Sample
from balance.weighting_methods import ipw as balance_ipw
from cvglmnet import cvglmnet # pyre-ignore[21]: this module exists
from cvglmnetCoef import cvglmnetCoef # pyre-ignore[21]: this module exists
class Testipw(
balance.testutil.BalanceTestCase,
):
def test_ipw_weights_order(self):
sample = pd.DataFrame({"a": (1, 2, 3, 4, 5, 6, 7, 9, 1)})
target = pd.DataFrame({"a": (1, 2, 3, 4, 5, 6, 7, 9, 9)})
result = balance_ipw.ipw(
sample_df=sample,
sample_weights=pd.Series((1,) * 9),
target_df=target,
target_weights=pd.Series((1,) * 9),
transformations=None,
max_de=1.5,
)
w = result["weight"].values
self.assertEqual(w[0], w[8])
self.assertTrue(w[0] < w[1])
self.assertTrue(w[0] < w[7])
def test_ipw_sample_indicator(self):
# TODO: verify this behavior of balance is sensible
# error message
# TODO: is this test working?
s = pd.DataFrame({"a": np.random.uniform(0, 1, 1000), "id": range(0, 1000)})
t = pd.DataFrame({"a": np.random.uniform(0.5, 1.5, 1000), "id": range(0, 1000)})
s_w = pd.Series(np.array((1,) * 1000))
t_w = pd.Series(np.array((1,) * 1000))
self.assertRaises(
Exception, "same number of rows", balance_ipw.ipw, s, s_w, t, t_w
)
t = pd.DataFrame({"a": np.random.uniform(0.5, 1.5, 999), "id": range(0, 999)})
# Doesn't raise an error
balance_ipw.ipw(
sample_df=s,
sample_weights=s_w,
target_df=t,
target_weights=pd.Series(np.array((1,) * 999)),
)
def test_ipw_bad_adjustment_warnings(self):
# Test the check for identical weights
# Test the check for no large coefficients
# Test the check for model accuracy
n = 100
sample = Sample.from_frame(
df=pd.DataFrame(
{"a": np.random.normal(0, 1, n).reshape((n,)), "id": range(0, n)}
),
id_column="id",
)
sample = sample.set_target(sample)
self.assertWarnsRegexp(
"All weights are identical. The estimates will not be adjusted",
sample.adjust,
method="ipw",
balance_classes=False,
)
self.assertWarnsRegexp(
(
"All propensity model coefficients are zero, your covariates do "
"not predict inclusion in the sample. The estimates will not be "
"adjusted"
),
sample.adjust,
method="ipw",
balance_classes=False,
)
self.assertWarnsRegexp(
(
"The propensity model has low fraction null deviance explained "
".*. Results may not be accurate"
),
sample.adjust,
method="ipw",
balance_classes=False,
)
def test_ipw_na_drop(self):
s = Sample.from_frame(
pd.DataFrame(
{
"a": np.concatenate(
(np.array([np.nan, np.nan]), np.arange(3, 100))
),
"id": np.arange(1, 100),
}
),
id_column="id",
)
t = Sample.from_frame(
pd.DataFrame(
{
"a": np.concatenate((np.array([np.nan]), np.arange(2, 100))),
"id": np.arange(1, 100),
}
),
id_column="id",
)
self.assertWarnsRegexp(
"Dropped 2/99 rows of sample",
s.adjust,
t,
na_action="drop",
transformations=None,
)
def test_cv_glmnet_performance(self):
x = np.random.rand(100, 10)
y = np.random.rand(100, 1)
y = (y > 0.5) * 1.0
with balance_ipw._patch_scipy_random():
fit = cvglmnet(x=x, y=y, family="binomial", ptype="class")
# Test default args with feature names
c = cvglmnetCoef(fit)
e_c_names = pd.Series(
index="intercept a b c d e f g h i j".split(), data=c.reshape((c.shape[0],))
)
e_c = pd.Series(data=c.reshape((c.shape[0],)))
r = balance_ipw.cv_glmnet_performance(
fit, feature_names="a b c d e f g h i j".split()
)
ix = fit["lambdau"] == fit["lambda_1se"]
e_dev = fit["glmnet_fit"]["dev"][ix]
e_cve = fit["cvm"][ix]
self.assertEqual(r["coefs"], e_c_names)
self.assertEqual(r["prop_dev_explained"], e_dev)
self.assertEqual(r["mean_cv_error"], e_cve)
self.assertEqual(len(fit["glmnet_fit"]["dev"].shape), 1)
self.assertEqual(len(fit["cvm"].shape), 1)
# Test default args with lambda_min
c = cvglmnetCoef(fit, s="lambda_min")
e_c_names = pd.Series(
index="intercept a b c d e f g h i j".split(), data=c.reshape((c.shape[0],))
)
e_c = pd.Series(data=c.reshape((c.shape[0],)))
r = balance_ipw.cv_glmnet_performance(fit, s="lambda_min")
ix = fit["lambdau"] == fit["lambda_min"]
e_dev = fit["glmnet_fit"]["dev"][ix]
e_cve = fit["cvm"][ix]
self.assertEqual(r["coefs"], e_c)
self.assertEqual(r["prop_dev_explained"], e_dev)
self.assertEqual(r["mean_cv_error"], e_cve)
# Test with specific lambda
s = np.array([fit["lambdau"][5]])
c = cvglmnetCoef(fit, s=s)
e_c_names = pd.Series(
index="intercept a b c d e f g h i j".split(), data=c.reshape((c.shape[0],))
)
e_c = pd.Series(data=c.reshape((c.shape[0],)))
r = balance_ipw.cv_glmnet_performance(fit, s=s)
ix = fit["lambdau"] == s
e_dev = fit["glmnet_fit"]["dev"][ix]
e_cve = fit["cvm"][ix]
self.assertEqual(r["coefs"], e_c)
self.assertEqual(r["prop_dev_explained"], e_dev)
self.assertEqual(r["mean_cv_error"], e_cve)
# Test exception
balance_ipw.cv_glmnet_performance(fit, s=s)
self.assertRaisesRegex(
Exception,
"No lambda found for",
balance_ipw.cv_glmnet_performance,
fit,
s=7,
)
def test_weights_from_link(self):
link = np.array((1, 2, 3)).reshape(3, 1)
target_weights = (1, 2)
r = balance_ipw.weights_from_link(link, False, (1, 1, 1), target_weights)
e = np.array((1 / np.exp(1), 1 / np.exp(2), 1 / np.exp(3)))
e = e * np.sum(target_weights) / np.sum(e)
self.assertEqual(r, e)
self.assertEqual(r.shape, (3,))
# balance_classes does nothing if classes have same sum weights
r = balance_ipw.weights_from_link(link, True, (1, 1, 1), (1, 2))
self.assertEqual(r, e)
# balance_classes uses link+log(odda)
target_weights = (1, 2, 3)
r = balance_ipw.weights_from_link(
link, True, (1, 1, 1), target_weights, keep_sum_of_weights=False
)
e = np.array(
(
1 / np.exp(1 + np.log(1 / 2)),
1 / np.exp(2 + np.log(1 / 2)),
1 / np.exp(3 + np.log(1 / 2)),
)
)
e = e * np.sum(target_weights) / np.sum(e)
self.assertEqual(r, e)
# sample_weights doubles
target_weights = (1, 2)
r = balance_ipw.weights_from_link(link, False, (2, 2, 2), target_weights)
e = np.array((2 / np.exp(1), 2 / np.exp(2), 2 / np.exp(3)))
e = e * np.sum(target_weights) / np.sum(e)
self.assertEqual(r, e)
# trimming works
r = balance_ipw.weights_from_link(
np.random.uniform(0, 1, 10000),
False,
(1,) * 10000,
(1),
weight_trimming_percentile=(0, 0.11),
keep_sum_of_weights=False, # this parameter is passed to trim_weights
)
self.assertTrue(r.max() < 0.9)
def test_ipw_input_assertions(self):
s_w = np.array((1))
self.assertRaisesRegex(
TypeError,
"must be a pandas DataFrame",
balance_ipw.ipw,
s_w,
s_w,
s_w,
s_w,
)
s = pd.DataFrame({"a": (1, 2), "id": (1, 2)})
s_w = pd.Series((1,))
self.assertRaisesRegex(
Exception,
"must be the same length",
balance_ipw.ipw,
s,
s_w,
s,
s_w,
)
def test_ipw_dropna_empty(self):
s = pd.DataFrame({"a": (1, None), "b": (np.nan, 2), "id": (1, 2)})
s_w = pd.Series((1, 2))
self.assertRaisesRegex(
Exception,
"Dropping rows led to empty",
balance_ipw.ipw,
s,
s_w,
s,
s_w,
na_action="drop",
)
def test_ipw_formula(self):
sample = pd.DataFrame(
{
"a": (1, 2, 3, 4, 5, 6, 7, 9, 1),
"b": (1, 2, 3, 4, 5, 6, 7, 9, 1),
"c": (1, 2, 3, 4, 5, 6, 7, 9, 1),
}
)
target = pd.DataFrame(
{
"a": (1, 2, 3, 4, 5, 6, 7, 9, 9),
"b": (1, 2, 3, 4, 5, 6, 7, 9, 1),
"c": (1, 2, 3, 4, 5, 6, 7, 9, 1),
}
)
result = balance_ipw.ipw(
sample_df=sample,
sample_weights=pd.Series((1,) * 9),
target_df=target,
target_weights=pd.Series((1,) * 9),
formula="a : b + c",
transformations=None,
)
self.assertEqual(result["model"]["X_matrix_columns"], ["a:b", "c"])
def test_ipw_consistency_with_default_arguments(self):
# This test is meant to check the consistency of the ipw function with the default arguments,
# Note that this test rely on all balance functions that are part of ipw:
# choose_variables, apply_transformations, model_matrix, choose_regularization,
# weights_from_link, cv_glmnet_performance
# Therefore a failure in this test may indicate a failure in one
# of these functions as well as a failure of the ipw function
np.random.seed(2021)
n_sample = 1000
n_target = 2000
sample_df = pd.concat(
[
pd.DataFrame(np.random.uniform(0, 10, size=n_sample), columns=[0]),
pd.DataFrame(
np.random.uniform(0, 1, size=(n_sample, 4)), columns=range(1, 5)
),
pd.DataFrame(
np.random.choice(
["level1", "level2", "level3"], size=(n_sample, 5)
),
columns=range(5, 10),
),
],
axis=1,
)
sample_df = sample_df.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
target_df = pd.concat(
[
pd.DataFrame(np.random.uniform(8, 18, size=n_target), columns=[0]),
pd.DataFrame(
np.random.uniform(0, 1, size=(n_target, 4)), columns=range(1, 5)
),
pd.DataFrame(
np.random.choice(
["level1", "level2", "level3"], size=(n_target, 5)
),
columns=range(5, 10),
),
],
axis=1,
)
target_df = target_df.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
sample_weights = pd.Series(np.random.uniform(0, 1, size=n_sample))
target_weights = pd.Series(np.random.uniform(0, 1, size=n_target))
res = balance_ipw.ipw(
sample_df, sample_weights, target_df, target_weights, max_de=1.5
)
# Compare output weights (examples and distribution)
self.assertEqual(round(res["weight"][15], 4), 0.0886)
self.assertEqual(round(res["weight"][995], 4), 0.2363)
self.assertEqual(
np.around(res["weight"].describe().values, 4),
np.array([1000, 1.0167, 0.7108, 0.0001, 0.2349, 1.2151, 1.7077, 1.7077]),
)
# Compare properties of output model
self.assertEqual(np.around(res["model"]["fit"]["lambda_1se"], 5), 0.00474)
self.assertEqual(
np.around(res["model"]["perf"]["prop_dev_explained"], 5), 0.77107
)
self.assertEqual(np.around(res["model"]["perf"]["mean_cv_error"], 5), 0.36291)
self.assertEqual(np.around(res["model"]["lambda"], 5), 0.00064)
self.assertEqual(res["model"]["regularisation_perf"]["best"]["trim"], 0.05)
@patch("balance.weighting_methods.ipw.scipy")
def test_patch_scipy_random(self, mock_scipy):
mock_scipy.random = None
with balance_ipw._patch_scipy_random():
self.assertEqual(mock_scipy.random, np.random)
self.assertEqual(mock_scipy.random, None)
| balance-main | tests/test_ipw.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import balance.testutil
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas.testing
from balance.sample_class import Sample
from balance.stats_and_plots import weighted_comparisons_plots, weighted_stats
s = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (-42, 8, 2),
"c": ("x", "y", "z"),
"id": (1, 2, 3),
"w": (0.5, 2, 1),
}
),
id_column="id",
weight_column="w",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (17, 9, -3),
"c": ("x", "y", "z"),
"id": (1, 2, 3),
"w": (0.5, 2, 1),
}
),
id_column="id",
weight_column="w",
)
# TODO: split out the weighted_stats.relative_frequency_table function.
class Test_weighted_comparisons_plots(
balance.testutil.BalanceTestCase,
):
def test_plot__return_sample_palette(self):
from balance.stats_and_plots.weighted_comparisons_plots import (
_return_sample_palette,
)
self.assertEqual(
_return_sample_palette(["self", "target"]),
{"self": "#de2d26cc", "target": "#9ecae1cc"},
)
self.assertEqual(
_return_sample_palette(["self", "unadjusted"]),
{"self": "#34a53080", "unadjusted": "#de2d26cc"},
)
self.assertEqual(
_return_sample_palette(["self", "unadjusted", "target"]),
{"self": "#34a53080", "unadjusted": "#de2d26cc", "target": "#9ecae1cc"},
)
self.assertEqual(
_return_sample_palette(["adjusted", "unadjusted", "target"]),
{"adjusted": "#34a53080", "unadjusted": "#de2d26cc", "target": "#9ecae1cc"},
)
self.assertEqual(_return_sample_palette(["cat", "dog"]), "muted")
def test_plot__plotly_marker_color(self):
from balance.stats_and_plots.weighted_comparisons_plots import (
_plotly_marker_color,
)
self.assertEqual(
_plotly_marker_color("self", True, "color"), "rgba(222,45,38,0.8)"
)
self.assertEqual(
_plotly_marker_color("self", False, "color"), "rgba(52,165,48,0.5)"
)
self.assertEqual(
_plotly_marker_color("self", True, "line"), "rgba(222,45,38,1)"
)
self.assertEqual(
_plotly_marker_color("self", False, "line"), "rgba(52,165,48,1)"
)
self.assertEqual(
_plotly_marker_color("target", True, "color"), "rgb(158,202,225,0.8)"
)
self.assertEqual(
_plotly_marker_color("target", False, "color"), "rgb(158,202,225,0.8)"
)
self.assertEqual(
_plotly_marker_color("target", True, "line"), "rgb(158,202,225,1)"
)
self.assertEqual(
_plotly_marker_color("target", False, "line"), "rgb(158,202,225,1)"
)
self.assertEqual(
_plotly_marker_color("adjusted", False, "color"), "rgba(52,165,48,0.5)"
)
self.assertEqual(
_plotly_marker_color("adjusted", False, "line"), "rgba(52,165,48,1)"
)
def test_plot_bar(self):
import matplotlib.pyplot as plt
from balance.stats_and_plots.weighted_comparisons_plots import plot_bar
df = pd.DataFrame(
{
"group": ("a", "b", "c", "c"),
"v1": (1, 2, 3, 4),
}
)
plt.figure(1)
fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
plot_bar(
[
{"df": df, "weight": pd.Series((1, 1, 1, 1))},
{"df": df, "weight": pd.Series((2, 1, 1, 1))},
],
names=["self", "target"],
column="group",
axis=ax,
weighted=True,
)
self.assertIn("barplot of covar ", ax.get_title())
def test_plot_dist_weighted_kde_error(self):
df4 = {
"df": pd.DataFrame(
{"numeric_5": pd.Series([0, 0, 0, 0, 0, 1, 1, 2, 3, 4])}
),
"weight": pd.Series([0, 0, 0, 0, 0, 0, 0, 0, 0, 5]),
}
plot_dist_type = type(
weighted_comparisons_plots.plot_dist(
(df4,),
dist_type="kde",
numeric_n_values_threshold=0,
weighted=False,
library="seaborn",
return_axes=True,
)[0]
)
# NOTE: There is no AxesSubplot class until one is invoked and created on the fly.
# See details here: https://stackoverflow.com/a/11690800/256662
self.assertTrue(issubclass(plot_dist_type, plt.Axes))
def test_relative_frequency_table(self):
df = pd.DataFrame({"a": list("abcd"), "b": list("bbcd")})
e = pd.DataFrame({"a": list("abcd"), "prop": (0.25,) * 4})
self.assertEqual(weighted_stats.relative_frequency_table(df, "a"), e)
t = weighted_stats.relative_frequency_table(df, "a", pd.Series((1, 1, 1, 1)))
self.assertEqual(t, e)
e = pd.DataFrame({"b": list("bcd"), "prop": (0.5, 0.25, 0.25)})
t = weighted_stats.relative_frequency_table(df, "b")
self.assertEqual(t, e)
t = weighted_stats.relative_frequency_table(df, "b", pd.Series((1, 1, 1, 1)))
self.assertEqual(t, e)
with self.assertRaisesRegex(TypeError, "must be a pandas Series"):
weighted_stats.relative_frequency_table(df, "a", 1)
e = pd.DataFrame({"a": list("abcd"), "prop": (0.2, 0.4, 0.2, 0.2)})
t = weighted_stats.relative_frequency_table(df, "a", pd.Series((1, 2, 1, 1)))
self.assertEqual(t, e)
e = pd.DataFrame({"b": list("bcd"), "prop": (1 / 3, 1 / 3, 1 / 3)})
t = weighted_stats.relative_frequency_table(
df, "b", pd.Series((0.5, 0.5, 1, 1))
)
self.assertEqual(t, e)
df = pd.DataFrame(
{
"group": ("a", "b", "c", "c"),
"v1": (1, 2, 3, 4),
}
)
t = weighted_stats.relative_frequency_table(
df,
"group",
pd.Series((2, 1, 1, 1)),
).to_dict()
e = {"group": {0: "a", 1: "b", 2: "c"}, "prop": {0: 0.4, 1: 0.2, 2: 0.4}}
self.assertEqual(t, e)
# check that using a pd.Series will give the same results
t_series = weighted_stats.relative_frequency_table(
df=df["group"],
w=pd.Series((2, 1, 1, 1)),
).to_dict()
self.assertEqual(t_series, e)
def test_naming_plot(self):
self.assertEqual(
weighted_comparisons_plots.naming_legend(
"self", ["self", "target", "unadjusted"]
),
"adjusted",
)
self.assertEqual(
weighted_comparisons_plots.naming_legend(
"unadjusted", ["self", "target", "unadjusted"]
),
"sample",
)
self.assertEqual(
weighted_comparisons_plots.naming_legend("self", ["self", "target"]),
"sample",
)
self.assertEqual(
weighted_comparisons_plots.naming_legend("other_name", ["self", "target"]),
"other_name",
)
def test_seaborn_plot_dist(self):
df4 = {
"df": pd.DataFrame(
{"numeric_5": pd.Series([0, 0, 0, 0, 0, 1, 1, 2, 3, 4])}
),
"weight": pd.Series([0, 0, 0, 0, 0, 0, 0, 0, 0, 5]),
}
# Check that we get a list of matplotlib axes
out = []
for dist_type in ("hist", "kde", "qq", "ecdf"):
out.append(
type(
weighted_comparisons_plots.seaborn_plot_dist(
(df4,),
names=["test"],
dist_type=dist_type,
return_axes=True,
)[0]
)
)
# NOTE: There is no AxesSubplot class until one is invoked and created on the fly.
# See details here: https://stackoverflow.com/a/11690800/256662
self.assertTrue(issubclass(out[0], matplotlib.axes.Axes))
self.assertTrue(issubclass(out[1], matplotlib.axes.Axes))
self.assertTrue(issubclass(out[2], matplotlib.axes.Axes))
self.assertTrue(issubclass(out[3], matplotlib.axes.Axes))
def test_plot_dist(self):
import plotly.graph_objs as go
from balance.stats_and_plots.weighted_comparisons_plots import plot_dist
from numpy import random
random.seed(96483)
df = pd.DataFrame(
{
"v1": random.random_integers(11111, 11114, size=100).astype(str),
"v2": random.normal(size=100),
"v3": random.uniform(size=100),
}
).sort_values(by=["v2"])
dfs1 = [
{"df": df, "weight": pd.Series(np.ones(100))},
{"df": df, "weight": pd.Series(np.ones(99).tolist() + [1000])},
{"df": df, "weight": pd.Series(np.ones(100))},
]
# If plot_it=False and
self.assertTrue(
plot_dist(
dfs1,
names=["self", "unadjusted", "target"],
library="plotly",
plot_it=False,
)
is None
)
# check the dict of figures returned:
dict_of_figures = plot_dist(
dfs1,
names=["self", "unadjusted", "target"],
library="plotly",
plot_it=False,
return_dict_of_figures=True,
)
self.assertEqual(type(dict_of_figures), dict)
self.assertEqual(sorted(dict_of_figures.keys()), ["v1", "v2", "v3"])
self.assertEqual(type(dict_of_figures["v1"]), go.Figure)
with self.assertRaisesRegex(ValueError, "library must be either*"):
plot_dist(
dfs1,
names=["self", "unadjusted", "target"],
library="ploting_library_which_is_not_plotly_or_seaborn",
)
| balance-main | tests/test_weighted_comparisons_plots.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import balance.testutil
import numpy as np
import pandas as pd
from balance.sample_class import Sample
from balance.weighting_methods.rake import (
_proportional_array_from_dict,
_realize_dicts_of_proportions,
prepare_marginal_dist_for_raking,
rake,
)
class Testrake(
balance.testutil.BalanceTestCase,
):
def test_rake_input_assertions(self):
N = 20
sample = pd.DataFrame(
{
"a": np.random.normal(size=N),
"b": np.random.normal(size=N),
"weight": [1.0] * N,
}
)
target = pd.DataFrame(
{
"a": np.random.normal(size=N),
"b": np.random.normal(size=N),
}
)
# Cannot have weight in df that is not the weight column
self.assertRaisesRegex(
AssertionError,
"weight shouldn't be a name for covariate in the sample data",
rake,
sample,
pd.Series((1,) * N),
target,
pd.Series((1,) * N),
)
target["weight"] = [2.0] * N
self.assertRaisesRegex(
AssertionError,
"weight shouldn't be a name for covariate in the target data",
rake,
sample[["a", "b"]],
pd.Series((1,) * N),
target,
pd.Series((1,) * N),
)
# Must pass more than one varaible
self.assertRaisesRegex(
AssertionError,
"Must weight on at least two variables",
rake,
sample[["a"]],
pd.Series((1,) * N),
target[["a"]],
pd.Series((1,) * N),
)
# Must pass weights for sample
self.assertRaisesRegex(
AssertionError,
"sample_weights must be a pandas Series",
rake,
sample[["a", "b"]],
None,
target[["a", "b"]],
pd.Series((1,) * N),
)
# Must pass weights for sample
self.assertRaisesRegex(
AssertionError,
"target_weights must be a pandas Series",
rake,
sample[["a", "b"]],
pd.Series((1,) * N),
target[["a", "b"]],
None,
)
# Must pass weights of same length as sample
self.assertRaisesRegex(
AssertionError,
"sample_weights must be the same length as sample_df",
rake,
sample[["a", "b"]],
pd.Series((1,) * (N - 1)),
target[["a", "b"]],
pd.Series((1,) * N),
)
# Must pass weights for sample
self.assertRaisesRegex(
AssertionError,
"target_weights must be the same length as target_df",
rake,
sample[["a", "b"]],
pd.Series((1,) * N),
target[["a", "b"]],
pd.Series((1,) * (N - 1)),
)
def test_rake_fails_when_all_na(self):
df_sample_nas = pd.DataFrame(
{
"a": np.array([np.nan] * 12),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_target = pd.DataFrame(
{
"a": np.array(["1"] * 10 + ["2"] * 2),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_sample = pd.DataFrame(
{
"a": np.array(["1", "2"] * 6),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_target_nas = pd.DataFrame(
{
"a": pd.Series([np.nan] * 6 + ["2"] * 6, dtype=object),
"b": pd.Series(["a"] * 6 + [np.nan] * 6, dtype=object),
"id": range(0, 12),
}
)
self.assertRaisesRegex(
ValueError,
"Dropping rows led to empty",
rake,
df_sample_nas,
pd.Series((1,) * 12),
df_target,
pd.Series((1,) * 12),
na_action="drop",
transformations=None,
)
self.assertRaisesRegex(
ValueError,
"Dropping rows led to empty",
rake,
df_sample,
pd.Series((1,) * 12),
df_target_nas,
pd.Series((1,) * 12),
na_action="drop",
transformations=None,
)
def test_rake_weights(self):
df_sample = pd.DataFrame(
{
"a": np.array(["1", "2"] * 6),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_target = pd.DataFrame(
{
"a": np.array(["1"] * 10 + ["2"] * 2),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
sample = Sample.from_frame(df_sample)
target = Sample.from_frame(df_target)
sample = sample.set_target(target)
adjusted = rake(
sample.covars().df,
sample.weight_column,
target.covars().df,
target.weight_column,
)
self.assertEqual(
adjusted["weight"].round(2),
pd.Series([1.67, 0.33] * 6, name="rake_weight").rename_axis("index"),
)
def test_rake_weights_with_weighted_input(self):
df_sample = pd.DataFrame(
{
"a": np.array(["1", "2"] * 6),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_target = pd.DataFrame(
{
"a": np.array(["1"] * 10 + ["2"] * 2),
"b": ["a"] * 6 + ["b"] * 6,
"weight": [0.5, 1.0] * 6,
"id": range(0, 12),
}
)
sample = Sample.from_frame(df_sample)
target = Sample.from_frame(df_target)
sample = sample.set_target(target)
adjusted = rake(
sample.covars().df,
sample.weight_column,
target.covars().df,
target.weight_column,
)
self.assertEqual(
adjusted["weight"].round(2),
pd.Series([1.25, 0.25] * 6, name="rake_weight").rename_axis("index"),
)
def test_rake_weights_scale_to_pop(self):
df_sample = pd.DataFrame(
{
"a": np.array(["1", "2"] * 6),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_target = pd.DataFrame(
{
"a": np.array(["1"] * 10 + ["2"] * 5),
"b": ["a"] * 6 + ["b"] * 9,
"id": range(0, 15),
}
)
sample = Sample.from_frame(df_sample)
target = Sample.from_frame(df_target)
sample = sample.set_target(target)
adjusted = rake(
sample.covars().df,
sample.weight_column,
target.covars().df,
target.weight_column,
)
self.assertEqual(round(sum(adjusted["weight"]), 2), 15.0)
def test_rake_expected_weights_with_na(self):
dfsamp = pd.DataFrame(
{
"a": np.array([1.0, 2.0, np.nan] * 6),
"b": ["a", "b"] * 9,
"id": range(0, 18),
}
)
dfpop = pd.DataFrame(
{
"a": np.array([1.0] * 10 + [2.0] * 6 + [np.nan] * 2),
"b": ["a", "b"] * 9,
"id": range(18, 36),
}
)
sample = Sample.from_frame(dfsamp)
target = Sample.from_frame(dfpop)
sample = sample.set_target(target)
# Dropping NAs (example calculation for test values):
# Note, 'b' does not matter here, always balanced
# In sample, a=1.0 is 6/12=0.5
# In target, a=1.0 is 10/16=0.625
# So a=1.0 in sample needs 1.25 weight (when weights sum to sample size)
# Now that weights sum to target size, we need to scale 1.25 by relative population sizes
# 1.25 * (16/12) = 1.6666667, final weight
adjusted = sample.adjust(method="rake", transformations=None, na_action="drop")
self.assertEqual(
adjusted.weight_column.round(2),
pd.Series([1.67, 1.0, np.nan] * 6, name="weight"),
)
# Dropping NAs (example calculation for test values):
# Note, 'b' does not matter here, always balanced
# In sample, a=1.0 is 6/18=0.333333
# In target, a=1.0 is 10/18=0.5555556
# So a=1.0 in sample needs 1.6667 weight (when weights sum to sample size)
# sample size = target size, so no need to rescale
adjusted = sample.adjust(
method="rake", transformations=None, na_action="add_indicator"
)
self.assertEqual(
adjusted.weight_column.round(2),
pd.Series([1.67, 1.0, 0.33] * 6, name="weight"),
)
# Test consistency result of rake
def test_rake_consistency_with_default_arguments(self):
# This test is meant to check the consistency of the rake function with the default arguments
np.random.seed(2021)
n_sample = 1000
n_target = 2000
sample_df = pd.concat(
[
pd.DataFrame(np.random.uniform(0, 10, size=n_sample), columns=[0]),
pd.DataFrame(
np.random.uniform(0, 1, size=(n_sample, 4)), columns=range(1, 5)
),
pd.DataFrame(
np.random.choice(
["level1", "level2", "level3"], size=(n_sample, 5)
),
columns=range(5, 10),
),
],
axis=1,
)
sample_df = sample_df.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
target_df = pd.concat(
[
pd.DataFrame(np.random.uniform(0, 18, size=n_target), columns=[0]),
pd.DataFrame(
np.random.uniform(0, 1, size=(n_target, 4)), columns=range(1, 5)
),
pd.DataFrame(
np.random.choice(
["level1", "level2", "level3"], size=(n_target, 5)
),
columns=range(5, 10),
),
],
axis=1,
)
target_df = target_df.rename(columns={i: "abcdefghij"[i] for i in range(0, 10)})
# Add some NAN values
sample_df.loc[[0, 1], "a"] = np.nan
target_df.loc[[100, 101], "a"] = np.nan
sample_weights = pd.Series(np.random.uniform(0, 1, size=n_sample))
target_weights = pd.Series(np.random.uniform(0, 1, size=n_target))
res = rake(sample_df, sample_weights, target_df, target_weights)
# Compare output weights (examples and distribution)
self.assertEqual(round(res["weight"][4], 4), 1.3221)
self.assertEqual(round(res["weight"][997], 4), 0.8985)
self.assertEqual(
np.around(res["weight"].describe().values, 4),
np.array(
[
1.0000e03,
1.0167e00,
3.5000e-01,
3.4260e-01,
7.4790e-01,
9.7610e-01,
1.2026e00,
2.8854e00,
]
),
)
def test_variable_order_alphabetized(self):
# Note: 'a' is always preferred, and due to perfect collinearity
# with 'b', 'b' never gets weighted to, even if we reverse the
# order. This is not a perfect test, but it broke pre-alphabetization!
df_sample = pd.DataFrame(
{
"a": ["1"] * 6 + ["2"] * 6,
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_target = pd.DataFrame(
{
"a": np.array(["1"] * 10 + ["2"] * 2),
"b": ["a"] * 3 + ["b"] * 9,
"id": range(0, 12),
}
)
sample = Sample.from_frame(df_sample)
target = Sample.from_frame(df_target)
adjusted = rake(
sample.covars().df,
sample.weight_column,
target.covars().df,
target.weight_column,
variables=["a", "b"],
)
adjusted_two = rake(
sample.covars().df,
sample.weight_column,
target.covars().df,
target.weight_column,
variables=["b", "a"],
)
self.assertEqual(
adjusted["weight"],
adjusted_two["weight"],
)
def test_rake_levels_warnings(self):
df_sample = pd.DataFrame(
{
"a": np.array(["1", "2"] * 6),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_target = pd.DataFrame(
{
"a": np.array(["1"] * 10 + ["2"] * 2),
"b": ["a"] * 6 + ["b"] * 6,
"id": range(0, 12),
}
)
df_sample_excess_levels = pd.DataFrame(
{
"a": np.array(["1", "2"] * 6),
"b": ["alpha"] * 2 + ["a"] * 4 + ["b"] * 6,
"id": range(0, 12),
}
)
df_target_excess_levels = pd.DataFrame(
{
"a": np.array(["1"] * 10 + ["2"] * 2),
"b": ["omega"] * 2 + ["a"] * 4 + ["b"] * 6,
"id": range(0, 12),
}
)
sample = Sample.from_frame(df_sample)
sample_excess_levels = Sample.from_frame(df_sample_excess_levels)
target = Sample.from_frame(df_target)
target_excess_levels = Sample.from_frame(df_target_excess_levels)
self.assertRaisesRegex(
ValueError,
"'b' in target is missing.*alpha",
rake,
sample_excess_levels.covars().df,
sample_excess_levels.weight_column,
target.covars().df,
target.weight_column,
)
self.assertWarnsRegexp(
"'b' in sample is missing.*omega",
rake,
sample.covars().df,
sample.weight_column,
target_excess_levels.covars().df,
target_excess_levels.weight_column,
)
def test__proportional_array_from_dict(self):
self.assertEqual(
_proportional_array_from_dict({"a": 0.2, "b": 0.8}),
["a", "b", "b", "b", "b"],
)
self.assertEqual(
_proportional_array_from_dict({"a": 0.5, "b": 0.5}), ["a", "b"]
)
self.assertEqual(
_proportional_array_from_dict({"a": 1 / 3, "b": 1 / 3, "c": 1 / 3}),
["a", "b", "c"],
)
self.assertEqual(
_proportional_array_from_dict({"a": 3 / 8, "b": 5 / 8}),
["a", "a", "a", "b", "b", "b", "b", "b"],
)
self.assertEqual(
_proportional_array_from_dict({"a": 3 / 5, "b": 1 / 5, "c": 2 / 10}),
["a", "a", "a", "b", "c"],
)
self.assertEqual(
_proportional_array_from_dict({"a": 3 / 8, "b": 5 / 8}, max_length=5),
["a", "a", "b", "b", "b"],
)
self.assertEqual(
_proportional_array_from_dict({"a": 3 / 8, "b": 5 / 8}, max_length=50),
["a", "a", "a", "b", "b", "b", "b", "b"],
)
def test__realize_dicts_of_proportions(self):
dict_of_dicts = {
"v1": {"a": 0.2, "b": 0.6, "c": 0.2},
"v2": {"aa": 0.5, "bb": 0.5},
}
self.assertEqual(
_realize_dicts_of_proportions(dict_of_dicts),
{
"v1": ["a", "b", "b", "b", "c", "a", "b", "b", "b", "c"],
"v2": ["aa", "bb", "aa", "bb", "aa", "bb", "aa", "bb", "aa", "bb"],
},
)
dict_of_dicts = {
"v1": {"a": 0.2, "b": 0.6, "c": 0.2},
"v2": {"aa": 0.5, "bb": 0.5},
"v3": {"A": 0.2, "B": 0.8},
}
self.assertEqual(
_realize_dicts_of_proportions(dict_of_dicts),
{
"v1": ["a", "b", "b", "b", "c", "a", "b", "b", "b", "c"],
"v2": ["aa", "bb", "aa", "bb", "aa", "bb", "aa", "bb", "aa", "bb"],
"v3": ["A", "B", "B", "B", "B", "A", "B", "B", "B", "B"],
},
)
dict_of_dicts = {
"v1": {"a": 0.2, "b": 0.6, "c": 0.2},
"v2": {"aa": 0.5, "bb": 0.5},
"v3": {"A": 0.2, "B": 0.8},
"v4": {"A": 0.1, "B": 0.9},
}
self.assertEqual(
_realize_dicts_of_proportions(dict_of_dicts),
{
"v1": ["a", "b", "b", "b", "c", "a", "b", "b", "b", "c"],
"v2": ["aa", "bb", "aa", "bb", "aa", "bb", "aa", "bb", "aa", "bb"],
"v3": ["A", "B", "B", "B", "B", "A", "B", "B", "B", "B"],
"v4": ["A", "B", "B", "B", "B", "B", "B", "B", "B", "B"],
},
)
def test_prepare_marginal_dist_for_raking(self):
self.assertEqual(
prepare_marginal_dist_for_raking(
{"A": {"a": 0.5, "b": 0.5}, "B": {"x": 0.2, "y": 0.8}}
).to_dict(),
{
"A": {
0: "a",
1: "b",
2: "a",
3: "b",
4: "a",
5: "b",
6: "a",
7: "b",
8: "a",
9: "b",
},
"B": {
0: "x",
1: "y",
2: "y",
3: "y",
4: "y",
5: "x",
6: "y",
7: "y",
8: "y",
9: "y",
},
"id": {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9},
},
)
# TODO: test convergence rate
# TODO: test max iteration
# TODO: test logging
| balance-main | tests/test_rake.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os.path
import tempfile
import balance.testutil
import numpy as np
import pandas as pd
from balance.cli import _float_or_none, BalanceCLI, make_parser
from numpy import dtype
# TODO: this should probably be generalized (so the code below could be made cleaner)
def check_some_flags(flag=True, the_flag_str="--skip_standardize_types"):
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as in_file:
in_contents = (
"x,y,is_respondent,id,weight\n"
+ ("1.0,50,1,1,1\n" * 1000)
+ ("2.0,60,0,1,1\n" * 1000)
)
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
parser = make_parser()
args_to_parse = [
"--input_file",
in_file.name,
"--output_file",
out_file,
"--covariate_columns",
"x,y",
]
if flag:
args_to_parse.append(the_flag_str)
args = parser.parse_args(args_to_parse)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
pd_in = pd.read_csv(in_file.name)
pd_out = pd.read_csv(out_file)
return {"pd_in": pd_in, "pd_out": pd_out}
class TestCli(
balance.testutil.BalanceTestCase,
):
def test_cli_help(self):
# Just make sure it doesn't fail
try:
parser = make_parser()
args = parser.parse_args(["--help"])
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
except SystemExit as e:
if e.code == 0:
pass
else:
raise e
def test_cli_float_or_none(self):
self.assertEqual(_float_or_none(None), None)
self.assertEqual(_float_or_none("None"), None)
self.assertEqual(_float_or_none("13.37"), 13.37)
def test_cli_succeed_on_weighting_failure(self):
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as in_file:
in_contents = "x,y,is_respondent,id,weight\n" "a,b,1,1,1\n" "a,b,0,1,1"
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--covariate_columns",
"x,y",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
self.assertRaisesRegex(Exception, "glmnet", cli.main)
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--covariate_columns",
"x,y",
"--succeed_on_weighting_failure",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
self.assertTrue(os.path.isfile(out_file))
def test_cli_works(self):
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as in_file:
in_contents = (
"x,y,is_respondent,id,weight\n"
+ ("a,b,1,1,1\n" * 1000)
+ ("c,b,0,1,1\n" * 1000)
)
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
def test_cli_works_with_row_column_filters(self):
import os
# TODO: remove imports (already imported in the beginning of the file)
import tempfile
import pandas as pd
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as in_file:
# # create temp folder / file
# in_file = tempfile.NamedTemporaryFile(
# "w", suffix=".csv", delete=False
# )
# temp_dir = tempfile.TemporaryDirectory().name
in_contents = (
"x,y,z,is_respondent,id,weight\n"
+ ("a,b,g,1,1,1\n" * 1000)
+ ("c,b,g,1,1,1\n" * 1000)
+ ("c,b,g,0,1,1\n" * 1000)
+ ("a,d,n,1,2,1\n" * 1000)
)
in_file.write(in_contents)
in_file.close()
# pd.read_csv(in_file)
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y,z",
"--rows_to_keep_for_diagnostics",
"z == 'g'", # filtering condition
"--covariate_columns_for_diagnostics",
"x,y", # ignoring z
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
pd_in_file = pd.read_csv(in_file.name)
pd_out_file = pd.read_csv(out_file)
pd_diagnostics_out_file = pd.read_csv(diagnostics_out_file)
# test stuff
# Make sure we indeed got all the output files
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
# the original file had 4000 rows (1k target and 3k sample)
self.assertEqual(pd_in_file.shape, (4000, 6))
# the cli output includes only the panel (NOT the target)
# it also includes all the original columns
self.assertEqual(pd_out_file.shape, (3000, 6))
self.assertEqual(pd_out_file.is_respondent.mean(), 1)
# the diagnostics file shows it was calculated on only 2k panelists (as required from the condition)
ss = pd_diagnostics_out_file.eval(
"(metric == 'size') & (var == 'sample_obs')"
)
self.assertEqual(int(pd_diagnostics_out_file[ss]["val"]), 2000)
# verify we get diagnostics only for x and y, and not z
ss = pd_diagnostics_out_file.eval("metric == 'covar_main_asmd_adjusted'")
output = pd_diagnostics_out_file[ss]["var"].to_list()
expected = ["x", "y", "mean(asmd)"]
self.assertEqual(output, expected)
# # remove temp folder / file
# os.unlink(in_file.name)
# import shutil
# shutil.rmtree(temp_dir)
def test_cli_empty_input(self):
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as in_file:
in_contents = "x,y,is_respondent,id,weight\n"
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
def test_cli_empty_input_keep_row(self):
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as in_file:
in_contents = "x,y,is_respondent,id,weight,keep_row,batch_column\n"
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y",
"--keep_row",
"keep_row",
"--batch_columns",
"batch_column",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
def test_cli_sep_works(self):
import os
import tempfile
import pandas as pd
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as in_file:
# # create temp folder / file
# in_file = tempfile.NamedTemporaryFile(
# "w", suffix=".csv", delete=False
# )
# temp_dir = tempfile.TemporaryDirectory().name
in_contents = (
"x,y,z,is_respondent,id,weight\n"
+ ("a,b,g,1,1,1\n" * 1000)
+ ("c,b,g,1,1,1\n" * 1000)
+ ("c,b,g,0,1,1\n" * 1000)
+ ("a,d,n,1,2,1\n" * 1000)
)
in_file.write(in_contents)
in_file.close()
# pd.read_csv(in_file)
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y,z",
"--sep_output_file",
";",
"--sep_diagnostics_output_file",
";",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
pd_in_file = pd.read_csv(in_file.name)
pd_out_file = pd.read_csv(out_file, sep=";")
pd_diagnostics_out_file = pd.read_csv(diagnostics_out_file, sep=";")
# test stuff
# Make sure we indeed got all the output files
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
# the original file had 4000 rows (1k target and 3k sample)
self.assertEqual(pd_in_file.shape, (4000, 6))
# the cli output includes only the panel (NOT the target)
# it also includes all the original columns
self.assertEqual(pd_out_file.shape, (3000, 6))
self.assertEqual(pd_out_file.is_respondent.mean(), 1)
# the diagnostics file shows it was calculated on all 3k panelists
ss = pd_diagnostics_out_file.eval(
"(metric == 'size') & (var == 'sample_obs')"
)
self.assertEqual(int(pd_diagnostics_out_file[ss]["val"]), 3000)
# # remove temp folder / file
# os.unlink(in_file.name)
# import shutil
# shutil.rmtree(temp_dir)
def test_cli_sep_input_works(self):
import os
import tempfile
import pandas as pd
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".tsv", delete=False
) as in_file:
in_contents = (
"x\ty\tz\tis_respondent\tid\tweight\n"
+ ("a\tb\tg\t1\t1\t1\n" * 1000)
+ ("c\tb\tg\t1\t1\t1\n" * 1000)
+ ("c\tb\tg\t0\t1\t1\n" * 1000)
+ ("a\td\tn\t1\t2\t1\n" * 1000)
)
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y,z",
"--sep_input_file",
"\t",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
pd_in_file = pd.read_csv(in_file.name, sep="\t")
pd_out_file = pd.read_csv(out_file)
pd_diagnostics_out_file = pd.read_csv(diagnostics_out_file)
# test stuff
# Make sure we indeed got all the output files
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
# the original file had 4000 rows (1k target and 3k sample)
self.assertEqual(pd_in_file.shape, (4000, 6))
# the cli output includes only the panel (NOT the target)
# it also includes all the original columns
self.assertEqual(pd_out_file.shape, (3000, 6))
self.assertEqual(pd_out_file.is_respondent.mean(), 1)
# the diagnostics file shows it was calculated on all 3k panelists
ss = pd_diagnostics_out_file.eval(
"(metric == 'size') & (var == 'sample_obs')"
)
self.assertEqual(int(pd_diagnostics_out_file[ss]["val"]), 3000)
def test_cli_short_arg_names_works(self):
# Some users used only partial arg names for their pipelines
# This is not good practice, but we'd like to not break these pipelines.
# Hence, this test verifies new arguments would still be backward compatible
import os
import tempfile
import pandas as pd
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as in_file:
in_contents = (
"x,y,z,is_respondent,id,weight\n"
+ ("a,b,g,1,1,1\n" * 1000)
+ ("c,b,g,1,1,1\n" * 1000)
+ ("c,b,g,0,1,1\n" * 1000)
+ ("a,d,n,1,2,1\n" * 1000)
)
in_file.write(in_contents)
in_file.close()
# pd.read_csv(in_file)
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input",
in_file.name,
"--output", # instead of output_file
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y,z",
"--sep_output",
";",
"--sep_diagnostics",
";",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
pd_in_file = pd.read_csv(in_file.name)
pd_out_file = pd.read_csv(out_file, sep=";")
pd_diagnostics_out_file = pd.read_csv(diagnostics_out_file, sep=";")
# test stuff
# Make sure we indeed got all the output files
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
# the original file had 4000 rows (1k target and 3k sample)
self.assertEqual(pd_in_file.shape, (4000, 6))
# the cli output includes only the panel (NOT the target)
# it also includes all the original columns
self.assertEqual(pd_out_file.shape, (3000, 6))
self.assertEqual(pd_out_file.is_respondent.mean(), 1)
# the diagnostics file shows it was calculated on all 3k panelists
ss = pd_diagnostics_out_file.eval(
"(metric == 'size') & (var == 'sample_obs')"
)
self.assertEqual(int(pd_diagnostics_out_file[ss]["val"]), 3000)
# TODO: Add tests for max_de
# TODO: Add tests for weight_trimming_mean_ratio
def test_method_works(self):
# TODO: ideally we'll have the example outside, and a different function for each of the methods (ipw, cbps, raking)
np.random.seed(2021)
n_sample = 1000
n_target = 2000
sample_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_sample),
"gender": np.random.choice((1, 2, 3, 4), n_sample),
"id": range(n_sample),
"weight": pd.Series((1,) * n_sample),
}
)
sample_df["is_respondent"] = True
target_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_target),
"gender": np.random.choice((1, 2, 3, 4), n_target),
"id": range(n_target),
"weight": pd.Series((1,) * n_target),
}
)
target_df["is_respondent"] = False
input_dataset = pd.concat([sample_df, target_df])
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as input_file:
input_dataset.to_csv(path_or_buf=input_file)
input_file.close()
output_file = os.path.join(temp_dir, "weights_out.csv")
diagnostics_output_file = os.path.join(temp_dir, "diagnostics_out.csv")
features = "age,gender"
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--method=cbps",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "adjustment_method"][
"var"
].values,
np.array(["cbps"]),
)
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--method=ipw",
"--max_de=1.5",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "adjustment_method"][
"var"
].values,
np.array(["ipw"]),
)
def test_method_works_with_rake(self):
# TODO: ideally we'll have the example outside, and a different function for each of the methods (ipw, cbps, raking)
np.random.seed(2021)
n_sample = 1000
n_target = 2000
sample_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_sample),
"gender": np.random.choice((1, 2, 3, 4), n_sample),
"id": range(n_sample),
"weight": pd.Series((1,) * n_sample),
}
)
sample_df["is_respondent"] = True
target_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_target),
"gender": np.random.choice((1, 2, 3, 4), n_target),
"id": range(n_target),
"weight": pd.Series((1,) * n_target),
}
)
target_df["is_respondent"] = False
input_dataset = pd.concat([sample_df, target_df])
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as input_file:
input_dataset.to_csv(path_or_buf=input_file)
input_file.close()
output_file = os.path.join(temp_dir, "weights_out.csv")
diagnostics_output_file = os.path.join(temp_dir, "diagnostics_out.csv")
features = "age,gender"
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--method=rake",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "adjustment_method"][
"var"
].values,
np.array(["rake"]),
)
def test_one_hot_encoding_works(self):
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".tsv", delete=False
) as in_file:
# Assert value is False when "False" is passed
out_file = os.path.join(temp_dir, "out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--covariate_columns",
"x,y",
"--one_hot_encoding",
"False",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
self.assertFalse(cli.one_hot_encoding())
self.assertEqual(type(cli.one_hot_encoding()), bool)
# Assert value is True by default
args2 = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--covariate_columns",
"x,y",
]
)
cli2 = BalanceCLI(args2)
cli2.update_attributes_for_main_used_by_adjust()
self.assertTrue(cli2.one_hot_encoding())
self.assertEqual(type(cli2.one_hot_encoding()), bool)
# Assert invalid value raises an error
with self.assertRaises(ValueError):
args3 = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--covariate_columns",
"x,y",
"--one_hot_encoding",
"Invalid Value",
]
)
cli3 = BalanceCLI(args3)
cli3.update_attributes_for_main_used_by_adjust()
def test_transformations_works(self):
# TODO: ideally we'll have the example outside
np.random.seed(2021)
n_sample = 1000
n_target = 2000
sample_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_sample),
"gender": np.random.choice((1, 2, 3, 4), n_sample),
"id": range(n_sample),
"weight": pd.Series((1,) * n_sample),
}
)
sample_df["is_respondent"] = True
target_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_target),
"gender": np.random.choice((1, 2, 3, 4), n_target),
"id": range(n_target),
"weight": pd.Series((1,) * n_target),
}
)
target_df["is_respondent"] = False
input_dataset = pd.concat([sample_df, target_df])
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as input_file:
input_dataset.to_csv(path_or_buf=input_file)
input_file.close()
output_file = os.path.join(temp_dir, "weights_out.csv")
diagnostics_output_file = os.path.join(temp_dir, "diagnostics_out.csv")
features = "age,gender"
# test transformations=None
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--transformations=None",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "model_coef"][
"var"
].values,
np.array(["intercept", "age", "gender"]),
)
# test transformations='default'
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--transformations=default",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "model_coef"][
"var"
].values,
np.array(
[
"intercept",
"C(age, one_hot_encoding_greater_2)[(0.00264, 10.925]]",
"C(age, one_hot_encoding_greater_2)[(10.925, 20.624]]",
"C(age, one_hot_encoding_greater_2)[(20.624, 30.985]]",
"C(age, one_hot_encoding_greater_2)[(30.985, 41.204]]",
"C(age, one_hot_encoding_greater_2)[(41.204, 51.335]]",
"C(age, one_hot_encoding_greater_2)[(51.335, 61.535]]",
"C(age, one_hot_encoding_greater_2)[(61.535, 71.696]]",
"C(age, one_hot_encoding_greater_2)[(71.696, 80.08]]",
"C(age, one_hot_encoding_greater_2)[(80.08, 89.446]]",
"C(age, one_hot_encoding_greater_2)[(89.446, 99.992]]",
"C(gender, one_hot_encoding_greater_2)[(0.999, 2.0]]",
"C(gender, one_hot_encoding_greater_2)[(2.0, 3.0]]",
"C(gender, one_hot_encoding_greater_2)[(3.0, 4.0]]",
]
),
)
# test default value for transformations
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "model_coef"][
"var"
].values,
np.array(
[
"intercept",
"C(age, one_hot_encoding_greater_2)[(0.00264, 10.925]]",
"C(age, one_hot_encoding_greater_2)[(10.925, 20.624]]",
"C(age, one_hot_encoding_greater_2)[(20.624, 30.985]]",
"C(age, one_hot_encoding_greater_2)[(30.985, 41.204]]",
"C(age, one_hot_encoding_greater_2)[(41.204, 51.335]]",
"C(age, one_hot_encoding_greater_2)[(51.335, 61.535]]",
"C(age, one_hot_encoding_greater_2)[(61.535, 71.696]]",
"C(age, one_hot_encoding_greater_2)[(71.696, 80.08]]",
"C(age, one_hot_encoding_greater_2)[(80.08, 89.446]]",
"C(age, one_hot_encoding_greater_2)[(89.446, 99.992]]",
"C(gender, one_hot_encoding_greater_2)[(0.999, 2.0]]",
"C(gender, one_hot_encoding_greater_2)[(2.0, 3.0]]",
"C(gender, one_hot_encoding_greater_2)[(3.0, 4.0]]",
]
),
)
def test_formula_works(self):
# TODO: ideally we'll have the example outside
np.random.seed(2021)
n_sample = 1000
n_target = 2000
sample_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_sample),
"gender": np.random.choice((1, 2, 3, 4), n_sample),
"id": range(n_sample),
"weight": pd.Series((1,) * n_sample),
}
)
sample_df["is_respondent"] = True
target_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_target),
"gender": np.random.choice((1, 2, 3, 4), n_target),
"id": range(n_target),
"weight": pd.Series((1,) * n_target),
}
)
target_df["is_respondent"] = False
input_dataset = pd.concat([sample_df, target_df])
with tempfile.TemporaryDirectory() as temp_dir, tempfile.NamedTemporaryFile(
"w", suffix=".csv", delete=False
) as input_file:
input_dataset.to_csv(path_or_buf=input_file)
input_file.close()
output_file = os.path.join(temp_dir, "weights_out.csv")
diagnostics_output_file = os.path.join(temp_dir, "diagnostics_out.csv")
features = "age,gender"
# test no formula
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--transformations=None",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "model_coef"][
"var"
].values,
np.array(["intercept", "age", "gender"]),
)
# test transformations=age*gender
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--transformations=None",
"--formula=age*gender",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "model_coef"][
"var"
].values,
np.array(["intercept", "age", "age:gender", "gender"]),
)
def test_cli_return_df_with_original_dtypes(self):
out_True = check_some_flags(True, "--return_df_with_original_dtypes")
out_False = check_some_flags(False, "--return_df_with_original_dtypes")
# IF the flag 'return_df_with_original_dtypes' is not passed, then the dtypes of the output dataframes are different
self.assertEqual(
out_False["pd_in"].dtypes.to_dict(),
{
"x": dtype("float64"),
"y": dtype("int64"),
"is_respondent": dtype("int64"),
"id": dtype("int64"),
"weight": dtype("int64"),
},
)
self.assertEqual(
out_False["pd_out"].dtypes.to_dict(),
{
"id": dtype("int64"),
"x": dtype("float64"),
"y": dtype("float64"),
"is_respondent": dtype("float64"),
"weight": dtype("float64"),
},
)
# IF the flag 'return_df_with_original_dtypes' IS passed, then the dtypes of the output dataframes are the SAME:
# The input df dtypes are the same
self.assertEqual(
out_True["pd_in"].dtypes.to_dict(), out_False["pd_in"].dtypes.to_dict()
)
# But now the output df dtypes are also the same (the order of the columns is different though)
self.assertEqual(
out_True["pd_out"].dtypes.to_dict(),
{
"id": dtype("int64"),
"x": dtype("float64"),
"y": dtype("int64"),
"is_respondent": dtype("int64"),
"weight": dtype("int64"),
},
)
def test_cli_standardize_types(self):
out_False = check_some_flags(True, "--standardize_types=False")
out_True = check_some_flags(
False, "--standardize_types=True"
) # This is the same as not using the flag at all
out_True_flag_on = check_some_flags(
True, "--standardize_types=True"
) # This is the same as not using the flag at all
# IF the flag 'skip_standardize_types' is not passed, then the dtypes of the output dataframes are different
self.assertEqual(
out_True["pd_in"].dtypes.to_dict(),
{
"x": dtype("float64"),
"y": dtype("int64"),
"is_respondent": dtype("int64"),
"id": dtype("int64"),
"weight": dtype("int64"),
},
)
self.assertEqual(
out_True["pd_out"].dtypes.to_dict(),
{
"id": dtype("int64"),
"x": dtype("float64"),
"y": dtype("float64"),
"is_respondent": dtype("float64"),
"weight": dtype("float64"),
},
)
# IF the flag 'skip_standardize_types' IS passed, then the dtypes of the output dataframes are the SAME:
# The input df dtypes are the same
self.assertEqual(
out_False["pd_in"].dtypes.to_dict(), out_True["pd_in"].dtypes.to_dict()
)
# But now the output df dtypes are also the same (the order of the columns is different though)
self.assertEqual(
out_False["pd_out"].dtypes.to_dict(),
{
"id": dtype("int64"),
"x": dtype("float64"),
"y": dtype("int64"),
"is_respondent": dtype("int64"),
"weight": dtype("float64"),
},
)
self.assertEqual(
out_True["pd_out"].dtypes.to_dict(),
out_True_flag_on["pd_out"].dtypes.to_dict(),
)
| balance-main | tests/test_cli.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import balance.testutil
import numpy as np
import pandas as pd
class TestBalance_weights_stats(
balance.testutil.BalanceTestCase,
):
def test__check_weights_are_valid(self):
from balance.stats_and_plots.weights_stats import _check_weights_are_valid
w = [np.inf, 1, 2, 1.0, 0]
self.assertEqual(_check_weights_are_valid(w), None)
self.assertEqual(_check_weights_are_valid(np.array(w)), None)
self.assertEqual(_check_weights_are_valid(pd.Series(w)), None)
self.assertEqual(_check_weights_are_valid(pd.DataFrame(w)), None)
self.assertEqual(_check_weights_are_valid(pd.DataFrame({"a": w})), None)
self.assertEqual(
_check_weights_are_valid(pd.DataFrame({"a": w, "b": [str(x) for x in w]})),
None,
) # checking only the first column
with self.assertRaisesRegex(TypeError, "weights \\(w\\) must be a number*"):
_check_weights_are_valid([str(x) for x in w])
with self.assertRaisesRegex(TypeError, "weights \\(w\\) must be a number*"):
w = ["a", "b"]
_check_weights_are_valid(w)
with self.assertRaisesRegex(
ValueError, "weights \\(w\\) must all be non-negative values."
):
w = [-1, 0, 1]
_check_weights_are_valid(w)
def test_design_effect(self):
from balance.stats_and_plots.weights_stats import design_effect
self.assertEqual(design_effect(pd.Series((1, 1, 1, 1))), 1)
self.assertEqual(
design_effect(pd.Series((0, 1, 2, 3))),
1.555_555_555_555_555_6,
)
self.assertEqual(type(design_effect(pd.Series((0, 1, 2, 3)))), np.float64)
def test_nonparametric_skew(self):
from balance.stats_and_plots.weights_stats import nonparametric_skew
self.assertEqual(nonparametric_skew(pd.Series((1, 1, 1, 1))), 0)
self.assertEqual(nonparametric_skew(pd.Series((1))), 0)
self.assertEqual(nonparametric_skew(pd.Series((1, 2, 3, 4))), 0)
self.assertEqual(nonparametric_skew(pd.Series((1, 1, 1, 2))), 0.5)
def test_prop_above_and_below(self):
from balance.stats_and_plots.weights_stats import prop_above_and_below
self.assertEqual(
prop_above_and_below(pd.Series((1, 1, 1, 1))).astype(int).to_list(),
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
)
self.assertEqual(
prop_above_and_below(pd.Series((1, 2, 3, 4))).to_list(),
[0.0, 0.0, 0.0, 0.25, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0],
)
self.assertEqual(
prop_above_and_below(
pd.Series((1, 2, 3, 4)), below=(0.1, 0.5), above=(2, 3)
).to_list(),
[0.0, 0.25, 0.0, 0.0],
)
self.assertEqual(
prop_above_and_below(
pd.Series((1, 2, 3, 4)), below=(0.1, 0.5), above=(2, 3)
).index.to_list(),
["prop(w < 0.1)", "prop(w < 0.5)", "prop(w >= 2)", "prop(w >= 3)"],
)
self.assertEqual(
prop_above_and_below(pd.Series((1, 2, 3, 4)), above=None, below=None), None
)
# test return_as_series = False
self.assertEqual(
{
k: v.to_list()
for k, v in prop_above_and_below(
pd.Series((1, 2, 3, 4)), return_as_series=False
).items()
},
{"below": [0.0, 0.0, 0.0, 0.25, 0.5], "above": [0.5, 0.0, 0.0, 0.0, 0.0]},
)
def test_weighted_median_breakdown_point(self):
import pandas as pd
from balance.stats_and_plots.weights_stats import (
weighted_median_breakdown_point,
)
self.assertEqual(weighted_median_breakdown_point(pd.Series((1, 1, 1, 1))), 0.5)
self.assertEqual(weighted_median_breakdown_point(pd.Series((2, 2, 2, 2))), 0.5)
self.assertEqual(
weighted_median_breakdown_point(pd.Series((1, 1, 1, 10))), 0.25
)
self.assertEqual(
weighted_median_breakdown_point(pd.Series((1, 1, 1, 1, 10))), 0.2
)
class TestBalance_weighted_stats(
balance.testutil.BalanceTestCase,
):
def test__prepare_weighted_stat_args(self):
from balance.stats_and_plots.weighted_stats import _prepare_weighted_stat_args
v, w = [-1, 0, 1, np.inf], [np.inf, 1, 2, 1.0]
v2, w2 = _prepare_weighted_stat_args(v, w, False)
# assert the new types:
self.assertEqual(type(v2), pd.DataFrame)
self.assertEqual(type(w2), pd.Series)
v, w = pd.Series([-1, 0, 1, np.inf]), pd.Series([np.inf, 1, 2, 1.0])
v2, w2 = _prepare_weighted_stat_args(v, w, False)
# assert the new types:
self.assertEqual(type(v2), pd.DataFrame)
self.assertEqual(type(w2), pd.Series)
# check the values are the same:
self.assertEqual(v.to_list(), v2[0].to_list())
self.assertEqual(w.to_list(), w2.to_list())
# Do we have any inf or nan?
self.assertTrue(any(np.isinf(v2[0])))
self.assertTrue(any(np.isinf(w2)))
self.assertTrue(not any(np.isnan(v2[0])))
self.assertTrue(not any(np.isnan(w2)))
# Checking how it works when inf_rm = True
v2, w2 = _prepare_weighted_stat_args(v, w, True)
# assert the new types:
self.assertEqual(type(v2), pd.DataFrame)
self.assertEqual(type(w2), pd.Series)
# check the values are the NOT same (because the Inf was turned to nan):
self.assertNotEqual(v.to_list(), v2[0].to_list())
self.assertNotEqual(w.to_list(), w2.to_list())
# Do we have any inf or nan?
self.assertTrue(not any(np.isinf(v2[0])))
self.assertTrue(not any(np.isinf(w2)))
self.assertTrue(any(np.isnan(v2[0])))
self.assertTrue(any(np.isnan(w2)))
# Check that it catches wrong input types
with self.assertRaises(TypeError):
v, w = pd.Series([1, 2]), np.matrix([1, 2]).T
v2, w2 = _prepare_weighted_stat_args(v, w)
with self.assertRaises(TypeError):
v, w = pd.Series([1, 2]), (1, 2)
v2, w2 = _prepare_weighted_stat_args(v, w)
with self.assertRaises(TypeError):
v, w = (1, 2), pd.Series([1, 2])
v2, w2 = _prepare_weighted_stat_args(v, w)
with self.assertRaises(ValueError):
v, w = pd.Series([1, 2, 3]), pd.Series([1, 2])
v2, w2 = _prepare_weighted_stat_args(v, w)
with self.assertRaises(TypeError):
v, w = pd.Series(["a", "b"]), pd.Series([1, 2])
v2, w2 = _prepare_weighted_stat_args(v, w)
# check other input types for v and w
# np.array
v, w = np.array([-1, 0, 1, np.inf]), np.array([np.inf, 1, 2, 1.0])
v2, w2 = _prepare_weighted_stat_args(v, w, False)
# assert the new types:
self.assertEqual(type(v2), pd.DataFrame)
self.assertEqual(type(w2), pd.Series)
# pd.DataFrame
v, w = pd.DataFrame([-1, 0, 1, np.inf]), np.array([np.inf, 1, 2, 1.0])
v2, w2 = _prepare_weighted_stat_args(v, w, False)
# assert the new types:
self.assertEqual(type(v2), pd.DataFrame)
self.assertEqual(type(w2), pd.Series)
# np.matrix
v, w = np.matrix([-1, 0, 1, np.inf]).T, np.array([np.inf, 1, 2, 1.0])
v2, w2 = _prepare_weighted_stat_args(v, w, False)
# assert the new types:
self.assertEqual(type(v2), pd.DataFrame)
self.assertEqual(type(w2), pd.Series)
# Dealing with w=None
v, w = pd.Series([-1, 0, 1, np.inf]), None
v2, w2 = _prepare_weighted_stat_args(v, w, False)
self.assertEqual(type(v2), pd.DataFrame)
self.assertEqual(type(w2), pd.Series)
self.assertEqual(w2, pd.Series([1.0, 1.0, 1.0, 1.0]))
self.assertTrue(len(w2) == 4)
# Verify defaults:
self.assertEqual(
_prepare_weighted_stat_args(v, None, False)[0],
_prepare_weighted_stat_args(v)[0],
)
with self.assertRaises(ValueError):
v, w = pd.Series([-1, 0, 1, np.inf]), pd.Series([np.inf, 1, -2, 1.0])
v2, w2 = _prepare_weighted_stat_args(v, w)
def test_weighted_mean(self):
from balance.stats_and_plots.weighted_stats import weighted_mean
# No weights
self.assertEqual(weighted_mean(pd.Series([-1, 0, 1, 2])), pd.Series(0.5))
self.assertEqual(weighted_mean(pd.Series([-1, None, 1, 2])), pd.Series(0.5))
# No weights, with one inf value
self.assertEqual(
weighted_mean(pd.Series([-1, np.inf, 1, 2])),
pd.Series(np.inf),
)
self.assertEqual(
weighted_mean(pd.Series([-1, np.inf, 1, 2]), inf_rm=True),
pd.Series(0.5),
)
# Inf value in weights
self.assertTrue(
all(
np.isnan(
weighted_mean(
pd.Series([-1, 2, 1, 2]), w=pd.Series([1, np.inf, 1, 1])
)
)
)
)
self.assertEqual(
weighted_mean(
pd.Series([-1, 2, 1, 2]), w=pd.Series([1, np.inf, 1, 1]), inf_rm=True
),
pd.Series(2 / 3),
)
# With weights
self.assertEqual(
weighted_mean(pd.Series([-1, 2, 1, 2]), w=pd.Series([1, 2, 3, 4])),
pd.Series(1.4),
)
self.assertEqual(
weighted_mean(pd.Series([-1, 2, 1, 2]), w=pd.Series([1, None, 1, 1])),
pd.Series(2 / 3),
)
# Notice that while None values are ignored, their weights will still be used in the denominator
# Hence, None in values acts like 0
self.assertEqual(
weighted_mean(pd.Series([-1, None, 1, 2]), w=pd.Series([1, 0, 1, 1])),
pd.Series(2 / 3),
)
self.assertEqual(
weighted_mean(pd.Series([-1, np.nan, 1, 2]), w=pd.Series([1, 0, 1, 1])),
pd.Series(2 / 3),
)
self.assertEqual(
weighted_mean(pd.Series([-1, None, 1, 2]), w=pd.Series([1, 1, 1, 1])),
pd.Series(1 / 2),
)
# None in the values is just like 0
self.assertEqual(
weighted_mean(pd.Series([-1, None, 1, 2]), w=pd.Series([1, 1, 1, 1])),
weighted_mean(pd.Series([-1, 0, 1, 2]), w=pd.Series([1, 1, 1, 1])),
)
# pd.DataFrame v
d = pd.DataFrame([(-1, 2, 1, 2), (1, 2, 3, 4)]).transpose()
pd.testing.assert_series_equal(weighted_mean(d), pd.Series((1, 2.5)))
pd.testing.assert_series_equal(
weighted_mean(d, w=pd.Series((1, 2, 3, 4))),
pd.Series((1.4, 3)),
)
# np.matrix v
d = np.matrix([(-1, 2, 1, 2), (1, 2, 3, 4)]).transpose()
pd.testing.assert_series_equal(weighted_mean(d), pd.Series((1, 2.5)))
pd.testing.assert_series_equal(
weighted_mean(d, w=pd.Series((1, 2, 3, 4))),
pd.Series((1.4, 3)),
)
# Test input validation
with self.assertRaisesRegex(TypeError, "must be numeric"):
weighted_mean(pd.Series(["a", "b"]))
with self.assertRaisesRegex(TypeError, "must be numeric"):
weighted_mean(pd.DataFrame({"a": [1, 2], "b": ["a", "b"]}))
with self.assertRaisesRegex(ValueError, "must have same number of rows"):
weighted_mean(pd.Series([1, 2]), pd.Series([1, 2, 3]))
with self.assertRaisesRegex(ValueError, "must have same number of rows"):
weighted_mean(pd.DataFrame({"a": [1, 2]}), pd.Series([1]))
# Make sure that index is ignored
self.assertEqual(
weighted_mean(
pd.Series([-1, 2, 1, 2], index=(0, 1, 2, 3)),
w=pd.Series([1, 2, 3, 4], index=(5, 6, 7, 8)),
inf_rm=True,
),
pd.Series((-1 * 1 + 2 * 2 + 1 * 3 + 2 * 4) / (1 + 2 + 3 + 4)),
)
self.assertEqual(
weighted_mean(
pd.Series([-1, 2, 1, 2], index=(0, 1, 2, 3)),
w=pd.Series([1, 2, 3, 4], index=(0, 6, 7, 8)),
inf_rm=True,
),
pd.Series((-1 * 1 + 2 * 2 + 1 * 3 + 2 * 4) / (1 + 2 + 3 + 4)),
)
def var_of_weighted_mean(self):
from balance.stats_and_plots.weighted_stats import var_of_weighted_mean
# Test no weights assigned
# In R: sum((1:4 - mean(1:4))^2 / 4) / (4)
# [1] 0.3125
self.assertEqual(
var_of_weighted_mean(pd.Series((1, 2, 3, 4))), pd.Series(0.3125)
)
# For a reproducible R example, see: https://gist.github.com/talgalili/b92cd8cdcbfc287e331a8f27db265c00
self.assertEqual(
var_of_weighted_mean(pd.Series((1, 2, 3, 4)), pd.Series((1, 2, 3, 4))),
pd.Series(0.24),
)
def ci_of_weighted_mean(self):
from balance.stats_and_plots.weighted_stats import ci_of_weighted_mean
self.assertEqual(
ci_of_weighted_mean(pd.Series((1, 2, 3, 4)), round_ndigits=3).to_list(),
[(1.404, 3.596)],
)
self.assertEqual(
ci_of_weighted_mean(
pd.Series((1, 2, 3, 4)), pd.Series((1, 2, 3, 4)), round_ndigits=3
).to_list(),
[(2.04, 3.96)],
)
df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [1, 1, 1, 1]})
w = pd.Series((1, 2, 3, 4))
self.assertEqual(
ci_of_weighted_mean(df, w, conf_level=0.99, round_ndigits=3).to_dict(),
{"a": (1.738, 4.262), "b": (1.0, 1.0)},
)
def test_weighted_var(self):
from balance.stats_and_plots.weighted_stats import weighted_var
# > var(c(1, 2, 3, 4))
# [1] 1.66667
self.assertEqual(weighted_var(pd.Series((1, 2, 3, 4))), pd.Series(5 / 3))
# > SDMTools::wt.var(c(1, 2), c(1, 2))
# [1] 0.5
self.assertEqual(
weighted_var(pd.Series((1, 2)), pd.Series((1, 2))), pd.Series(0.5)
)
def test_weighted_sd(self):
from balance.stats_and_plots.weighted_stats import weighted_sd
# > sd(c(1, 2, 3, 4))
# [1] 1.290994
self.assertEqual(weighted_sd(pd.Series((1, 2, 3, 4))), pd.Series(1.290_994))
# > SDMTools::wt.sd(c(1, 2), c(1, 2))
# [1] 0.7071068
self.assertEqual(
weighted_sd(pd.Series((1, 2)), pd.Series((1, 2))),
pd.Series(0.707_106_8),
)
x = [1, 2, 3, 4]
x2 = pd.Series(x)
manual_std = np.sqrt(np.sum((x2 - x2.mean()) ** 2) / (len(x) - 1))
self.assertEqual(round(weighted_sd(x)[0], 5), round(manual_std, 5))
def test_weighted_quantile(self):
from balance.stats_and_plots.weighted_stats import weighted_quantile
self.assertEqual(
weighted_quantile(np.arange(1, 100, 1), 0.5).values,
np.array(((50,),)),
)
# In R: reldist::wtd.quantile(c(1, 2, 3), q=c(0.5, 0.75), weight=c(1, 1, 2))
self.assertEqual(
weighted_quantile(np.array([1, 2, 3]), (0.5, 0.75)).values,
np.array(((2,), (3,))),
)
self.assertEqual(
weighted_quantile(np.array([1, 2, 3]), 0.5, np.array([1, 1, 2])).values,
np.percentile([1, 2, 3, 3], 50),
)
# verify it indeed works with pd.DataFrame input
# no weights
self.assertEqual(
weighted_quantile(
pd.DataFrame([[1, 2, 3, 4], [1, 1, 1, 1]]).transpose(),
[0.25, 0.5],
).values,
np.array([[1.5, 1.0], [2.5, 1.0]]),
)
# with weights
self.assertEqual(
weighted_quantile(
pd.DataFrame([[1, 2, 3, 4], [1, 1, 1, 1]]).transpose(),
[0.25, 0.5],
w=pd.Series([1, 1, 0, 0]),
).values,
np.array([[1.0, 1.0], [1.5, 1.0]]),
)
self.assertEqual(
weighted_quantile(
pd.DataFrame([[1, 2, 3, 4], [1, 1, 1, 1]]).transpose(),
[0.25, 0.5],
w=pd.Series([1, 100, 1, 1]),
).values,
np.array([[2.0, 1.0], [2.0, 1.0]]),
)
# verify it indeed works with np.matrix input
# no weights
self.assertEqual(
weighted_quantile(
np.matrix([[1, 2, 3, 4], [1, 1, 1, 1]]).transpose(),
[0.25, 0.5],
).values,
np.array([[1.5, 1.0], [2.5, 1.0]]),
)
# with weights
self.assertEqual(
weighted_quantile(
np.matrix([[1, 2, 3, 4], [1, 1, 1, 1]]).transpose(),
[0.25, 0.5],
w=pd.Series([1, 1, 0, 0]),
).values,
np.array([[1.0, 1.0], [1.5, 1.0]]),
)
self.assertEqual(
weighted_quantile(
np.matrix([[1, 2, 3, 4], [1, 1, 1, 1]]).transpose(),
[0.25, 0.5],
w=pd.Series([1, 100, 1, 1]),
).values,
np.array([[2.0, 1.0], [2.0, 1.0]]),
)
def test_descriptive_stats(self):
from balance.stats_and_plots.weighted_stats import (
descriptive_stats,
weighted_mean,
weighted_sd,
)
from statsmodels.stats.weightstats import DescrStatsW
x = pd.Series([-1, 0, 1, 2])
self.assertEqual(
descriptive_stats(pd.DataFrame(x), stat="mean"),
weighted_mean(x).to_frame().T,
)
self.assertEqual(
descriptive_stats(pd.DataFrame(x), stat="std"), weighted_sd(x).to_frame().T
)
x = [1, 2, 3, 4]
self.assertEqual(
descriptive_stats(pd.DataFrame(x), stat="var_of_mean").to_dict(),
{0: {0: 0.3125}},
)
# with weights
x, w = pd.Series([-1, 2, 1, 2]), pd.Series([1, 2, 3, 4])
self.assertEqual(
descriptive_stats(pd.DataFrame(x), w, stat="mean"),
weighted_mean(x, w).to_frame().T,
)
self.assertEqual(
descriptive_stats(pd.DataFrame(x), w, stat="std"),
weighted_sd(x, w).to_frame().T,
)
# show that with/without weights gives different results
self.assertNotEqual(
descriptive_stats(pd.DataFrame(x), stat="mean").iloc[0, 0],
descriptive_stats(pd.DataFrame(x), w, stat="mean").iloc[0, 0],
)
self.assertNotEqual(
descriptive_stats(pd.DataFrame(x), stat="std").iloc[0, 0],
descriptive_stats(pd.DataFrame(x), w, stat="std").iloc[0, 0],
)
# shows that descriptive_stats can calculate std_mean and that it's smaller than std (as expected.)
self.assertTrue(
descriptive_stats(pd.DataFrame(x), w, stat="std").iloc[0, 0]
> descriptive_stats(pd.DataFrame(x), w, stat="std_mean").iloc[0, 0]
)
x = [1, 2, 3, 4]
x2 = pd.Series(x)
tmp_sd = np.sqrt(np.sum((x2 - x2.mean()) ** 2) / (len(x) - 1))
tmp_se = tmp_sd / np.sqrt(len(x))
self.assertEqual(
round(descriptive_stats(pd.DataFrame(x), stat="std_mean").iloc[0, 0], 5),
round(tmp_se, 5),
)
# verify DescrStatsW can deal with None weights
self.assertEqual(
DescrStatsW([1, 2, 3], weights=[1, 1, 1]).mean,
DescrStatsW([1, 2, 3], weights=None).mean,
)
self.assertEqual(
DescrStatsW([1, 2, 3], weights=None).mean,
2.0,
)
x, w = [1, 2, 3, 4], [1, 2, 3, 4]
self.assertEqual(
descriptive_stats(pd.DataFrame(x), w, stat="var_of_mean").to_dict(),
{0: {0: 0.24}},
)
self.assertEqual(
descriptive_stats(
pd.DataFrame(x), w, stat="ci_of_mean", conf_level=0.99, round_ndigits=3
).to_dict(),
{0: {0: (1.738, 4.262)}},
)
class TestBalance_weighted_comparisons_stats(
balance.testutil.BalanceTestCase,
):
def test_outcome_variance_ratio(self):
from balance.stats_and_plots.weighted_comparisons_stats import (
outcome_variance_ratio,
)
np.random.seed(876324)
d = pd.DataFrame(np.random.rand(1000, 11))
d["id"] = range(0, d.shape[0])
d = d.rename(columns={i: "abcdefghijk"[i] for i in range(0, 11)})
self.assertEqual(
outcome_variance_ratio(d[["j", "k"]], d[["j", "k"]]),
pd.Series([1.0, 1.0], index=["j", "k"]),
)
def test__weights_per_covars_names(self):
# toy example
from balance.stats_and_plots.weighted_comparisons_stats import (
_weights_per_covars_names,
)
asmd_df = pd.DataFrame(
{
"age": 0.5,
"education[T.high_school]": 1,
"education[T. bachelor]": 1,
"education[T. masters]": 1,
"education[T. phd]": 1,
},
index=("self",),
)
outcome = _weights_per_covars_names(asmd_df.columns.values.tolist()).to_dict()
# We expect a df with 2 columns: weight and main_covar_names.
expected = {
"weight": {
"age": 1.0,
"education[T.high_school]": 0.25,
"education[T. bachelor]": 0.25,
"education[T. masters]": 0.25,
"education[T. phd]": 0.25,
},
"main_covar_names": {
"age": "age",
"education[T.high_school]": "education",
"education[T. bachelor]": "education",
"education[T. masters]": "education",
"education[T. phd]": "education",
},
}
self.assertEqual(outcome, expected)
def test_asmd(self):
from balance.stats_and_plots.weighted_comparisons_stats import asmd
with self.assertRaisesRegex(ValueError, "sample_df must be pd.DataFrame, is*"):
# Using wild card since it will return:
# "sample_df must be pd.DataFrame, is* <class 'pandas.core.series.Series'>"
asmd(
pd.Series((0, 1, 2, 3)),
pd.Series((0, 1, 2, 3)),
pd.Series((0, 1, 2, 3)),
pd.Series((0, 1, 2, 3)),
)
with self.assertRaisesRegex(ValueError, "target_df must be pd.DataFrame, is*"):
asmd(
pd.DataFrame({"a": (0, 1, 2, 3)}),
pd.Series((0, 1, 2, 3)),
pd.Series((0, 1, 2, 3)),
pd.Series((0, 1, 2, 3)),
)
# If column names are different, it will only calculate asmd for
# the overlapping columns. The rest will be np.nan.
# The mean(asmd) will be calculated while treating the nan values as 0s.
self.assertEqual(
np.isnan(
asmd(
pd.DataFrame({"a": (1, 2), "b": (-1, 12)}),
pd.DataFrame({"a": (3, 4), "c": (5, 6)}),
)
).tolist(),
[False, True, True, False],
)
with self.assertRaisesRegex(ValueError, "std_type must be in*"):
asmd(
pd.DataFrame({"a": (1, 2), "b": (-1, 12)}),
pd.DataFrame({"a": (3, 4), "c": (5, 6)}),
std_type="magic variance type that doesn't exist",
)
# TODO: (p2) add comparison to the following numbers
# Benchmark for the numbers:
# ---------------------------
# Test data from R cobalt package:
# cobalt::bal.tab(
# data.frame(a=c(1, 2, 3, 4), b=c(-1, 12, 0, 42)),
# treat=c(1, 1, 0, 0),
# weights=c(1, 2, 1, 2),
# s.d.denom='control',
# method='weighting'
# )
# Output:
# Balance Measures
# Type Diff.Adj
# a Contin. -2.8284
# b Contin. -0.6847
# Effective sample sizes
# Control Treated
# Unadjusted 2. 2.
# Adjusted 1.8 1.8
# show the default "target" calculation is working as expected
a1 = pd.Series((1, 2))
b1 = pd.Series((-1, 1))
a2 = pd.Series((3, 4))
b2 = pd.Series((-2, 2))
w1 = pd.Series((1, 1))
w2 = w1
r = asmd(
pd.DataFrame({"a": a1, "b": b1}),
pd.DataFrame({"a": a2, "b": b2}),
w1,
w2,
).to_dict()
exp_a = np.abs(a1.mean() - a2.mean()) / a2.std()
exp_b = np.abs(b1.mean() - b2.mean()) / b2.std()
self.assertEqual((r["a"], r["b"]), (exp_a, exp_b))
# show that the default is weights equal 1.
r_no_weights = asmd(
pd.DataFrame({"a": a1, "b": b1}),
pd.DataFrame({"a": a2, "b": b2}),
).to_dict()
self.assertEqual(r, r_no_weights)
# demonstrate that weights effect the outcome (use 0 weights.)
a1 = pd.Series((1, 2, 100))
b1 = pd.Series((-1, 1, 100))
a2 = pd.Series((3, 4, 100))
b2 = pd.Series((-2, 2, 100))
w1 = pd.Series((1, 1, 0))
w2 = w1
r_with_0_3rd_weight = asmd(
pd.DataFrame({"a": a1, "b": b1}),
pd.DataFrame({"a": a2, "b": b2}),
w1,
w2,
).to_dict()
self.assertEqual(r, r_with_0_3rd_weight)
# Not passing weights is the same as weights of all 1s
r = asmd(
pd.DataFrame({"a": (1, 2), "b": (-1, 12)}),
pd.DataFrame({"a": (3, 4), "b": (0, 42)}),
pd.Series((1, 2)),
pd.Series((1, 2)),
)
e_asmd = pd.Series(
(2.828_427_1, 0.684_658_9, (2.828_427_1 + 0.684_658_9) / 2),
index=("a", "b", "mean(asmd)"),
)
self.assertEqual(r, e_asmd)
self.assertEqual(type(r), pd.Series)
r = asmd(
pd.DataFrame({"a": (1, 2), "b": (-1, 12)}),
pd.DataFrame({"a": (3, 4), "b": (0, 42)}),
pd.Series((1, 2)),
pd.Series((1, 2)),
)
e_asmd = pd.Series(
(2.828_427_1, 0.684_658_9, (2.828_427_1 + 0.684_658_9) / 2),
index=("a", "b", "mean(asmd)"),
)
self.assertEqual(r, e_asmd)
# Test different std_types
args = (
pd.DataFrame({"a": (1, 2), "b": (-1, 12)}),
pd.DataFrame({"a": (3, 4), "b": (0, 42)}),
pd.Series((1, 2)),
pd.Series((1, 2)),
)
r = asmd(*args, std_type="target")
self.assertEqual(r, e_asmd)
# TODO: this should be called : test consistency of asmd
r = asmd(*args, std_type="sample")
e_asmd_sample = pd.Series(
(
2.828_427_124_746_189_4,
2.211_975_059_096_379,
(2.828_427_124_746_189_4 + 2.211_975_059_096_379) / 2,
),
index=("a", "b", "mean(asmd)"),
)
self.assertEqual(r, e_asmd_sample)
r = asmd(*args, std_type="pooled")
e_asmd_pooled = pd.Series(
(2.828_427_1, 0.924_959_4, (2.828_427_1 + 0.924_959_4) / 2),
index=("a", "b", "mean(asmd)"),
)
self.assertEqual(r, e_asmd_pooled)
# Test with categoricals
# Categorical variable has missing value in one df
r = asmd(
pd.DataFrame({"c": ("x", "y", "x", "x"), "a": (5, 6, 7, 8)}),
pd.DataFrame({"c": ("x", "y", "x", "z"), "a": (1, 2, 3, 4)}),
pd.Series((1, 2, 3, 4)),
pd.Series((1, 1, 1, 1)),
)
e_asmd = pd.Series(
(
3.485_685_011_586_675_3,
0.519_615_242_270_663_2,
0.099_999_999_999_999_98,
np.nan,
(
3.485_685_011_586_675_3
+ 0.519_615_242_270_663_2 * (1 / 3)
+ 0.099_999_999_999_999_98 * (1 / 3)
+ 0 * (1 / 3)
)
/ (2),
),
index=("a", "c[x]", "c[y]", "c[z]", "mean(asmd)"),
)
self.assertEqual(r, e_asmd)
# Check that using aggregate_by_main_covar works
a1 = pd.Series((1, 2))
b1_A = pd.Series((1, 3))
b1_B = pd.Series((-1, -3))
a2 = pd.Series((3, 4))
b2_A = pd.Series((2, 3))
b2_B = pd.Series((-2, -3))
w1 = pd.Series((1, 1))
w2 = w1
r1 = asmd(
pd.DataFrame({"a": a1, "b[A]": b1_A, "b[B]": b1_B}),
pd.DataFrame({"a": a2, "b[A]": b2_A, "b[B]": b2_B}),
w1,
w2,
).to_list()
r2 = asmd(
pd.DataFrame({"a": a1, "b[A]": b1_A, "b[B]": b1_B}),
pd.DataFrame({"a": a2, "b[A]": b2_A, "b[B]": b2_B}),
w1,
w2,
"target",
True,
).to_list()
self.assertTrue(
all((np.round(r1, 5)) == np.array([2.82843, 0.70711, 0.70711, 1.76777]))
)
self.assertTrue(all((np.round(r2, 5)) == np.array([2.82843, 0.70711, 1.76777])))
def test__aggregate_asmd_by_main_covar(self):
from balance.stats_and_plots.weighted_comparisons_stats import (
_aggregate_asmd_by_main_covar,
)
# toy example
asmd_series = pd.Series(
{
"age": 0.5,
"education[T.high_school]": 1,
"education[T. bachelor]": 2,
"education[T. masters]": 3,
"education[T. phd]": 4,
}
)
outcome = _aggregate_asmd_by_main_covar(asmd_series).to_dict()
expected = {"age": 0.5, "education": 2.5}
self.assertEqual(outcome, expected)
def test_asmd_improvement(self):
from balance.stats_and_plots.weighted_comparisons_stats import asmd_improvement
r = asmd_improvement(
pd.DataFrame({"a": (5, 6, 7, 8)}),
pd.DataFrame({"a": (5, 6, 7, 8)}),
pd.DataFrame({"a": (1, 2, 3, 4)}),
pd.Series((1, 1, 1, 1)),
pd.Series((2, 2, 2, 2)),
pd.Series((1, 1, 1, 1)),
)
self.assertEqual(r, 0)
self.assertEqual(type(r), np.float64)
r = asmd_improvement(
pd.DataFrame({"a": (5, 6, 7, 8)}),
pd.DataFrame({"a": (1, 2, 3, 4)}),
pd.DataFrame({"a": (1, 2, 3, 4)}),
pd.Series((1, 1, 1, 1)),
pd.Series((1, 1, 1, 1)),
pd.Series((1, 1, 1, 1)),
)
self.assertEqual(r, 1)
self.assertEqual(type(r), np.float64)
r = asmd_improvement(
pd.DataFrame({"a": (3, 4)}),
pd.DataFrame({"a": (2, 3)}),
pd.DataFrame({"a": (1, 2)}),
pd.Series((1, 1)),
pd.Series((1, 1)),
pd.Series((1, 1)),
)
self.assertEqual(r, 0.5)
self.assertEqual(type(r), np.float64)
class TestBalance_general_stats(
balance.testutil.BalanceTestCase,
):
def test_relative_response_rates(self):
from balance.stats_and_plots.general_stats import relative_response_rates
df = pd.DataFrame(
{"o1": (7, 8, 9, 10), "o2": (7, 8, 9, np.nan), "id": (1, 2, 3, 4)}
)
self.assertEqual(
relative_response_rates(df).to_dict(),
{
"o1": {"n": 4.0, "%": 100.0},
"o2": {"n": 3.0, "%": 75.0},
"id": {"n": 4.0, "%": 100.0},
},
)
df_target = pd.concat([df, df])
self.assertEqual(
relative_response_rates(df, df_target).to_dict(),
{
"o1": {"n": 4.0, "%": 50.0},
"o2": {"n": 3.0, "%": 50.0},
"id": {"n": 4.0, "%": 50.0},
},
)
# verify behavior when per_column is set to False
self.assertEqual(
relative_response_rates(df, df_target, per_column=False).round(3).to_dict(),
{
"o1": {"n": 4.0, "%": 66.667},
"o2": {"n": 3.0, "%": 50.0},
"id": {"n": 4.0, "%": 66.667},
},
)
with self.assertRaisesRegex(
ValueError, "df and df_target must have the exact same columns*"
):
relative_response_rates(df, df_target.iloc[:, 0:1], per_column=True)
| balance-main | tests/test_stats_and_plots.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import balance.testutil
import numpy as np
import pandas as pd
from balance.sample_class import Sample
from balance.weighting_methods.poststratify import poststratify
class Testpoststratify(
balance.testutil.BalanceTestCase,
):
def test_poststratify(self):
s = pd.DataFrame(
{
"a": (0, 1, 0, 1),
"c": ("a", "a", "b", "b"),
},
)
s_weights = pd.Series([4, 2, 1, 1])
t = s
t_weights = pd.Series([4, 2, 2, 8])
result = poststratify(
sample_df=s, sample_weights=s_weights, target_df=t, target_weights=t_weights
)["weight"]
self.assertEqual(result, t_weights.astype("float64"))
# same example when dataframe of elements are all related to weights of one
s = pd.DataFrame(
{
"a": (0, 0, 0, 0, 1, 1, 0, 1),
"c": ("a", "a", "a", "a", "a", "a", "b", "b"),
},
)
s_weights = pd.Series([1, 1, 1, 1, 1, 1, 1, 1])
result = poststratify(
sample_df=s, sample_weights=s_weights, target_df=t, target_weights=t_weights
)["weight"]
self.assertEqual(result, pd.Series((1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 8.0)))
# same example with normalized weights
s = pd.DataFrame(
{
"a": (0, 1, 0, 1),
"c": ("a", "a", "b", "b"),
},
)
s_weights = pd.Series([1 / 2, 1 / 4, 1 / 8, 1 / 8])
result = poststratify(
sample_df=s, sample_weights=s_weights, target_df=t, target_weights=t_weights
)["weight"]
self.assertEqual(result, t_weights.astype("float64"))
# test through adjustment
# TODO: test the previous example through adjustment as well
sample = Sample.from_frame(
df=pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "x"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
target = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (-42, 8, 2),
"c": ("x", "y", "z"),
"id": (1, 2, 3),
"w": (2, 0.5, 1),
}
),
id_column="id",
weight_column="w",
)
result = sample.adjust(target, method="poststratify", transformations=None)
expected = pd.Series(
(
(2 / 1.5 * 0.5),
(0.5 / 2 * 2),
(1 / 1 * 1),
(2 / 1.5 * 1),
)
)
self.assertEqual(expected, result.weights().df.iloc[:, 0].values)
def test_poststratify_variables_arg(self):
s = pd.DataFrame(
{
"a": (0, 1, 0, 1),
"c": ("a", "a", "b", "b"),
},
)
s_weights = pd.Series([4, 2, 2, 3])
t = s
t_weights = pd.Series([4, 2, 2, 8])
result = poststratify(
sample_df=s,
sample_weights=s_weights,
target_df=t,
target_weights=t_weights,
variables=["a"],
)["weight"]
self.assertEqual(result, pd.Series([4.0, 4.0, 2.0, 6.0]))
def test_poststratify_transformations(self):
# for numeric
size = 10000
s = pd.DataFrame({"age": np.random.uniform(0, 1, size)})
tmp = int(size * 0.2)
t = pd.DataFrame(
{
"age": np.concatenate(
(
np.random.uniform(0, 0.4, tmp),
np.random.uniform(0.4, 1, size - tmp),
)
)
}
)
result = poststratify(
sample_df=s,
sample_weights=pd.Series([1] * size),
target_df=t,
target_weights=pd.Series([1] * size),
)["weight"]
# age>0.4 has 4 times as many people than age <0.4 in the target
# Check that the weights come out as 0.2 and 0.8
eps = 0.05
self.assertTrue(abs(result[s.age < 0.4].sum() / size - 0.2) < eps)
self.assertTrue(abs(result[s.age >= 0.4].sum() / size - 0.8) < eps)
# for strings
size = 10000
s = pd.DataFrame(
{"x": np.random.choice(("a", "b", "c"), size, p=(0.95, 0.035, 0.015))}
)
t = pd.DataFrame(
{"x": np.random.choice(("a", "b", "c"), size, p=(0.95, 0.015, 0.035))}
)
result = poststratify(
sample_df=s,
sample_weights=pd.Series([1] * size),
target_df=t,
target_weights=pd.Series([1] * size),
)["weight"]
# Output weights should ignore the difference between values 'b' and 'c'
# since these are combined in default transformations (into '_lumped_other').
# Hence their frequency would be as in sample
eps = 0.05
self.assertTrue(abs(result[s.x == "a"].sum() / size - 0.95) < eps)
self.assertTrue(abs(result[s.x == "b"].sum() / size - 0.035) < eps)
self.assertTrue(abs(result[s.x == "c"].sum() / size - 0.015) < eps)
def test_poststratify_exceptions(self):
# column with name weight
s = pd.DataFrame(
{
"weight": (0, 1, 0, 1),
"c": ("a", "a", "b", "b"),
},
)
s_weights = pd.Series([4, 2, 1, 1])
t = pd.DataFrame(
{
"a": (0, 1, 0, 1),
"c": ("a", "a", "b", "b"),
},
)
t_weights = pd.Series([4, 2, 2, 8])
with self.assertRaisesRegex(
ValueError,
"weight can't be a name of a column in sample or target when applying poststratify",
):
poststratify(s, s_weights, t, t_weights)
with self.assertRaisesRegex(
ValueError,
"weight can't be a name of a column in sample or target when applying poststratify",
):
poststratify(t, t_weights, s, s_weights)
# not all sample cells are in target
s = pd.DataFrame(
{
"a": ("x", "y"),
"b": (0, 1),
},
)
s_weights = pd.Series([1] * 2)
t = pd.DataFrame(
{
"a": ("x", "x", "y"),
"b": (0, 1, 0),
},
)
t_weights = pd.Series([2] * 3)
with self.assertRaisesRegex(
ValueError, "all combinations of cells in sample_df must be in target_df"
):
poststratify(s, s_weights, t, t_weights)
| balance-main | tests/test_poststratify.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import logging
from typing import Dict, List, Literal, Optional, Tuple, Union
import numpy as np
import pandas as pd
import plotly.graph_objs as go
from balance import util as balance_util
from balance.adjustment import trim_weights
from balance.sample_class import Sample
from balance.stats_and_plots import (
general_stats,
weighted_comparisons_plots,
weighted_comparisons_stats,
weighted_stats,
weights_stats,
)
from balance.typing import FilePathOrBuffer
from balance.util import find_items_index_in_list, get_items_from_list_via_indices
from IPython.lib.display import FileLink
logger: "logging.Logger" = logging.getLogger(__package__)
class BalanceDF:
"""
Wrapper class around a Sample which provides additional balance-specific functionality
"""
_model_matrix = None
def __init__(
self: "BalanceDF",
df: pd.DataFrame,
sample: Sample,
name: Literal["outcomes", "weights", "covars"],
) -> None:
"""A basic init method used by BalanceOutcomesDF,BalanceCovarsDF, and BalanceWeightsDF
Args:
self (BalanceDF): The object that is initiated.
df (pd.DataFrame): a df from a sample object.
sample (Sample): A sample object to be stored as reference.
name (Literal["outcomes", "weights", "covars"]): The type of object that will be created. In practice, used for "outcomes", "weights" and "covars".
"""
# NOTE: double underscore helps to add friction so that users do not change these objects.
# see details here: https://stackoverflow.com/a/1301369/256662
# TODO: when refactoring the object class model, re-evaluate if we want to keep such objects protected or not.
self.__sample = sample
self.__df = df
self.__name = name
def __str__(self: "BalanceDF") -> str:
name = self.__name
sample = object.__repr__(self._sample)
df = self.df.__repr__()
return f"{name} from {sample}:\n{df}"
def __repr__(self: "BalanceDF") -> str:
return (
f"({self.__class__.__module__}.{self.__class__.__qualname__})\n"
f"{self.__str__()}"
)
# Private API
@staticmethod
def _check_if_not_BalanceDF(
BalanceDF_class_obj: "BalanceDF", object_name: str = "sample_BalanceDF"
) -> None:
"""Check if an object is BalanceDF, if not then it raises ValueError
Args:
BalanceDF_class_obj (BalanceDF): Object to check.
object_name (str, optional): Object name (to use when raising the ValueError). Defaults to "sample_BalanceDF".
Returns: None.
Raises:
ValueError: if BalanceDF_class_obj is not BalanceDF object.
"""
if not isinstance(BalanceDF_class_obj, BalanceDF):
raise ValueError(
f"{object_name} must be balancedf_class.BalanceDF, is {type(BalanceDF_class_obj)}"
)
@property
def _sample(self: "BalanceDF") -> "Sample":
"""Access __sample internal object.
Args:
self (BalanceDF): Object
Returns:
Sample: __sample
"""
return self.__sample
@property
def _weights(
self: "BalanceDF",
) -> Optional[pd.DataFrame]:
"""Access the weight_column in __sample.
Args:
self (BalanceDF): Object
Returns:
Optional[pd.DataFrame]: The weights (with no column name)
"""
w = self._sample.weight_column
return w.rename(None)
# NOTE: only in the case of BalanceOutcomesDF can it result in a None value.
def _BalanceDF_child_from_linked_samples(
self: "BalanceDF",
) -> Dict[
str,
Union["BalanceCovarsDF", "BalanceWeightsDF", Union["BalanceOutcomesDF", None]],
]:
"""Returns a dict with self and the same type of BalanceDF_child when created from the linked samples.
For example, if this function is called from a BalanceCovarsDF (originally created using `Sample.covars()`),
that was invoked by a Sample with a target then the return dict will have the keys 'self' and 'target',
with the BalanceCovarsDF of the self and that of the target.
If the object has nothing but self, then it will be a dict with only one key:value pair (of self).
Args:
self (BalanceDF): Object (used in practice only with children of BalanceDF).
Returns:
Dict[str, Union["BalanceCovarsDF", "BalanceWeightsDF", Union["BalanceOutcomesDF", None]],]:
A dict mapping the link relationship to the result.
First item is self, and it just returns it without using method on it.
The other items are based on the objects in _links. E.g.: it can be 'target'
and 'unadjusted', and it will return them after running the same BalanceDF child creation method on them.
Examples:
::
from balance.sample_class import Sample
import pandas as pd
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
# keys depends on which samples are linked to the object:
list(s1.covars()._BalanceDF_child_from_linked_samples().keys()) # ['self']
list(s3.covars()._BalanceDF_child_from_linked_samples().keys()) # ['self', 'target']
list(s3_null.covars()._BalanceDF_child_from_linked_samples().keys()) # ['self', 'target', 'unadjusted']
# Indeed, all are of the same BalanceDF child type:
s3.covars()._BalanceDF_child_from_linked_samples()
# {'self': (balance.balancedf_class.BalanceCovarsDF)
# covars from <balance.sample_class.Sample object at 0x7f4392ea61c0>:
# a b c
# 0 1 -42 x
# 1 2 8 y
# 2 3 2 z
# 3 1 -42 v,
# 'target': (balance.balancedf_class.BalanceCovarsDF)
# covars from <balance.sample_class.Sample object at 0x7f43958fbd90>:
# a b c
# 0 1 4 x
# 1 2 6 y
# 2 3 8 z}
s3_null.covars()._BalanceDF_child_from_linked_samples()
# {'self': (balance.balancedf_class.BalanceCovarsDF)
# covars from <balance.sample_class.Sample object at 0x7f4392ea60d0>:
# a b c
# 0 1 -42 x
# 1 2 8 y
# 2 3 2 z
# 3 1 -42 v,
# 'target': (balance.balancedf_class.BalanceCovarsDF)
# covars from <balance.sample_class.Sample object at 0x7f43958fbd90>:
# a b c
# 0 1 4 x
# 1 2 6 y
# 2 3 8 z,
# 'unadjusted': (balance.balancedf_class.BalanceCovarsDF)
# covars from <balance.sample_class.Sample object at 0x7f4392ea61c0>:
# a b c
# 0 1 -42 x
# 1 2 8 y
# 2 3 2 z
# 3 1 -42 v}
the_dict = s3_null.covars()._BalanceDF_child_from_linked_samples()
[v.__class__ for (k,v) in the_dict.items()]
[balance.balancedf_class.BalanceCovarsDF,
balance.balancedf_class.BalanceCovarsDF,
balance.balancedf_class.BalanceCovarsDF]
# This also works for outcomes (returns None if there is none):
s3.outcomes()._BalanceDF_child_from_linked_samples()
# {'self': (balance.balancedf_class.BalanceOutcomesDF)
# outcomes from <balance.sample_class.Sample object at 0x7f4392ea61c0>:
# o
# 0 7
# 1 8
# 2 9
# 3 10,
# 'target': None}
# And also works for weights:
s3.weights()._BalanceDF_child_from_linked_samples()
# {'self': (balance.balancedf_class.BalanceWeightsDF)
# weights from <balance.sample_class.Sample object at 0x7f4392ea61c0>:
# w
# 0 0.5
# 1 2.0
# 2 1.0
# 3 1.0,
# 'target': (balance.balancedf_class.BalanceWeightsDF)
# weights from <balance.sample_class.Sample object at 0x7f43958fbd90>:
# w
# 0 0.5
# 1 1.0
# 2 2.0}
"""
# NOTE: this assumes that the .__name is the same as the creation method (i.e.: .covars(), .weights(), .outcomes())
BalanceDF_child_method = self.__name
d = {"self": self}
d.update(
{
k: getattr(v, BalanceDF_child_method)()
for k, v in self._sample._links.items()
}
)
return d # pyre-fixme[7]: this returns what's declared `Dict[str, Union[BalanceCovarsDF, BalanceOutcomesDF, BalanceWeightsDF]]` but got `Dict[str, BalanceDF]`
def _call_on_linked(
self: "BalanceDF",
method: str,
exclude: Union[Tuple[str], Tuple] = (),
*args,
**kwargs,
) -> pd.DataFrame:
"""Call a given method on the linked DFs of the BalanceDF object.
Returns the result as a pandas DataFrame where the source column
indicates where the result came from
Args:
self (BalanceDF): Object.
method (str): A name of a method to call (e.g.: "mean", "std", etc.).
Can also be a name of an attribute that is a DataFrame (e.g.: 'df')
exclude (Tuple[str], optional): A tuple of strings which indicates which source should be excluded from the output. Defaults to ().
E.g.: "self", "target".
Returns:
pd.DataFrame: A pandas DataFrame where the source column
indicates where the result came from. E.g.: 'self', 'target', 'unadjusted'.
And the columns are based on the method called. E.g.: using mean will give the
per column mean, after applying `model_matrix` to the df from each object.
Examples:
::
from balance.sample_class import Sample
import pandas as pd
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
print(s3.covars()._call_on_linked("mean").round(3))
# a b c[v] c[x] c[y] c[z]
# source
# self 1.889 -10.000 0.222 0.111 0.444 0.222
# target 2.429 6.857 NaN 0.143 0.286 0.571
print(s3.covars()._call_on_linked("df").round(3))
# a b c
# source
# self 1 -42 x
# self 2 8 y
# self 3 2 z
# self 1 -42 v
# target 1 4 x
# target 2 6 y
# target 3 8 z
"""
output = []
for k, v in self._BalanceDF_child_from_linked_samples().items():
if v is not None and k not in exclude:
v_att_method = getattr(v, method)
if callable(v_att_method):
v_att_method = v_att_method(
on_linked_samples=False, *args, **kwargs
)
output.append(v_att_method.assign(source=k).set_index("source"))
return pd.concat(output)
# return pd.concat(
# getattr(v, method)(on_linked_samples=False, *args, **kwargs)
# .assign(source=k)
# .set_index("source")
# if callable(getattr(v, method))
# else getattr(v, method)(on_linked_samples=False, *args, **kwargs)
# .assign(source=k)
# .set_index("source")
# for k, v in self._BalanceDF_child_from_linked_samples().items()
# if v is not None and k not in exclude
# )
# TODO: add the ability to pass formula argument to model_matrix
# but in which case - notice that we'd want the ability to track
# which object is stored in _model_matrix (and to run it over)
# Also, the output may sometimes no longer only be pd.DataFrame
# so such work will require update the type hinting here.
def model_matrix(self: "BalanceDF") -> pd.DataFrame:
"""Return a model_matrix version of the df inside the BalanceDF object using balance_util.model_matrix
This can be used to turn all character columns into a one hot encoding columns.
Args:
self (BalanceDF): Object
Returns:
pd.DataFrame: The output from :func:`balance_util.model_matrix`
Examples:
::
import pandas as pd
from balance.sample_class import Sample
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
print(s1.covars().df)
# a b c
# 0 1 -42 x
# 1 2 8 y
# 2 3 2 z
# 3 1 -42 v
print(s1.covars().model_matrix())
# a b c[v] c[x] c[y] c[z]
# 0 1.0 -42.0 0.0 1.0 0.0 0.0
# 1 2.0 8.0 0.0 0.0 1.0 0.0
# 2 3.0 2.0 0.0 0.0 0.0 1.0
# 3 1.0 -42.0 1.0 0.0 0.0 0.0
"""
if not hasattr(self, "_model_matrix") or self._model_matrix is None:
self._model_matrix = balance_util.model_matrix(
self.df, add_na=True, return_type="one"
)["model_matrix"]
return self._model_matrix
def _descriptive_stats(
self: "BalanceDF",
stat: Literal["mean", "std", "var_of_mean", "ci_of_mean", "..."] = "mean",
weighted: bool = True,
numeric_only: bool = False,
add_na: bool = True,
**kwargs,
) -> pd.DataFrame:
"""
Calls a given method from :func:`weighted_stats.descriptive_stats` on 'self'.
This function knows how to extract the df and the weights from a BalanceDF object.
Args:
self (BalanceDF): An object to run stats on.
stat (Literal["mean", "std", "var_of_mean", "ci_of_mean", "..."], optional): Defaults to "mean".
weighted (bool, optional): Defaults to True.
numeric_only (bool, optional): Defaults to False.
add_na (bool, optional): Defaults to True.
**kwargs: extra args to pass to descriptive_stats
Returns:
pd.DataFrame: Returns pd.DataFrame of the output (based on stat argument), for each of the columns in df.
"""
if numeric_only:
df = self.df.select_dtypes(include=[np.number])
else:
df = self.model_matrix()
weights = (
self._weights.values if (weighted and self._weights is not None) else None
)
wdf = weighted_stats.descriptive_stats(
df,
weights,
stat,
weighted=weighted,
# Using numeric_only=True since we know that df is screened in this function
# To only include numeric variables. So this saves descriptive_stats from
# running model_matrix again.
numeric_only=True,
add_na=add_na,
**kwargs,
)
return wdf
def to_download(self: "BalanceDF", tempdir: Optional[str] = None) -> FileLink:
"""Creates a downloadable link of the DataFrame, with ids, of the BalanceDF object.
File name starts with tmp_balance_out_, and some random file name (using :func:`uuid.uuid4`).
Args:
self (BalanceDF): Object.
tempdir (Optional[str], optional): Defaults to None (which then uses a temporary folder using :func:`tempfile.gettempdir`).
Returns:
FileLink: Embedding a local file link in an IPython session, based on path. Using :func:FileLink.
"""
return balance_util._to_download(self._df_with_ids(), tempdir)
# Public API
# All these functions operate on multiple samples
@property
def df(self: "BalanceDF") -> pd.DataFrame:
"""
Get the df of the BalanceDF object.
The df is stored in the BalanceDF.__df object, that is set during the __init__ of the object.
Args:
self (BalanceDF): The object.
Returns:
pd.DataFrame: The df (this is __df, with no weights) from the BalanceDF object.
"""
return self.__df
def names(self: "BalanceDF") -> List:
"""Returns the column names of the DataFrame (df) inside a BalanceDF object.
Args:
self (BalanceDF): The object.
Returns:
List: Of column names.
Examples:
::
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s1.covars().names()
# ['a', 'b', 'c']
s1.weights().names()
# ['w']
s1.outcomes().names()
# ['o']
"""
return list(self.df.columns.values)
def plot(
self: "BalanceDF", on_linked_samples: bool = True, **kwargs
) -> Union[Union[List, np.ndarray], Dict[str, go.Figure], None]:
"""Plots the variables in the df of the BalanceDF object.
See :func:`weighted_comparisons_plots.plot_dist` for details of various arguments that can be passed.
The default plotting engine is plotly, but seaborn can be used for static plots.
This function is inherited as is when invoking BalanceCovarsDF.plot, but some modifications are made when
preparing the data for BalanceOutcomesDF.plot and BalanceWeightsDF.plot.
Args:
self (BalanceDF): Object (used in the plots as "sample" or "self")
on_linked_samples (bool, optional): Determines if the linked samples should be included in the plot.
Defaults to True.
**kwargs: passed to :func:`weighted_comparisons_plots.plot_dist`.
Returns:
Union[Union[List, np.ndarray], Dict[str, go.Figure], None]:
If library="plotly" then returns a dictionary containing plots if return_dict_of_figures is True. None otherwise.
If library="seaborn" then returns None, unless return_axes is True. Then either a list or an np.array of matplotlib axis.
Examples:
::
import numpy as np
import pandas as pd
from numpy import random
from balance.sample_class import Sample
random.seed(96483)
df = pd.DataFrame({
"id": range(100),
'v1': random.random_integers(11111, 11114, size=100).astype(str),
'v2': random.normal(size = 100),
'v3': random.uniform(size = 100),
"w": pd.Series(np.ones(99).tolist() + [1000]),
}).sort_values(by=['v2'])
s1 = Sample.from_frame(df,
id_column="id",
weight_column="w",
)
s2 = Sample.from_frame(
df.assign(w = pd.Series(np.ones(100))),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
s3_null.set_weights(random.random(size = 100) + 0.5)
s3_null.covars().plot()
s3_null.covars().plot(library = "seaborn")
# Controlling the limits of the y axis using lim:
s3_null.covars().plot(ylim = (0,1))
s3_null.covars().plot(library = "seaborn",ylim = (0,1), dist_type = "hist")
# Returning plotly qq plots:
s3_null.covars().plot(dist_type = "qq")
"""
if on_linked_samples:
dfs_to_add = self._BalanceDF_child_from_linked_samples()
else:
dfs_to_add = {"self": self}
# Create a list of dicts, each dict representing a dataframe and weights
# Notice that we skip cases in which there is no data (i.e.: v is None)
# None values are skipped in both dfs and names
dfs = [
{"df": v.df, "weight": v._weights}
for k, v in dfs_to_add.items()
if (v is not None)
]
names = [k for k, v in dfs_to_add.items() if (v is not None)]
# re-order dfs and names
# NOTE: "target", if exists, is placed at the end of the dict so that comparative plotting functions,
indices_of_ordered_names = find_items_index_in_list(
names, ["unadjusted", "self", "adjusted", "target"]
)
dfs = get_items_from_list_via_indices(dfs, indices_of_ordered_names)
names = get_items_from_list_via_indices(names, indices_of_ordered_names)
return weighted_comparisons_plots.plot_dist(dfs, names=names, **kwargs)
# NOTE: The following functions use the _call_on_linked method
# to return information about the characteristics of linked Samples
def mean(
self: "BalanceDF", on_linked_samples: bool = True, **kwargs
) -> pd.DataFrame:
"""Calculates a weighted mean on the df of the BalanceDF object.
Args:
self (BalanceDF): Object.
on_linked_samples (bool, optional): Should the calculation be on self AND the linked samples objects? Defaults to True.
If True, then uses :func:`_call_on_linked` with method "mean".
If False, then uses :func:`_descriptive_stats` with method "mean".
Returns:
pd.DataFrame:
With row per object: self if on_linked_samples=False, and self and others (e.g.: target and unadjusted) if True.
Columns are for each of the columns in the relevant df (after applying :func:`model_matrix`)
Examples:
::
import pandas as pd
from balance.sample_class import Sample
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
print(s3_null.covars().mean())
# a b c[v] c[x] c[y] c[z]
# source
# self 1.888889 -10.000000 0.222222 0.111111 0.444444 0.222222
# target 2.428571 6.857143 NaN 0.142857 0.285714 0.571429
# unadjusted 1.888889 -10.000000 0.222222 0.111111 0.444444 0.222222
"""
if on_linked_samples:
return self._call_on_linked("mean", **kwargs)
else:
return self._descriptive_stats("mean", **kwargs)
def std(
self: "BalanceDF", on_linked_samples: bool = True, **kwargs
) -> pd.DataFrame:
"""Calculates a weighted std on the df of the BalanceDF object.
Args:
self (BalanceDF): Object.
on_linked_samples (bool, optional): Should the calculation be on self AND the linked samples objects? Defaults to True.
If True, then uses :func:`_call_on_linked` with method "std".
If False, then uses :func:`_descriptive_stats` with method "std".
Returns:
pd.DataFrame:
With row per object: self if on_linked_samples=False, and self and others (e.g.: target and unadjusted) if True.
Columns are for each of the columns in the relevant df (after applying :func:`model_matrix`)
Examples:
::
import pandas as pd
from balance.sample_class import Sample
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
print(s3_null.covars().std())
# a b c[v] c[x] c[y] c[z]
# source
# self 0.886405 27.354812 0.5 0.377964 0.597614 0.500000
# target 0.963624 1.927248 NaN 0.462910 0.597614 0.654654
# unadjusted 0.886405 27.354812 0.5 0.377964 0.597614 0.500000
"""
if on_linked_samples:
return self._call_on_linked("std", **kwargs)
else:
return self._descriptive_stats("std", **kwargs)
def var_of_mean(
self: "BalanceDF", on_linked_samples: bool = True, **kwargs
) -> pd.DataFrame:
"""Calculates a variance of the weighted mean on the df of the BalanceDF object.
Args:
self (BalanceDF): Object.
on_linked_samples (bool, optional): Should the calculation be on self AND the linked samples objects? Defaults to True.
If True, then uses :func:`_call_on_linked` with method "var_of_mean".
If False, then uses :func:`_descriptive_stats` with method "var_of_mean".
Returns:
pd.DataFrame:
With row per object: self if on_linked_samples=False, and self and others (e.g.: target and unadjusted) if True.
Columns are for each of the columns in the relevant df (after applying :func:`model_matrix`)
Examples:
::
import pandas as pd
from balance.sample_class import Sample
from balance.stats_and_plots.weighted_stats import var_of_weighted_mean
var_of_weighted_mean(pd.Series((1, 2, 3, 1)), pd.Series((0.5, 2, 1, 1)))
# 0 0.112178
# dtype: float64
# This shows we got the first cell of 'a' as expected.
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
print(s3_null.covars().var_of_mean())
# a b c[v] c[x] c[y] c[z]
# source
# self 0.112178 134.320988 0.042676 0.013413 0.082914 0.042676
# target 0.163265 0.653061 NaN 0.023324 0.069971 0.093294
# unadjusted 0.112178 134.320988 0.042676 0.013413 0.082914 0.042676
"""
if on_linked_samples:
return self._call_on_linked("var_of_mean", **kwargs)
else:
return self._descriptive_stats("var_of_mean", **kwargs)
def ci_of_mean(
self: "BalanceDF", on_linked_samples: bool = True, **kwargs
) -> pd.DataFrame:
"""Calculates a confidence intervals of the weighted mean on the df of the BalanceDF object.
Args:
self (BalanceDF): Object.
on_linked_samples (bool, optional): Should the calculation be on self AND the linked samples objects? Defaults to True.
If True, then uses :func:`_call_on_linked` with method "ci_of_mean".
If False, then uses :func:`_descriptive_stats` with method "ci_of_mean".
kwargs: we can pass ci_of_mean arguments. E.g.: conf_level and round_ndigits.
Returns:
pd.DataFrame:
With row per object: self if on_linked_samples=False, and self and others (e.g.: target and unadjusted) if True.
Columns are for each of the columns in the relevant df (after applying :func:`model_matrix`)
Examples:
::
import pandas as pd
from balance.sample_class import Sample
from balance.stats_and_plots.weighted_stats import ci_of_weighted_mean
ci_of_weighted_mean(pd.Series((1, 2, 3, 1)), pd.Series((0.5, 2, 1, 1)), round_ndigits = 3)
# 0 (1.232, 2.545)
# dtype: object
# This shows we got the first cell of 'a' as expected.
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
print(s3_null.covars().ci_of_mean(round_ndigits = 3).T)
# source self target unadjusted
# a (1.232, 2.545) (1.637, 3.221) (1.232, 2.545)
# b (-32.715, 12.715) (5.273, 8.441) (-32.715, 12.715)
# c[v] (-0.183, 0.627) NaN (-0.183, 0.627)
# c[x] (-0.116, 0.338) (-0.156, 0.442) (-0.116, 0.338)
# c[y] (-0.12, 1.009) (-0.233, 0.804) (-0.12, 1.009)
# c[z] (-0.183, 0.627) (-0.027, 1.17) (-0.183, 0.627)
s3_2 = s1.set_target(s2)
s3_null_2 = s3_2.adjust(method="null")
print(s3_null_2.outcomes().ci_of_mean(round_ndigits = 3))
# o
# source
# self (7.671, 9.44)
# unadjusted (7.671, 9.44)
"""
if on_linked_samples:
return self._call_on_linked("ci_of_mean", **kwargs)
else:
return self._descriptive_stats("ci_of_mean", **kwargs)
def mean_with_ci(
self: "BalanceDF", round_ndigits: int = 3, on_linked_samples: bool = True
) -> pd.DataFrame:
"""
Returns a table with means and confidence intervals (CIs) for all elements in the BalanceDF object.
This method calculates the mean and CI for each column of the BalanceDF object using the BalanceDF.mean()
and BalanceDF.ci_of_mean() methods, respectively. The resulting table contains (for each element such as self, target and adjust) two columns for each input
column: one for the mean and one for the CI.
Args:
self (BalanceDF): The BalanceDF object.
round_ndigits (int, optional): The number of decimal places to round the mean and CI to.
Defaults to 3.
on_linked_samples (bool, optional): A boolean indicating whether to include linked samples
when calculating the mean. Defaults to True.
Returns:
pd.DataFrame: A table with two rows for each input column: one for the mean and one for the CI.
The columns of the table are labeled with the names of the input columns.
Examples:
::
import numpy as np
import pandas as pd
from balance.sample_class import Sample
s_o = Sample.from_frame(
pd.DataFrame({"o1": (7, 8, 9, 10), "o2": (7, 8, 9, np.nan), "id": (1, 2, 3, 4)}),
id_column="id",
outcome_columns=("o1", "o2"),
)
t_o = Sample.from_frame(
pd.DataFrame(
{
"o1": (7, 8, 9, 10, 11, 12, 13, 14),
"o2": (7, 8, 9, np.nan, np.nan, 12, 13, 14),
"id": (1, 2, 3, 4, 5, 6, 7, 8),
}
),
id_column="id",
outcome_columns=("o1", "o2"),
)
s_o2 = s_o.set_target(t_o)
print(s_o2.outcomes().mean_with_ci())
# source self target self target
# _is_na_o2[False] 0.75 0.750 (0.326, 1.174) (0.45, 1.05)
# _is_na_o2[True] 0.25 0.250 (-0.174, 0.674) (-0.05, 0.55)
# o1 8.50 10.500 (7.404, 9.596) (8.912, 12.088)
# o2 6.00 7.875 (2.535, 9.465) (4.351, 11.399)
"""
the_means = (
self.mean(on_linked_samples=on_linked_samples).round(round_ndigits).T
)
the_cis = self.ci_of_mean(
on_linked_samples=on_linked_samples, round_ndigits=round_ndigits
).T
the_cis.columns = the_cis.columns.astype(str) + "_ci"
return pd.concat([the_means, the_cis], axis=1)
# NOTE: Summary could return also an str in case it is overridden in other children's methods.
def summary(
self: "BalanceDF", on_linked_samples: bool = True
) -> Union[pd.DataFrame, str]:
"""
Returns a summary of the BalanceDF object.
This method currently calculates the mean and confidence interval (CI) for each column of the object
using the :func:`BalanceDF.mean_with_ci()` method. In the future, this method may be extended to include additional
summary statistics.
Args:
self (BalanceDF): The BalanceDF object.
on_linked_samples (bool, optional): A boolean indicating whether to include linked samples
when calculating the mean and CI. Defaults to True.
Returns:
Union[pd.DataFrame, str]: A table with two rows for each input column: one for the mean and one for the CI.
The columns of the table are labeled with the names of the input columns.
"""
# TODO model matrix means to include categorical columns, fix model_matrix to accept DataFrame
# TODO: include min/max/std/etc. show min/mean/max if there's a single column, just means if multiple (covars and outcomes)
# Doing so would either require to implement a min/max etc methods in BalanceDF and use them with _call_on_linked.
# Or, update _call_on_linked to deal with non functions, get 'df' from it, and apply the needed functions on it.
# TODO add outcome variance ratio
return self.mean_with_ci(on_linked_samples=on_linked_samples)
def _get_df_and_weights(
self: "BalanceDF",
) -> Tuple[pd.DataFrame, Optional[np.ndarray]]:
"""Extract covars df (after using model_matrix) and weights from a BalanceDF object.
Args:
self (BalanceDF): Object
Returns:
Tuple[pd.DataFrame, Optional[np.ndarray]]:
A pd.DataFrame output from running :func:`model_matrix`, and
A np.ndarray of weights from :func:`_weights`, or just None (if there are no weights).
"""
# get df values (like in BalanceDF._descriptive_stats)
df_model_matrix = self.model_matrix()
# get weights (like in BalanceDF._descriptive_stats)
weights = self._weights.values if (self._weights is not None) else None
return df_model_matrix, weights
@staticmethod
def _asmd_BalanceDF(
sample_BalanceDF: "BalanceDF",
target_BalanceDF: "BalanceDF",
aggregate_by_main_covar: bool = False,
) -> pd.Series:
"""Run asmd on two BalanceDF objects
Prepares the BalanceDF objects by passing them through :func:`_get_df_and_weights`, and
then pass the df and weights from the two objects into :func:`weighted_comparisons_stats.asmd`.
Note that this will works on the result of model_matrix (default behavior, no formula supplied),
which is different than just the raw covars. E.g.: in case there are nulls (will produce an indicator column of that),
as well as if there are categorical variables (transforming them using one hot encoding).
Args:
sample_df (BalanceDF): Object
target_df (BalanceDF): Object
aggregate_by_main_covar (bool, optional): See :func:`weighted_comparisons_stats.asmd`. Defaults to False.
Returns:
pd.Series: See :func:`weighted_comparisons_stats.asmd`
Examples:
::
from balance.balancedf_class import BalanceDF
BalanceDF._asmd_BalanceDF(
Sample.from_frame(
pd.DataFrame(
{"id": (1, 2), "a": (1, 2), "b": (-1, 12), "weight": (1, 2)}
)
).covars(),
Sample.from_frame(
pd.DataFrame(
{"id": (1, 2), "a": (3, 4), "b": (0, 42), "weight": (1, 2)}
)
).covars(),
)
# a 2.828427
# b 0.684659
# mean(asmd) 1.756543
# dtype: float64
"""
BalanceDF._check_if_not_BalanceDF(sample_BalanceDF, "sample_BalanceDF")
BalanceDF._check_if_not_BalanceDF(sample_BalanceDF, "target_BalanceDF")
sample_df_values, sample_weights = sample_BalanceDF._get_df_and_weights()
target_df_values, target_weights = target_BalanceDF._get_df_and_weights()
return weighted_comparisons_stats.asmd(
sample_df_values,
target_df_values,
sample_weights,
target_weights,
std_type="target",
aggregate_by_main_covar=aggregate_by_main_covar,
)
def asmd(
self: "BalanceDF",
on_linked_samples: bool = True,
target: Optional["BalanceDF"] = None,
aggregate_by_main_covar: bool = False,
**kwargs,
) -> pd.DataFrame:
"""ASMD is the absolute difference of the means of two groups (say, P and T), divided by some standard deviation (std).
It can be std of P or of T, or of P and T.
These are all variations on the absolute value of cohen's d (see: https://en.wikipedia.org/wiki/Effect_size#Cohen's_d).
We can use asmd to compares multiple Samples (with and without adjustment) to a target population.
Args:
self (BalanceDF): Object from sample (with/without adjustment, but it needs some target)
on_linked_samples (bool, optional): If to compare also to linked sample objects (specifically: unadjusted), or not. Defaults to True.
target (Optional["BalanceDF"], optional): A BalanceDF (of the same type as the one used in self) to compare against.
If None then it looks for a target in the self linked objects. Defaults to None.
aggregate_by_main_covar (bool, optional): Defaults to False.
If True, it will make sure to return the asmd DataFrame after averaging
all the columns from using the one-hot encoding for categorical variables.
See ::_aggregate_asmd_by_main_covar:: for more details.
Raises:
ValueError:
If self has no target and no target is supplied.
Returns:
pd.DataFrame:
If on_linked_samples is False, then only one row (index name depends on BalanceDF type, e.g.: covars), with asmd of self vs the target (depending if it's covars, or something else).
If on_linked_samples is True, then two rows per source (self, unadjusted), each with the asmd compared to target, and a third row for the difference (self-unadjusted).
Examples:
::
import pandas as pd
from balance.sample_class import Sample
from copy import deepcopy
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
s3_null_madeup_weights = deepcopy(s3_null)
s3_null_madeup_weights.set_weights((1, 2, 3, 1))
print(s3_null.covars().asmd().round(3))
# a b c[v] c[x] c[y] c[z] mean(asmd)
# source
# self 0.56 8.747 NaN 0.069 0.266 0.533 3.175
# unadjusted 0.56 8.747 NaN 0.069 0.266 0.533 3.175
# unadjusted - self 0.00 0.000 NaN 0.000 0.000 0.000 0.000
# show that on_linked_samples = False works:
print(s3_null.covars().asmd(on_linked_samples = False).round(3))
# a b c[v] c[x] c[y] c[z] mean(asmd)
# index
# covars 0.56 8.747 NaN 0.069 0.266 0.533 3.175
# verify this also works when we have some weights
print(s3_null_madeup_weights.covars().asmd())
# a b c[v] ... c[y] c[z] mean(asmd)
# source ...
# self 0.296500 8.153742 NaN ... 0.000000 0.218218 2.834932
# unadjusted 0.560055 8.746742 NaN ... 0.265606 0.533422 3.174566
# unadjusted - self 0.263555 0.592999 NaN ... 0.265606 0.315204 0.33963
"""
target_from_self = self._BalanceDF_child_from_linked_samples().get("target")
if target is None:
target = target_from_self
if target is None:
raise ValueError(
f"Sample {object.__str__(self._sample)} has no target set, or target has no {self.__name} to compare against."
)
elif on_linked_samples:
return balance_util.row_pairwise_diffs(
self._call_on_linked(
"asmd",
exclude=("target",),
target=target,
aggregate_by_main_covar=aggregate_by_main_covar,
**kwargs,
)
)
else:
out = (
pd.DataFrame(
self._asmd_BalanceDF(self, target, aggregate_by_main_covar)
)
.transpose()
.assign(index=(self.__name,))
.set_index("index")
)
return out
def asmd_improvement(
self: "BalanceDF",
unadjusted: Optional["BalanceDF"] = None,
target: Optional["BalanceDF"] = None,
) -> np.float64:
"""Calculates the improvement in mean(asmd) from before to after applying some weight adjustment.
See :func:`weighted_comparisons_stats.asmd_improvement` for details.
Args:
self (BalanceDF): BalanceDF (e.g.: of self after adjustment)
unadjusted (Optional["BalanceDF"], optional): BalanceDF (e.g.: of self before adjustment). Defaults to None.
target (Optional["BalanceDF"], optional): To compare against. Defaults to None.
Raises:
ValueError: If target is not linked in self and also not provided to the function.
ValueError: If unadjusted is not linked in self and also not provided to the function.
Returns:
np.float64: The improvement is taking the (before_mean_asmd-after_mean_asmd)/before_mean_asmd.
The asmd is calculated using :func:`asmd`.
Examples:
::
import pandas as pd
from balance.sample_class import Sample
from copy import deepcopy
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
s2 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3),
"b": (4, 6, 8),
"id": (1, 2, 3),
"w": (0.5, 1, 2),
"c": ("x", "y", "z"),
}
),
id_column="id",
weight_column="w",
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
s3_null_madeup_weights = deepcopy(s3_null)
s3_null_madeup_weights.set_weights((1, 2, 3, 1))
s3_null.covars().asmd_improvement() # 0. since unadjusted is just a copy of self
s3_null_madeup_weights.covars().asmd_improvement() # 0.10698596233975825
asmd_df = s3_null_madeup_weights.covars().asmd()
print(asmd_df["mean(asmd)"])
# source
# self 2.834932
# unadjusted 3.174566
# unadjusted - self 0.339634
# Name: mean(asmd), dtype: float64
(asmd_df["mean(asmd)"][1] - asmd_df["mean(asmd)"][0]) / asmd_df["mean(asmd)"][1] # 0.10698596233975825
# just like asmd_improvement
"""
if unadjusted is None:
unadjusted = self._BalanceDF_child_from_linked_samples().get("unadjusted")
if unadjusted is None:
raise ValueError(
f"Sample {object.__repr__(self._sample)} has no unadjusted set or unadjusted has no {self.__name}."
)
if target is None:
target = self._BalanceDF_child_from_linked_samples().get("target")
if target is None:
raise ValueError(
f"Sample {object.__repr__(self._sample)} has no target set or target has no {self.__name}."
)
sample_before_df, sample_before_weights = unadjusted._get_df_and_weights()
sample_after_df, sample_after_weights = self._get_df_and_weights()
target_df, target_weights = target._get_df_and_weights()
return weighted_comparisons_stats.asmd_improvement(
sample_before=sample_before_df,
sample_after=sample_after_df,
target=target_df,
sample_before_weights=sample_before_weights,
sample_after_weights=sample_after_weights,
target_weights=target_weights,
)
# TODO: implement the following methods (probably first in balance.stats_and_plots.weighted_comparisons_stats)
# def emd(self):
# return NotImplementedError()
# def cvmd(self):
# return NotImplementedError()
# def ks(self):
# return NotImplementedError()
def _df_with_ids(self: "BalanceDF") -> pd.DataFrame:
"""Creates a DataFrame of the BalanceDF, with ids.
Args:
self (BalanceDF): Object.
Returns:
pd.DataFrame: DataFrame with id_column and then the df.
"""
return pd.concat((self._sample.id_column, self.df), axis=1)
def to_csv(
self: "BalanceDF",
path_or_buf: Optional[FilePathOrBuffer] = None,
*args,
**kwargs,
) -> Optional[str]:
"""Write df with ids from BalanceDF to a comma-separated values (csv) file.
Uses :func:`pd.DataFrame.to_csv`.
If an 'index' argument is not provided then it defaults to False.
Args:
self (BalanceDF): Object.
path_or_buf (Optional[FilePathOrBuffer], optional): location where to save the csv.
Returns:
Optional[str]: If path_or_buf is None, returns the resulting csv format as a string. Otherwise returns None.
"""
if "index" not in kwargs:
kwargs["index"] = False
return self._df_with_ids().to_csv(path_or_buf=path_or_buf, *args, **kwargs)
class BalanceOutcomesDF(BalanceDF):
def __init__(self: "BalanceOutcomesDF", sample: Sample) -> None:
"""A factory function to create BalanceOutcomesDF
This is used through :func:`Sample.outcomes`.
It initiates a BalanceOutcomesDF object by passing the relevant arguments to
:func:`BalanceDF.__init__`.
Args:
self (BalanceOutcomesDF): Object that is initiated.
sample (Sample): Object
"""
super().__init__(sample._outcome_columns, sample, name="outcomes")
# TODO: add the `relative_to` argument (with options 'self' and 'target')
# this will also require to update _relative_response_rates a bit.
def relative_response_rates(
self: "BalanceOutcomesDF",
target: Union[bool, pd.DataFrame] = False,
per_column: bool = False,
) -> Optional[pd.DataFrame]:
"""Produces a summary table of number of responses and proportion of completed responses.
See :func:`general_stats.relative_response_rates`.
Args:
self (BalanceOutcomesDF): Object
target (Union[bool, pd.DataFrame], optional): Defaults to False.
Determines what is passed to df_target in :func:`general_stats.relative_response_rates`
If False: passes None.
If True: passes the df from the target of sample (notice, it's the df of target, NOT target.outcome().df).
So it means it will count only rows that are all notnull rows (so if the target has covars and outcomes,
both will need to be notnull to be counted).
If you want to control this in a more specific way, pass pd.DataFrame instead.
If pd.DataFrame: passes it as is.
per_column (bool, optional): Default is False. See :func:`general_stats.relative_response_rates`.
Returns:
Optional[pd.DataFrame]: A column per outcome, and two rows.
One row with number of non-null observations, and
A second row with the proportion of non-null observations.
If 'target' is set to True but there is no target, the function returns None.
Examples:
::
import numpy as np
import pandas as pd
from balance.sample_class import Sample
s_o = Sample.from_frame(
pd.DataFrame({"o1": (7, 8, 9, 10), "o2": (7, 8, 9, np.nan), "id": (1, 2, 3, 4)}),
id_column="id",
outcome_columns=("o1", "o2"),
)
print(s_o.outcomes().relative_response_rates())
# o1 o2
# n 4.0 3.0
# % 100.0 75.0
s_o.outcomes().relative_response_rates(target = True)
# None
# compared with a larger target
t_o = Sample.from_frame(
pd.DataFrame(
{
"o1": (7, 8, 9, 10, 11, 12, 13, 14),
"o2": (7, 8, 9, np.nan, np.nan, 12, 13, 14),
"id": (1, 2, 3, 4, 5, 6, 7, 8),
}
),
id_column="id",
outcome_columns=("o1", "o2"),
)
s_o2 = s_o.set_target(t_o)
print(s_o2.outcomes().relative_response_rates(True, per_column = True))
# o1 o2
# n 4.0 3.0
# % 50.0 50.0
df_target = pd.DataFrame(
{
"o1": (7, 8, 9, 10, 11, 12, 13, 14),
"o2": (7, 8, 9, np.nan, np.nan, 12, 13, 14),
}
)
print(s_o2.outcomes().relative_response_rates(target = df_target, per_column = True))
# o1 o2
# n 4.0 3.0
# % 50.0 50.0
"""
if type(target) is bool:
# Then: get target from self:
if target:
self_target = self._BalanceDF_child_from_linked_samples().get("target")
if self_target is None:
logger.warning("Sample does not have target set")
return None
else:
df_target = self_target.df
else:
df_target = None
else:
df_target = target
return general_stats.relative_response_rates(
self.df, df_target, per_column=per_column
)
def target_response_rates(self: "BalanceOutcomesDF") -> Optional[pd.DataFrame]:
"""Calculates relative_response_rates for the target in a Sample object.
See :func:`general_stats.relative_response_rates`.
Args:
self (BalanceOutcomesDF): Object (with/without a target set)
Returns:
Optional[pd.DataFrame]: None if the object doesn't have a target.
If the object has a target, it returns the output of :func:`general_stats.relative_response_rates`.
Examples:
::
import numpy as np
import pandas as pd
from balance.sample_class import Sample
s_o = Sample.from_frame(
pd.DataFrame({"o1": (7, 8, 9, 10), "o2": (7, 8, 9, np.nan), "id": (1, 2, 3, 4)}),
id_column="id",
outcome_columns=("o1", "o2"),
)
t_o = Sample.from_frame(
pd.DataFrame(
{
"o1": (7, 8, 9, 10, 11, 12, 13, 14),
"o2": (7, 8, 9, np.nan, 11, 12, 13, 14),
"id": (1, 2, 3, 4, 5, 6, 7, 8),
}
),
id_column="id",
outcome_columns=("o1", "o2"),
)
s_o = s_o.set_target(t_o)
print(s_o.outcomes().target_response_rates())
# o1 o2
# n 8.0 7.0
# % 100.0 87.5
"""
self_target = self._BalanceDF_child_from_linked_samples().get("target")
if self_target is None:
logger.warning("Sample does not have target set")
return None
else:
return general_stats.relative_response_rates(self_target.df)
# TODO: it's a question if summary should produce a printable output or a DataFrame.
# The BalanceDF.summary method only returns a DataFrame. So it's a question
# what is the best way to structure this more generally.
def summary(
self: "BalanceOutcomesDF", on_linked_samples: Optional[bool] = None
) -> str:
"""Produces summary printable string of a BalanceOutcomesDF object.
Args:
self (BalanceOutcomesDF): Object.
on_linked_samples (Optional[bool]): Ignored. Only here since summary overrides BalanceDF.summary.
Returns:
str: A printable string, with mean of outcome variables and response rates.
Examples:
::
import numpy as np
import pandas as pd
from balance.sample_class import Sample
s_o = Sample.from_frame(
pd.DataFrame({"o1": (7, 8, 9, 10), "o2": (7, 8, 9, np.nan), "id": (1, 2, 3, 4)}),
id_column="id",
outcome_columns=("o1", "o2"),
)
t_o = Sample.from_frame(
pd.DataFrame(
{
"o1": (7, 8, 9, 10, 11, 12, 13, 14),
"o2": (7, 8, 9, np.nan, np.nan, 12, 13, 14),
"id": (1, 2, 3, 4, 5, 6, 7, 8),
}
),
id_column="id",
outcome_columns=("o1", "o2"),
)
s_o2 = s_o.set_target(t_o)
print(s_o.outcomes().summary())
# 2 outcomes: ['o1' 'o2']
# Mean outcomes (with 95% confidence intervals):
# source self self
# _is_na_o2[False] 0.75 (0.326, 1.174)
# _is_na_o2[True] 0.25 (-0.174, 0.674)
# o1 8.50 (7.404, 9.596)
# o2 6.00 (2.535, 9.465)
# Response rates (relative to number of respondents in sample):
# o1 o2
# n 4.0 3.0
# % 100.0 75.0
print(s_o2.outcomes().summary())
# 2 outcomes: ['o1' 'o2']
# Mean outcomes (with 95% confidence intervals):
# source self target self target
# _is_na_o2[False] 0.75 0.750 (0.326, 1.174) (0.45, 1.05)
# _is_na_o2[True] 0.25 0.250 (-0.174, 0.674) (-0.05, 0.55)
# o1 8.50 10.500 (7.404, 9.596) (8.912, 12.088)
# o2 6.00 7.875 (2.535, 9.465) (4.351, 11.399)
# Response rates (relative to number of respondents in sample):
# o1 o2
# n 4.0 3.0
# % 100.0 75.0
# Response rates (relative to notnull rows in the target):
# o1 o2
# n 4.000000 3.0
# % 66.666667 50.0
# Response rates (in the target):
# o1 o2
# n 8.0 6.0
# % 100.0 75.0
"""
mean_outcomes_with_ci = self.mean_with_ci()
relative_response_rates = self.relative_response_rates()
target_response_rates = self.target_response_rates()
if target_response_rates is None:
target_clause = ""
relative_to_target_clause = ""
else:
relative_to_target_response_rates = self.relative_response_rates(
target=True, per_column=False
)
relative_to_target_clause = f"Response rates (relative to notnull rows in the target):\n {relative_to_target_response_rates}"
target_clause = f"Response rates (in the target):\n {target_response_rates}"
n_outcomes = self.df.shape[1]
list_outcomes = self.df.columns.values
mean_outcomes_with_ci = mean_outcomes_with_ci
relative_response_rates = relative_response_rates
target_clause = target_clause
out = (
f"{n_outcomes} outcomes: {list_outcomes}\n"
f"Mean outcomes (with 95% confidence intervals):\n"
# TODO: in the future consider if to add an argument to transpose (.T) the output, in case there are multiple outcomes.
f"{mean_outcomes_with_ci.to_string(max_cols=None)}\n\n"
"Response rates (relative to number of respondents in sample):\n"
f"{relative_response_rates}\n"
f"{relative_to_target_clause}\n"
f"{target_clause}\n"
)
return out
class BalanceCovarsDF(BalanceDF):
def __init__(self: "BalanceCovarsDF", sample: Sample) -> None:
"""A factory function to create BalanceCovarsDF
This is used through :func:`Sample.covars`.
It initiates a BalanceCovarsDF object by passing the relevant arguments to
:func:`BalanceDF.__init__`.
Args:
self (BalanceCovarsDF): Object that is initiated.
sample (Sample): Object
"""
super().__init__(sample._covar_columns(), sample, name="covars")
def from_frame(
self: "BalanceCovarsDF",
df: pd.DataFrame,
weights=Optional[pd.Series],
) -> "BalanceCovarsDF":
"""A factory function to create a BalanceCovarsDF from a df.
Although generally the main way the object is created is through the __init__ method.
Args:
self (BalanceCovarsDF): Object
df (pd.DataFrame): A df.
weights (Optional[pd.Series], optional): _description_. Defaults to None.
Returns:
BalanceCovarsDF: Object.
"""
df = df.reset_index()
df = pd.concat(
(df, pd.Series(np.arange(0, df.shape[0]), name="id"), weights), axis=1
)
return Sample.from_frame(df, id_column="id").covars()
class BalanceWeightsDF(BalanceDF):
def __init__(self: "BalanceWeightsDF", sample: Sample) -> None:
"""A factory function to create BalanceWeightsDF
This is used through :func:`Sample.weights`.
It initiates a BalanceWeightsDF object by passing the relevant arguments to
:func:`BalanceDF.__init__`.
Args:
self (BalanceWeightsDF): Object that is initiated.
sample (Sample): Object
"""
super().__init__(sample.weight_column.to_frame(), sample, name="weights")
# TODO: maybe add better control if there are no weights for unadjusted or target (the current default shows them in the legend, but not in the figure)
def plot(
self: "BalanceWeightsDF", on_linked_samples: bool = True, **kwargs
) -> Union[Union[List, np.ndarray], Dict[str, go.Figure], None]:
"""Plots kde (kernal density estimation) of the weights in a BalanceWeightsDF object using seaborn (as default).
It's possible to use other plots using dist_type with arguments such as "hist", "kde" (default), "qq", and "ecdf".
Look at :func:`plot_dist` for more details.
Args:
self (BalanceWeightsDF): a BalanceOutcomesDF object, with a set of variables.
on_linked_samples (bool, optional): Determines if the linked samples should be included in the plot.
Defaults to True.
Returns:
Union[Union[List, np.ndarray], Dict[str, go.Figure], None]:
If library="plotly" then returns a dictionary containing plots if return_dict_of_figures is True. None otherwise.
If library="seaborn" then returns None, unless return_axes is True. Then either a list or an np.array of matplotlib axis.
Examples:
::
import numpy as np
import pandas as pd
from numpy import random
from balance.sample_class import Sample
random.seed(96483)
df = pd.DataFrame({
"id": range(100),
'v1': random.random_integers(11111, 11114, size=100).astype(str),
'v2': random.normal(size = 100),
'v3': random.uniform(size = 100),
"w": pd.Series(np.ones(99).tolist() + [1000]),
}).sort_values(by=['v2'])
s1 = Sample.from_frame(df,
id_column="id",
weight_column="w",
outcome_columns=["v1", "v2"],
)
s2 = Sample.from_frame(
df.assign(w = pd.Series(np.ones(100))),
id_column="id",
weight_column="w",
outcome_columns=["v1", "v2"],
)
s3 = s1.set_target(s2)
s3_null = s3.adjust(method="null")
s3_null.set_weights(random.random(size = 100) + 0.5)
# default: seaborn with dist_type = "kde"
s3_null.weights().plot()
"""
default_kwargs = {
"weighted": False,
"library": "seaborn",
"dist_type": "kde",
"numeric_n_values_threshold": -1,
}
default_kwargs.update(kwargs)
return super().plot(on_linked_samples=on_linked_samples, **default_kwargs)
def design_effect(self: "BalanceWeightsDF") -> np.float64:
"""Calculates Kish's design effect (deff) on the BalanceWeightsDF weights.
Extract the first column to get a pd.Series of the weights.
See :func:`weights_stats.design_effect` for details.
Args:
self (BalanceWeightsDF): Object.
Returns:
np.float64: Deff.
"""
return weights_stats.design_effect(self.df.iloc[:, 0])
# TODO: in the future, consider if this type of overriding is the best solution.
# to reconsider as part of a larger code refactoring.
@property
def _weights(self: "BalanceWeightsDF") -> None:
"""A BalanceWeightsDF has no weights (its df is that of the weights.)
Args:
self (BalanceWeightsDF): Object.
Returns:
NoneType: None.
"""
return None
def trim(
self: "BalanceWeightsDF",
ratio: Optional[Union[float, int]] = None,
percentile: Optional[float] = None,
keep_sum_of_weights: bool = True,
) -> None:
"""Trim weights in the sample object.
Uses :func:`adjustments.trim_weights` for the weights trimming.
Args:
self (BalanceWeightsDF): Object.
ratio (Optional[Union[float, int]], optional): Maps to weight_trimming_mean_ratio. Defaults to None.
percentile (Optional[float], optional): Maps to weight_trimming_percentile. Defaults to None.
keep_sum_of_weights (bool, optional): Maps to weight_trimming_percentile. Defaults to True.
Returns:
None. This function updates the :func:`_sample` using :func:`set_weights`
"""
# TODO: verify which object exactly gets updated - and explain it here.
self._sample.set_weights(
trim_weights(
self.df.iloc[:, 0],
weight_trimming_mean_ratio=ratio,
weight_trimming_percentile=percentile,
keep_sum_of_weights=keep_sum_of_weights,
)
)
def summary(
self: "BalanceWeightsDF", on_linked_samples: Optional[bool] = None
) -> pd.DataFrame:
"""
Generates a summary of a BalanceWeightsDF object.
This function provides a comprehensive overview of the BalanceWeightsDF object
by calculating and returning a range of weight diagnostics.
Args:
self (BalanceWeightsDF): The BalanceWeightsDF object to be summarized.
on_linked_samples (Optional[bool], optional): This parameter is ignored. It is only included
because summary overrides BalanceDF.summary. Defaults to None.
Returns:
pd.DataFrame: A DataFrame containing various weight diagnostics such as 'design_effect',
'effective_sample_proportion', 'effective_sample_size', sum of weights, and basic summary statistics
from describe, 'nonparametric_skew', and 'weighted_median_breakdown_point' among others.
Note:
The weights are normalized to sum to the sample size, n.
Examples:
::
import pandas as pd
from balance.sample_class import Sample
s1 = Sample.from_frame(
pd.DataFrame(
{
"a": (1, 2, 3, 1),
"b": (-42, 8, 2, -42),
"o": (7, 8, 9, 10),
"c": ("x", "y", "z", "v"),
"id": (1, 2, 3, 4),
"w": (0.5, 2, 1, 1),
}
),
id_column="id",
weight_column="w",
outcome_columns="o",
)
print(s1.weights().summary().round(2))
# var val
# 0 design_effect 1.23
# 1 effective_sample_proportion 0.81
# 2 effective_sample_size 3.24
# 3 sum 4.50
# 4 describe_count 4.00
# 5 describe_mean 1.00
# 6 describe_std 0.56
# 7 describe_min 0.44
# 8 describe_25% 0.78
# 9 describe_50% 0.89
# 10 describe_75% 1.11
# 11 describe_max 1.78
# 12 prop(w < 0.1) 0.00
# 13 prop(w < 0.2) 0.00
# 14 prop(w < 0.333) 0.00
# 15 prop(w < 0.5) 0.25
# 16 prop(w < 1) 0.75
# 17 prop(w >= 1) 0.25
# 18 prop(w >= 2) 0.00
# 19 prop(w >= 3) 0.00
# 20 prop(w >= 5) 0.00
# 21 prop(w >= 10) 0.00
# 22 nonparametric_skew 0.20
# 23 weighted_median_breakdown_point 0.25
"""
# ----------------------------------------------------
# Diagnostics on the weights
# ----------------------------------------------------
the_weights = self.df.iloc[
:, 0
] # should be ['weight'], but this is more robust in case a user uses other names
weights_diag_var = []
weights_diag_value = []
# adding design_effect and variations
the_weights_de = weights_stats.design_effect(the_weights)
weights_diag_var.extend(
["design_effect", "effective_sample_proportion", "effective_sample_size"]
)
weights_diag_value.extend(
[the_weights_de, 1 / the_weights_de, len(the_weights) / the_weights_de]
)
# adding sum of weights, and then normalizing them to n (sample size)
weights_diag_var.append("sum")
weights_diag_value.append(the_weights.sum())
the_weights = the_weights / the_weights.mean() # normalize weights to sum to n.
# adding basic summary statistics from describe:
tmp_describe = the_weights.describe()
weights_diag_var.extend(["describe_" + i for i in tmp_describe.index])
weights_diag_value.extend(tmp_describe.to_list())
# TODO: decide if we want more quantiles of the weights.
# adding prop_above_and_below
tmp_props = weights_stats.prop_above_and_below(the_weights)
weights_diag_var.extend(
tmp_props.index.to_list() # pyre-ignore[16]: existing defaults make sure this output is pd.Series with relevant methods.
)
weights_diag_value.extend(
tmp_props.to_list() # pyre-ignore[16]: existing defaults make sure this output is pd.Series with relevant methods.
)
# TODO: decide if we want more numbers (e.g.: 2/3 and 3/2)
# adding nonparametric_skew and weighted_median_breakdown_point
weights_diag_var.append("nonparametric_skew")
weights_diag_value.append(weights_stats.nonparametric_skew(the_weights))
weights_diag_var.append("weighted_median_breakdown_point")
weights_diag_value.append(
weights_stats.weighted_median_breakdown_point(the_weights)
)
return pd.DataFrame(
{
# "metric": "weights_diagnostics",
"var": weights_diag_var,
"val": weights_diag_value,
}
)
| balance-main | balance/balancedf_class.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import collections.abc
import copy
import logging
import tempfile
import uuid
import warnings
from functools import reduce
from itertools import combinations
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
from IPython.lib.display import FileLink
from pandas.api.types import is_bool_dtype, is_numeric_dtype
from patsy.contrasts import ContrastMatrix
from patsy.highlevel import dmatrix, ModelDesc
from scipy.sparse import csc_matrix, hstack
logger: logging.Logger = logging.getLogger(__package__)
# TODO: split util and adjustment files into separate files: transformations, model_matrix, others..
def _check_weighting_methods_input(
df: pd.DataFrame,
weights: pd.Series,
object_name: str,
) -> None:
"""
This is a helper function fo weighting methods functions.
It checks the inputs are of the correct type and shapes.
Args:
df (pd.DataFrame):
weights (pd.Series):
object_name (str):
Raises:
TypeError: if df is not a DataFrame
TypeError: if weights is not a pd.Series
ValueError: {object_name}_weights must be the same length as {object_name}_df
ValueError: {object_name}_df index must be the same as {object_name}_weights index
"""
if not isinstance(df, pd.DataFrame):
raise TypeError(f"{object_name}_df must be a pandas DataFrame, is {type(df)}")
if not isinstance(weights, pd.Series):
raise TypeError(
f"{object_name}_weights must be a pandas Series, is {type(weights)}"
)
if df.shape[0] != weights.shape[0]:
raise ValueError(
f"{object_name}_weights must be the same length as {object_name}_df: "
f"{df.shape[0]}, {weights.shape[0]}"
)
if not df.index.equals(weights.index):
raise ValueError(
f"{object_name}_df index must be the same as {object_name}_weights index"
)
# This is so to avoid various cyclic imports (since various files call sample_class, and then sample_class also calls these files)
# TODO: (p2) move away from this method once we restructure Sample and BalanceDF objects...
def _isinstance_sample(obj) -> bool:
try:
from balance import sample_class
except ImportError:
return False
return isinstance(obj, sample_class.Sample)
def guess_id_column(dataset: pd.DataFrame, column_name: Optional[str] = None):
"""
Guess the id column of a given dataset.
Possible values for guess: 'id'.
Args:
dataset (pd.DataFrame): dataset to guess id column
column_name (str, optional): Given id column name. Defaults to None,
which will guess the id column or raise exception.
Returns:
str: name of guessed id column
"""
# TODO: add a general argument for the user so they could set
# a list of possible userid column names instead of only "id".
# This should go as an input into Sample.from_frame as well.
columns = list(dataset.columns)
if column_name is not None:
if column_name in columns:
return column_name
else:
raise ValueError(f"Dataframe does not have column '{column_name}'")
else:
possible_columns = [i for i in ["id"] if i in columns]
if len(possible_columns) != 1:
raise ValueError(
"Cannot guess id column name for this DataFrame. "
"Please provide a value in id_column"
)
else:
column_name = possible_columns[0]
logger.warning(f"Guessed id column name {column_name} for the data")
return column_name
def add_na_indicator(
df: pd.DataFrame, replace_val_obj: str = "_NA", replace_val_num: int = 0
) -> pd.DataFrame:
"""If a column in the DataFrame contains NAs, replace these with 0 for
numerical columns or "_NA" for non-numerical columns,
and add another column of an indicator variable for which rows were NA.
Args:
df (pd.DataFrame): The input DataFrame
replace_val_obj (str, optional): The value to put instead of nulls for object columns. Defaults to "_NA".
replace_val_num (int, optional): The value to put instead of nulls for numeric columns. Defaults to 0.
Raises:
Exception: Can't add NA indicator to DataFrame which contains columns which start with '_is_na_'
Exception: Can't add NA indicator to columns containing NAs and the value '{replace_val_obj}',
Returns:
pd.DataFrame: New dataframe with additional columns
"""
already_na_cols = [c for c in df.columns if c.startswith("_is_na_")]
if len(already_na_cols) > 0:
# TODO: change to ValueError?!
raise Exception(
"Can't add NA indicator to DataFrame which contains"
f"columns which start with '_is_na_': {already_na_cols}"
)
na = df.isnull()
na_cols = list(df.columns[na.any(axis="index")])
na_indicators = na.loc[:, na_cols]
na_indicators.columns = ("_is_na_" + c for c in na_indicators.columns)
categorical_cols = list(df.columns[df.dtypes == "category"])
non_numeric_cols = list(
df.columns[(df.dtypes == "object") | (df.dtypes == "string")]
)
for c in list(na_cols):
if replace_val_obj in set(df[c]):
# TODO: change to ValueError?!
raise Exception(
f"Can't add NA indicator to columns containing NAs and the value '{replace_val_obj}', "
f"i.e. column: {c}"
)
if c in categorical_cols:
df[c] = df[c].cat.add_categories(replace_val_obj).fillna(replace_val_obj)
elif c in non_numeric_cols:
df[c] = df[c].fillna(replace_val_obj)
else:
df[c] = df[c].fillna(replace_val_num)
return pd.concat((df, na_indicators), axis=1)
def drop_na_rows(
sample_df: pd.DataFrame, sample_weights: pd.Series, name: str = "sample object"
) -> Tuple[pd.DataFrame, pd.Series]:
"""
Drop rows with missing values in sample_df and their corresponding weights, and the same in target_df.
Args:
sample_df (pd.DataFrame): a dataframe representing the sample or target
sample_weights (pd.Series): design weights for sample or target
name (str, optional): name of object checked (used for warnings prints). Defaults to "sample object".
Raises:
ValueError: Dropping rows led to empty {name}. Maybe try na_action='add_indicator'?
Returns:
Tuple[pd.DataFrame, pd.Series]: sample_df, sample_weights without NAs rows
"""
sample_n = sample_df.shape[0]
sample_df = sample_df.dropna()
sample_weights = sample_weights[sample_df.index]
sample_n_after = sample_df.shape[0]
_sample_rate = f"{sample_n - sample_n_after}/{sample_n}"
logger.warning(f"Dropped {_sample_rate} rows of {name}")
if sample_n_after == 0:
raise ValueError(
f"Dropping rows led to empty {name}. Maybe try na_action='add_indicator'?"
)
return (sample_df, sample_weights)
def formula_generator(variables, formula_type: str = "additive") -> str:
"""Create formula to build the model matrix
Default is additive formula.
Args:
variables: list with names of variables (as strings) to combine into a formula
formula_type (str, optional): how to construct the formula. Currently only "additive" is supported. Defaults to "additive".
Raises:
Exception: "This formula type is not supported.'" "Please provide a string formula"
Returns:
str: A string representing the formula
Examples:
::
formula_generator(['a','b','c'])
# returns 'c + b + a'
"""
if formula_type == "additive":
rhs_formula = " + ".join(sorted(variables, reverse=True))
else:
# TODO ValueError?!
raise Exception(
"This formula type is not supported.'" "Please provide a string formula"
)
logger.debug(f"Model default formula: {rhs_formula}")
return rhs_formula
def dot_expansion(formula, variables: List):
"""Build a formula string by replacing "." with "summing" all the variables,
If no dot appears, returns the formula as is.
This function is named for the 'dot' operators in R, where a formula given
as ' ~ .' means "use all variables in dataframe.
Args:
formula: The formula to expand.
variables (List): List of all variables in the dataframe we build the formula for.
Raises:
Exception: "Variables should not be empty. Please provide a list of strings."
Exception: "Variables should be a list of strings and have to be included."
Returns:
A string formula replacing the '.'' with all variables in variables.
If no '.' is present, then the original formula is returned as is.
Examples:
::
dot_expansion('.', ['a','b','c','d']) # (a+b+c+d)
dot_expansion('b:(. - a)', ['a','b','c','d']) # b:((a+b+c+d) - a)
dot_expansion('a*b', ['a','b','c','d']) # a*b
dot_expansion('.', None) # Raise error
import pandas as pd
d = {'a': ['a1','a2','a1','a1'], 'b': ['b1','b2','b3','b3'],
'c': ['c1','c1','c2','c1'], 'd':['d1','d1','d2','d3']}
df = pd.DataFrame(data=d)
dot_expansion('.', df) # Raise error
dot_expansion('.', list(df.columns)) # (a+b+c+d)
"""
if variables is None:
# TODO: TypeError?
raise Exception(
"Variables should not be empty. Please provide a list of strings."
)
if not isinstance(variables, list):
# TODO: TypeError?
raise Exception(
"Variables should be a list of strings and have to be included."
"Please provide a list of your variables. If you would like to use all variables in"
"a dataframe, insert variables = list(df.columns)"
)
if formula.find(".") == -1:
rhs = formula
else:
dot = "(" + "+".join(x for x in variables) + ")"
rhs = str(formula).replace(".", dot)
return rhs
class one_hot_encoding_greater_2:
"""
This class creates a special encoding for factor variable to be used in a LASSO model.
For variables with exactly two levels using this in dmatrix will only keep one level, i.e.
will create one column with a 0 or 1 indicator for one of the levels. The level kept will
be the second one, based on loxicographical order of the levels.
For variables with more than 2 levels, using this in dmatrix will keep all levels
as columns of the matrix.
References:
1. More about this encoding:
# https://stats.stackexchange.com/questions/69804/group-categorical-variables-in-glmnet/107958#107958
3. Source code: adaptation of
# https://patsy.readthedocs.io/en/latest/categorical-coding.html
Examples:
::
import pandas as pd
d = {'a': ['a1','a2','a1','a1'], 'b': ['b1','b2','b3','b3'],
'c': ['c1','c1','c2','c1'], 'd':['d1','d1','d2','d3']}
df = pd.DataFrame(data=d)
print(dmatrix('C(a, one_hot_encoding_greater_2)', df, return_type = 'dataframe'))
# Intercept C(a, one_hot_encoding_greater_2)[a2]
#0 1.0 0.0
#1 1.0 1.0
#2 1.0 0.0
#3 1.0 0.0
print(dmatrix('C(a, one_hot_encoding_greater_2)-1', df, return_type = 'dataframe'))
# C(a, one_hot_encoding_greater_2)[a2]
#0 0.0
#1 1.0
#2 0.0
#3 0.0
print(dmatrix('C(b, one_hot_encoding_greater_2)', df, return_type = 'dataframe'))
# Intercept C(b, one_hot_encoding_greater_2)[b1] \
#0 1.0 1.0
#1 1.0 0.0
#2 1.0 0.0
#3 1.0 0.0
#
# C(b, one_hot_encoding_greater_2)[b2] C(b, one_hot_encoding_greater_2)[b3]
#0 0.0 0.0
#1 1.0 0.0
#2 0.0 1.0
#3 0.0 1.0
print(dmatrix('C(b, one_hot_encoding_greater_2)-1', df, return_type = 'dataframe'))
# C(b, one_hot_encoding_greater_2)[b1] C(b, one_hot_encoding_greater_2)[b2] \
#0 1.0 0.0
#1 0.0 1.0
#2 0.0 0.0
#3 0.0 0.0
#
# C(b, one_hot_encoding_greater_2)[b3]
#0 0.0
#1 0.0
#2 1.0
d = {'a': ['a1','a1','a1','a1'], 'b': ['b1','b2','b3','b3']}
df = pd.DataFrame(data=d)
print(dmatrix('C(a, one_hot_encoding_greater_2)-1', df, return_type = 'dataframe'))
print(dmatrix('C(a, one_hot_encoding_greater_2):C(b, one_hot_encoding_greater_2)-1', df, return_type = 'dataframe')) C(a, one_hot_encoding_greater_2)[a1]
#0 1.0
#1 1.0
#2 1.0
#3 1.0
# C(a, one_hot_encoding_greater_2)[a1]:C(b, one_hot_encoding_greater_2)[b1] \
#0 1.0
#1 0.0
#2 0.0
#3 0.0
#
# C(a, one_hot_encoding_greater_2)[a1]:C(b, one_hot_encoding_greater_2)[b2] \
#0 0.0
#1 1.0
#2 0.0
#3 0.0
"""
def __init__(self, reference: int = 0) -> None:
self.reference = reference
def code_with_intercept(self, levels):
if len(levels) == 2:
eye = np.eye(len(levels) - 1)
contrasts = np.vstack(
(
eye[: self.reference, :],
np.zeros((1, len(levels) - 1)),
eye[self.reference :, :],
)
)
suffixes = [
f"[{level}]"
for level in levels[: self.reference] + levels[self.reference + 1 :]
]
contrasts_mat = ContrastMatrix(contrasts, suffixes)
else:
contrasts_mat = ContrastMatrix(
np.eye(len(levels)), [f"[{level}]" for level in levels]
)
return contrasts_mat
def code_without_intercept(self, levels):
return self.code_with_intercept(levels)
def process_formula(formula, variables: List, factor_variables=None):
"""Process a formula string:
1. Expand . notation using dot_expansion function
2. Remove intercept (if using ipw, it will be added automatically by cvglmnet)
3. If factor_variables is not None, one_hot_encoding_greater_2 is applied
to factor_variables
Args:
formula: A string representing the formula
variables (List): list of all variables to include (usually all variables in data)
factor_variables: list of names of factor variables that we use
one_hot_encoding_greater_2 for. Note that these should be also
part of variables.
Default is None, in which case no special contrasts are
applied (using patsy defaults). one_hot_encoding_greater_2
creates one-hot-encoding for all categorical variables with
more than 2 categories (i.e. the number of columns will
be equal to the number of categories), and only 1
column for variables with 2 levels (treatment contrast).
Raises:
Exception: "Not all factor variables are contained in variables"
Returns:
a ModelDesc object to build a model matrix using patsy.dmatrix.
Examples:
::
f1 = process_formula('a:(b+aab)', ['a','b','aab'])
print(f1)
# ModelDesc(lhs_termlist=[],
# rhs_termlist=[Term([EvalFactor('a'), EvalFactor('b')]),
# Term([EvalFactor('a'), EvalFactor('aab')])])
f2 = process_formula('a:(b+aab)', ['a','b','aab'], ['a','b'])
print(f2)
# ModelDesc(lhs_termlist=[],
# rhs_termlist=[Term([EvalFactor('C(a, one_hot_encoding_greater_2)'),
# EvalFactor('C(b, one_hot_encoding_greater_2)')]),
# Term([EvalFactor('C(a, one_hot_encoding_greater_2)'),
# EvalFactor('aab')])])
"""
# Check all factor variables are in variables:
if (factor_variables is not None) and (not set(factor_variables) <= set(variables)):
# TODO: ValueError?!
raise Exception("Not all factor variables are contained in variables")
formula = dot_expansion(formula, variables)
# Remove the intercept since it is added by cvglmnet/cbps
formula = formula + " -1"
desc = ModelDesc.from_formula(formula)
if factor_variables is not None:
# We use one_hot_encoding_greater_2 for building the model matrix for factor_variables
# Reference: https://patsy.readthedocs.io/en/latest/categorical-coding.html
for i, term_i in enumerate(desc.rhs_termlist):
for j, factor_j in enumerate(term_i.factors):
if factor_j.code in factor_variables:
var = desc.rhs_termlist[i].factors[j].code
desc.rhs_termlist[i].factors[
j
].code = f"C({var}, one_hot_encoding_greater_2)"
return desc
def build_model_matrix(
df: pd.DataFrame,
formula: str = ".",
factor_variables: Optional[List] = None,
return_sparse: bool = False,
) -> Dict[str, Any]:
"""Build a model matrix from a formula (using patsy.dmatrix)
Args:
df (pd.DataFrame): The data from which to create the model matrix (pandas dataframe)
formula (str, optional): a string representing the formula to use for building the model matrix.
Default is additive formula with all variables in df. Defaults to ".".
factor_variables (LisOptional[List]t, optional): list of names of factor variables that we use
one_hot_encoding_greater_2 for.
Default is None, in which case no special contrasts are applied
(uses patsy defaults).
one_hot_encoding_greater_2 creates one-hot-encoding for all
categorical variables with more than 2 categories (i.e. the
number of columns will be equal to the number of categories), and only 1
column for variables with 2 levels (treatment contrast).
return_sparse (bool, optional): whether to return a sparse matrix using scipy.sparse.csc_matrix. Defaults to False.
Raises:
Exception: "Variable names cannot contain characters '[' or ']'"
Exception: "Not all factor variables are contained in df"
Returns:
Dict[str, Any]: A dictionary of 2 elements:
1. model_matrix - this is a pd dataframe or a csc_matrix (depends on return_sparse), ordered by columns names
2. model_matrix_columns - A list of the columns names of model_matrix
(We include model_matrix_columns as a separate argument since if we return a sparse X_matrix,
it doesn't have a columns names argument and these need to be kept separately,
see here:
https://stackoverflow.com/questions/35086940/how-can-i-give-row-and-column-names-to-scipys-csr-matrix.)
Examples:
::
import pandas as pd
d = {'a': ['a1','a2','a1','a1'], 'b': ['b1','b2','b3','b3']}
df = pd.DataFrame(data=d)
print(build_model_matrix(df, 'a'))
# {'model_matrix': a[a1] a[a2]
# 0 1.0 0.0
# 1 0.0 1.0
# 2 1.0 0.0
# 3 1.0 0.0,
# 'model_matrix_columns': ['a[a1]', 'a[a2]']}
print(build_model_matrix(df, '.'))
# {'model_matrix': a[a1] a[a2] b[T.b2] b[T.b3]
# 0 1.0 0.0 0.0 0.0
# 1 0.0 1.0 1.0 0.0
# 2 1.0 0.0 0.0 1.0
# 3 1.0 0.0 0.0 1.0,
# 'model_matrix_columns': ['a[a1]', 'a[a2]', 'b[T.b2]', 'b[T.b3]']}
print(build_model_matrix(df, '.', factor_variables=['a']))
# {'model_matrix': C(a, one_hot_encoding_greater_2)[a2] b[T.b2] b[T.b3]
# 0 0.0 0.0 0.0
# 1 1.0 1.0 0.0
# 2 0.0 0.0 1.0
# 3 0.0 0.0 1.0,
# 'model_matrix_columns': ['C(a, one_hot_encoding_greater_2)[a2]', 'b[T.b2]', 'b[T.b3]']}
print(build_model_matrix(df, 'a', return_sparse=True))
# {'model_matrix': <4x2 sparse matrix of type '<class 'numpy.float64'>'
# with 4 stored elements in Compressed Sparse Column format>, 'model_matrix_columns': ['a[a1]', 'a[a2]']}
print(build_model_matrix(df, 'a', return_sparse=True)["model_matrix"].toarray())
# [[1. 0.]
# [0. 1.]
# [1. 0.]
# [1. 0.]]
"""
variables = list(df.columns)
bracket_variables = [v for v in variables if ("[" in v) or ("]" in v)]
if len(bracket_variables) > 0:
# TODO: ValueError?
raise Exception(
"Variable names cannot contain characters '[' or ']'"
f"because patsy uses them to denote one-hot encoded categoricals: ({bracket_variables})"
)
# Check all factor variables are in variables:
if factor_variables is not None:
if not (set(factor_variables) <= set(variables)):
# TODO: ValueError?
raise Exception("Not all factor variables are contained in df")
model_desc = process_formula(formula, variables, factor_variables)
# dmatrix cannot get Int64Dtype as data type. Hence converting all numeric columns to float64.
for x in df.columns:
if (is_numeric_dtype(df[x])) and (not is_bool_dtype(df[x])):
df[x] = df[x].astype("float64")
X_matrix = dmatrix(model_desc, data=df, return_type="dataframe")
# Sorting the output in order to eliminate edge cases that cause column order to be stochastic
X_matrix = X_matrix.sort_index(axis=1)
logger.debug(f"X_matrix shape: {X_matrix.shape}")
X_matrix_columns = list(X_matrix.columns)
if return_sparse:
X_matrix = csc_matrix(X_matrix)
return {"model_matrix": X_matrix, "model_matrix_columns": X_matrix_columns}
def _prepare_input_model_matrix(
sample: Union[pd.DataFrame, Any],
target: Union[pd.DataFrame, Any, None] = None,
variables: Optional[List] = None,
add_na: bool = True,
fix_columns_names: bool = True,
) -> Dict[str, Any]:
"""Helper function to model_matrix. Prepare and check input of sample and target:
- Choose joint variables to sample and target (or by given variables)
- Extract sample and target dataframes
- Concat dataframes together
- Add na indicator if required.
Args:
sample (Union[pd.DataFrame, Any]): This can either be a DataFrame or a Sample object. TODO: add text.
target (Union[pd.DataFrame, Any, None], optional): This can either be a DataFrame or a Sample object.. Defaults to None.
variables (Optional[List], optional): Defaults to None. TODO: add text.
add_na (bool, optional): Defaults to True. TODO: add text.
fix_columns_names (bool, optional): Defaults to True. If to fix the column names of the DataFrame by changing special characters to '_'.
Raises:
Exception: "Variable names cannot contain characters '[' or ']'"
Returns:
Dict[str, Any]: returns a dictionary containing two keys: 'all_data' and 'sample_n'.
The 'all_data' is a pd.DataFrame with all the rows of 'sample' (including 'target', if supplied)
The'sample_n' is the number of rows in the first input DataFrame ('sample').
Examples:
::
import pandas as pd
import balance.util
df = pd.DataFrame(
{"a": ["a1", "a2", "a1", "a1"], "b": ["b1", "b2", "b3", "b3"]}
)
print(balance.util._prepare_input_model_matrix(df, df))
# {'all_data': a b
# 0 a1 b1
# 1 a2 b2
# 2 a1 b3
# 3 a1 b3
# 0 a1 b1
# 1 a2 b2
# 2 a1 b3
# 3 a1 b3, 'sample_n': 4}
# It automatically fixes the column names for you from special characters
df = pd.DataFrame(
{"a": ["a1", "a2", "a1", "a1"], "b./ * b": ["b1", "b2", "b3", "b3"]}
)
print(balance.util._prepare_input_model_matrix(df, df))
# {'all_data': a b_____b
# 0 a1 b1
# 1 a2 b2
# 2 a1 b3
# 3 a1 b3
# 0 a1 b1
# 1 a2 b2
# 2 a1 b3
# 3 a1 b3, 'sample_n': 4}
"""
variables = choose_variables(sample, target, variables=variables)
bracket_variables = [v for v in variables if ("[" in v) or ("]" in v)]
if len(bracket_variables) > 0:
raise Exception(
"Variable names cannot contain characters '[' or ']'"
f"because patsy uses them to denote one-hot encoded categoricals: ({bracket_variables})"
)
if _isinstance_sample(sample):
sample_df = sample._df
else:
sample_df = sample
assert sample_df.shape[0] > 0, "sample must have more than zero rows"
sample_n = sample_df.shape[0]
sample_df = sample_df.loc[:, variables]
if target is None:
target_df = None
elif _isinstance_sample(target):
target_df = target._df.loc[:, variables]
else:
target_df = target.loc[:, variables]
all_data = pd.concat((sample_df, target_df))
if add_na:
all_data = add_na_indicator(all_data)
else:
logger.warning("Dropping all rows with NAs")
if fix_columns_names:
all_data.columns = all_data.columns.str.replace(r"[^\w]", "_", regex=True)
all_data = _make_df_column_names_unique(all_data)
return {"all_data": all_data, "sample_n": sample_n}
def model_matrix(
sample: Union[pd.DataFrame, Any],
target: Union[pd.DataFrame, Any, None] = None,
variables: Optional[List] = None,
add_na: bool = True,
return_type: str = "two",
return_var_type: str = "dataframe",
formula: Optional[List[str]] = None,
penalty_factor: Optional[List[float]] = None,
one_hot_encoding: bool = False,
) -> Dict[
str, Union[List[str], np.ndarray, Union[pd.DataFrame, np.ndarray, csc_matrix], None]
]:
"""Create a model matrix from a sample (and target).
The default is to use an additive formula for all variables (or the ones specified).
Can also create a custom model matrix if a formula is provided.
Args:
sample (Union[pd.DataFrame, Any]): The Samples from which to create the model matrix. This can either be a DataFrame or a Sample object.
target (Union[pd.DataFrame, Any, None], optional): See sample. Defaults to None. This can either be a DataFrame or a Sample object.
variables (Optional[List]): the names of the variables to include (when 'None' then
all joint variables to target and sample are used). Defaults to None.
add_na (bool, optional): whether to call add_na_indicator on the data before constructing
the matrix.If add_na = True, then the function add_na_indicator is applied,
i.e. if a column in the DataFrame contains NAs, replace these with 0 or "_NA", and
add another column of an indicator variable for which rows were NA.
If add_na is False, observations with any missing data will be
omitted from the model. Defaults to True.
return_type (str, optional): whether to return a single matrix ('one'), or a dict of
sample and target matrices. Defaults to "two".
return_var_type (str, optional): whether to return a "dataframe" (pd.dataframe) a "matrix" (np.ndarray)
(i.e. only values of the output dataframe), or a "sparse" matrix. Defaults to "dataframe".
formula (Optional[List[str]], optional): according to what formula to construct the matrix. If no formula is provided an
additive formula is applied. This may be a string or a list of strings
representing different parts of the formula that will be concated together.
Default is None, which will create an additive formula from the available variables. Defaults to None.
penalty_factor (Optional[List[float]], optional): the penalty used in the glmnet function in ipw. The penalty
should have the same length as the formula list. If not provided,
assume the same penalty for all variables. Defaults to None.
one_hot_encoding (bool, optional): whether to encode all factor variables in the model matrix with
one_hot_encoding_greater_2. This is recommended in case of using
LASSO on the data (Default: False).
one_hot_encoding_greater_2 creates one-hot-encoding for all
categorical variables with more than 2 categories (i.e. the
number of columns will be equal to the number of categories),
and only 1 column for variables with 2 levels (treatment contrast). Defaults to False.
Returns:
Dict[ str, Union[List[str], np.ndarray, Union[pd.DataFrame, np.ndarray, csc_matrix], None] ]:
a dict of:
1. "model_matrix_columns_names": columns names of the model matrix
2. "penalty_factor ": a penalty_factor for each column in the model matrix
3. "model_matrix" (or: "sample" and "target"): the DataFrames for the sample and target
(one or two, according to return_type)
If return_sparse="True" returns a sparse matrix (csc_matrix)
Examples:
::
import pandas as pd
d = {'a': ['a1','a2','a1','a1'], 'b': ['b1','b2','b3','b3']}
df = pd.DataFrame(data=d)
model_matrix(df)
# {'model_matrix_columns_names': ['b[b1]', 'b[b2]', 'b[b3]', 'a[T.a2]'],
# 'penalty_factor': array([1, 1, 1, 1]),
# 'sample': b[b1] b[b2] b[b3] a[T.a2]
# 0 1.0 0.0 0.0 0.0
# 1 0.0 1.0 0.0 1.0
# 2 0.0 0.0 1.0 0.0
# 3 0.0 0.0 1.0 0.0,
# 'target': None}
model_matrix(df, formula = 'a*b')
# {'model_matrix_columns_names': ['a[a1]',
# 'a[a2]',
# 'b[T.b2]',
# 'b[T.b3]',
# 'a[T.a2]:b[T.b2]',
# 'a[T.a2]:b[T.b3]'],
# 'penalty_factor': array([1, 1, 1, 1, 1, 1]),
# 'sample': a[a1] a[a2] b[T.b2] b[T.b3] a[T.a2]:b[T.b2] a[T.a2]:b[T.b3]
# 0 1.0 0.0 0.0 0.0 0.0 0.0
# 1 0.0 1.0 1.0 0.0 1.0 0.0
# 2 1.0 0.0 0.0 1.0 0.0 0.0
# 3 1.0 0.0 0.0 1.0 0.0 0.0,
# 'target': None}
model_matrix(df, formula = ['a','b'], penalty_factor=[1,2])
# {'model_matrix_columns_names': ['a[a1]', 'a[a2]', 'b[b1]', 'b[b2]', 'b[b3]'],
# 'penalty_factor': array([1, 1, 2, 2, 2]),
# 'sample': a[a1] a[a2] b[b1] b[b2] b[b3]
# 0 1.0 0.0 1.0 0.0 0.0
# 1 0.0 1.0 0.0 1.0 0.0
# 2 1.0 0.0 0.0 0.0 1.0
# 3 1.0 0.0 0.0 0.0 1.0,
# 'target': None}
model_matrix(df, formula = ['a','b'], penalty_factor=[1,2], one_hot_encoding=True)
# {'model_matrix_columns_names': ['C(a, one_hot_encoding_greater_2)[a2]',
# 'C(b, one_hot_encoding_greater_2)[b1]',
# 'C(b, one_hot_encoding_greater_2)[b2]',
# 'C(b, one_hot_encoding_greater_2)[b3]'],
# 'penalty_factor': array([1, 2, 2, 2]),
# 'sample': C(a, one_hot_encoding_greater_2)[a2] ... C(b, one_hot_encoding_greater_2)[b3]
# 0 0.0 ... 0.0
# 1 1.0 ... 0.0
# 2 0.0 ... 1.0
# 3 0.0 ... 1.0
# [4 rows x 4 columns],
# 'target': None}
model_matrix(df, formula = ['a','b'], penalty_factor=[1,2], return_sparse = True)
# {'model_matrix_columns_names': ['a[a1]', 'a[a2]', 'b[b1]', 'b[b2]', 'b[b3]'],
# 'penalty_factor': array([1, 1, 2, 2, 2]),
# 'sample': <4x5 sparse matrix of type '<class 'numpy.float64'>'
# with 8 stored elements in Compressed Sparse Column format>,
# 'target': None}
model_matrix(df, target = df)
# {'model_matrix_columns_names': ['b[b1]', 'b[b2]', 'b[b3]', 'a[T.a2]'],
# 'penalty_factor': array([1, 1, 1, 1]),
# 'sample': b[b1] b[b2] b[b3] a[T.a2]
# 0 1.0 0.0 0.0 0.0
# 1 0.0 1.0 0.0 1.0
# 2 0.0 0.0 1.0 0.0
# 3 0.0 0.0 1.0 0.0,
# 'target': b[b1] b[b2] b[b3] a[T.a2]
# 0 1.0 0.0 0.0 0.0
# 1 0.0 1.0 0.0 1.0
# 2 0.0 0.0 1.0 0.0
# 3 0.0 0.0 1.0 0.0}
model_matrix(df, target = df, return_type = "one")
# {'model_matrix_columns_names': ['b[b1]', 'b[b2]', 'b[b3]', 'a[T.a2]'],
# 'penalty_factor': array([1, 1, 1, 1]),
# 'model_matrix': b[b1] b[b2] b[b3] a[T.a2]
# 0 1.0 0.0 0.0 0.0
# 1 0.0 1.0 0.0 1.0
# 2 0.0 0.0 1.0 0.0
# 3 0.0 0.0 1.0 0.0
# 0 1.0 0.0 0.0 0.0
# 1 0.0 1.0 0.0 1.0
# 2 0.0 0.0 1.0 0.0
# 3 0.0 0.0 1.0 0.0}
model_matrix(df, target = df, formula=['a','b'],return_type = "one")
# {'model_matrix_columns_names': ['a[a1]', 'a[a2]', 'b[b1]', 'b[b2]', 'b[b3]'],
# 'penalty_factor': array([1, 1, 1, 1, 1]),
# 'model_matrix': a[a1] a[a2] b[b1] b[b2] b[b3]
# 0 1.0 0.0 1.0 0.0 0.0
# 1 0.0 1.0 0.0 1.0 0.0
# 2 1.0 0.0 0.0 0.0 1.0
# 3 1.0 0.0 0.0 0.0 1.0
# 0 1.0 0.0 1.0 0.0 0.0
# 1 0.0 1.0 0.0 1.0 0.0
# 2 1.0 0.0 0.0 0.0 1.0
# 3 1.0 0.0 0.0 0.0 1.0}
"""
logger.debug("Starting building the model matrix")
input_data = _prepare_input_model_matrix(sample, target, variables, add_na)
all_data = input_data["all_data"]
sample_n = input_data["sample_n"]
# Arrange formula
if formula is None:
# if no formula is provided, we create an additive formula from available columns
formula = formula_generator(list(all_data.columns), formula_type="additive")
if not isinstance(formula, list):
formula = [formula]
logger.debug(f"The formula used to build the model matrix: {formula}")
# If formula is given we rely on patsy formula checker to check it.
# Arrange penalty factor
if penalty_factor is None:
penalty_factor = [1] * len(formula)
assert len(formula) == len(
penalty_factor
), "penalty factor and formula must have the same length"
# Arrange factor variables
if one_hot_encoding:
factor_variables = list(
all_data.select_dtypes(["category", "string", "boolean", "object"]).columns
)
logger.debug(
f"These variables will be encoded using one-hot encoding: {factor_variables}"
)
else:
factor_variables = None
X_matrix = []
X_matrix_columns = []
pf = []
for idx, formula_item in enumerate(formula):
logger.debug(f"Building model matrix for formula item {formula_item}")
model_matrix_result = build_model_matrix(
all_data,
formula_item,
factor_variables=factor_variables,
return_sparse=(return_var_type == "sparse"),
)
X_matrix_columns = (
X_matrix_columns + model_matrix_result["model_matrix_columns"]
)
X_matrix.append(model_matrix_result["model_matrix"])
pf.append(
np.repeat(
penalty_factor[idx],
model_matrix_result["model_matrix"].shape[1],
axis=0,
)
)
penalty_factor = np.concatenate(pf, axis=0)
if return_var_type == "sparse":
X_matrix = hstack(X_matrix, format="csc")
elif return_var_type == "matrix":
X_matrix = pd.concat(X_matrix, axis=1).values
else:
X_matrix = pd.concat(X_matrix, axis=1)
logger.debug("The number of columns in the model matrix: {X_matrix.shape[1]}")
logger.debug("The number of rows in the model matrix: {X_matrix.shape[0]}")
result = {
"model_matrix_columns_names": X_matrix_columns,
"penalty_factor": penalty_factor,
"formula": formula,
}
if return_type == "one":
result["model_matrix"] = X_matrix
elif return_type == "two":
sample_matrix = X_matrix[0:sample_n]
if target is None:
target_matrix = None
else:
target_matrix = X_matrix[sample_n:]
result["sample"] = sample_matrix
result["target"] = target_matrix
logger.debug("Finished building the model matrix")
return result
# TODO: add type hinting
def qcut(s, q, duplicates: str = "drop", **kwargs):
"""Discretize variable into equal-sized buckets based quantiles.
This is a wrapper to pandas qcut function.
Args:
s (_type_): 1d ndarray or Series.
q (_type_): Number of quantiles (int or float).
duplicates (str, optional): whether to drop non unique bin edges or raise error ("raise" or "drop").
Defaults to "drop".
Returns:
Series of type object with intervals.
"""
if s.shape[0] < q:
logger.warning("Not quantizing, too few values")
return s
else:
return pd.qcut(s, q, duplicates=duplicates, **kwargs).astype("O")
# TODO: fix it so that the order of the returned columns is the same as the original order in the DataFrame
def quantize(
df: Union[pd.DataFrame, pd.Series], q: int = 10, variables=None
) -> pd.DataFrame:
"""Cut numeric variables of a DataFrame into quantiles buckets
Args:
df (Union[pd.DataFrame, pd.Series]): a DataFrame to transform
q (int, optional): Number of buckets to create for each variable. Defaults to 10.
variables (optional): variables to transform.
If None, all numeric variables are transformed. Defaults to None.
Returns:
pd.DataFrame: DataFrame after quantization. numpy.nan values are kept as is.
Examples:
::
from balance.util import quantize
import numpy as np
df = pd.DataFrame({"a": [1,1,2,20,22,23,np.nan], "b": range(7), "c": range(7), "d": [1,1,np.nan,20,5,23,np.nan]})
print(quantize(df, q = 3))
# b d c a
# 0 (-0.001, 2.0] (0.999, 2.333] (-0.001, 2.0] (0.999, 1.667]
# 1 (-0.001, 2.0] (0.999, 2.333] (-0.001, 2.0] (0.999, 1.667]
# 2 (-0.001, 2.0] NaN (-0.001, 2.0] (1.667, 20.667]
# 3 (2.0, 4.0] (15.0, 23.0] (2.0, 4.0] (1.667, 20.667]
# 4 (2.0, 4.0] (2.333, 15.0] (2.0, 4.0] (20.667, 23.0]
# 5 (4.0, 6.0] (15.0, 23.0] (4.0, 6.0] (20.667, 23.0]
# 6 (4.0, 6.0] NaN (4.0, 6.0] NaN
"""
if not (isinstance(df, pd.Series) or isinstance(df, pd.DataFrame)):
# Necessary because pandas calls the function on the first item on its own
# https://stackoverflow.com/questions/21635915/
df = pd.Series(df)
# TODO: change assert to raise
if isinstance(df, pd.Series):
assert is_numeric_dtype(df.dtype), "series must be numeric"
return qcut(df, q, duplicates="drop")
assert isinstance(df, pd.DataFrame)
variables = choose_variables(df, variables=variables)
numeric_columns = list(df.select_dtypes(include=[np.number]).columns)
variables = [v for v in variables if v in numeric_columns]
transformed_data = df.loc[:, variables].transform(
lambda c: qcut(c, q, duplicates="drop")
)
untransformed_columns = df.columns.difference(variables)
transformed_data = pd.concat(
(df.loc[:, untransformed_columns], transformed_data), axis=1
)
return transformed_data
def row_pairwise_diffs(df: pd.DataFrame) -> pd.DataFrame:
"""Produce the differences between every pair of rows of df
Args:
df (pd.DataFrame): DataFrame
Returns:
pd.DataFrame: DataFrame with differences between all combinations of rows
Examples:
::
d = pd.DataFrame({"a": (1, 2, 3), "b": (-42, 8, 2)})
row_pairwise_diffs(d)
# a b
# 0 1 -42
# 1 2 8
# 2 3 2
# 1 - 0 1 50
# 2 - 0 2 44
# 2 - 1 1 -6
"""
c = combinations(sorted(df.index), 2)
diffs = []
for j, i in c:
d = df.loc[i] - df.loc[j]
d = d.to_frame().transpose().assign(source=f"{i} - {j}").set_index("source")
diffs.append(d)
return pd.concat([df] + diffs)
def _is_arraylike(o) -> bool:
"""Test (returns True) if an object is an array-ish type (a numpy array, or
a sequence, but not a string). Not the same as numpy's arraylike,
which also applies to scalars which can be turned into arrays.
Args:
o: Object to test.
Returns:
bool: returns True if an object is an array-ish type.
"""
return (
isinstance(o, np.ndarray)
or isinstance(o, pd.Series)
or isinstance(o, pd.arrays.PandasArray)
or isinstance(o, pd.arrays.StringArray)
or isinstance(o, pd.arrays.IntegerArray)
or isinstance(o, pd.arrays.BooleanArray)
or "pandas.core.arrays" in str(type(o)) # support any pandas array type.
or (isinstance(o, collections.abc.Sequence) and not isinstance(o, str))
)
def rm_mutual_nas(*args) -> List:
"""
Remove entries in a position which is na or infinite in any of the arguments.
Ignores args which are None.
Can accept multiple array-like arguments or a single array-like argument. Handles pandas and numpy arrays.
Raises:
ValueError: If any argument is not array-like. (see: :func:`_is_arraylike`)
ValueError: If arguments include arrays of different lengths.
Returns:
List: A list containing the original input arrays, after removing elements that have a missing or infinite value in the same position as any of the other arrays.
Examples:
::
import pandas as pd
import numpy as np
x1 = pd.array([1,2, None, np.nan, pd.NA, 3])
x2 = pd.array([1.1,2,3, None, np.nan, pd.NA])
x3 = pd.array([1.1,2,3, 4,5,6])
x4 = pd.array(["1.1",2,3, None, np.nan, pd.NA])
x5 = pd.array(["1.1","2","3", None, np.nan, pd.NA], dtype = "string")
x6 = np.array([1,2,3.3,4,5,6])
x7 = np.array([1,2,3.3,4,"5","6"])
x8 = [1,2,3.3,4,"5","6"]
(x1,x2, x3, x4, x5, x6, x7, x8)
# (<IntegerArray>
# [1, 2, <NA>, <NA>, <NA>, 3]
# Length: 6, dtype: Int64,
# <PandasArray>
# [1.1, 2, 3, None, nan, <NA>]
# Length: 6, dtype: object,
# <PandasArray>
# [1.1, 2.0, 3.0, 4.0, 5.0, 6.0]
# Length: 6, dtype: float64,
# <PandasArray>
# ['1.1', 2, 3, None, nan, <NA>]
# Length: 6, dtype: object,
# <StringArray>
# ['1.1', '2', '3', <NA>, <NA>, <NA>]
# Length: 6, dtype: string,
# array([1. , 2. , 3.3, 4. , 5. , 6. ]),
# array(['1', '2', '3.3', '4', '5', '6'], dtype='<U32'),
# [1, 2, 3.3, 4, '5', '6'])
from balance.util import rm_mutual_nas
rm_mutual_nas(x1,x2, x3, x4, x5,x6,x7,x8)
# [<IntegerArray>
# [1, 2]
# Length: 2, dtype: Int64,
# <PandasArray>
# [1.1, 2]
# Length: 2, dtype: object,
# <PandasArray>
# [1.1, 2.0]
# Length: 2, dtype: float64,
# <PandasArray>
# ['1.1', 2]
# Length: 2, dtype: object,
# <StringArray>
# ['1.1', '2']
# Length: 2, dtype: string,
# array([1., 2.]),
# array(['1', '2'], dtype='<U32'),
# [1, 2]]
# Preserve the index values in the resulting pd.Series:
x1 = pd.Series([1, 2, 3, 4])
x2 = pd.Series([np.nan, 2, 3, 4])
x3 = np.array([1, 2, 3, 4])
print(rm_mutual_nas(x1, x2)[0])
print(rm_mutual_nas(x1.sort_values(ascending=False), x2)[0])
print(rm_mutual_nas(x1, x3)[0])
# 1 2
# 2 3
# 3 4
# dtype: int64
# 3 4
# 2 3
# 1 2
# dtype: int64
# 0 1
# 1 2
# 2 3
# 3 4
# dtype: int64
"""
if any(not (a is None or _is_arraylike(a)) for a in args):
raise ValueError("All arguments must be arraylike")
# create a set of lengths of all arrays, and see if there are is more than
# one array length: (we shouldn't, since we expect all arrays to have the same length)
if len({len(a) for a in args if a is not None}) > 1:
raise ValueError("All arrays must be of same length")
missing_mask = reduce(
lambda x, y: x | y,
[
# pyre-ignore[16]: pd.Series has isna.
pd.Series(x).replace([np.inf, -np.inf], np.nan).isna()
for x in args
if x is not None
],
)
nonmissing_mask = ~missing_mask
def _return_type_creation_function(x: Any) -> Union[Callable, Any]:
# The numpy.ndarray constructor doesn't take the same arguments as np.array
if isinstance(x, np.ndarray):
return lambda obj: np.array(obj, dtype=x.dtype)
# same with pd.arrays.PandasArray, pd.arrays.StringArray, etc.
elif "pandas.core.arrays" in str(type(x)):
return lambda obj: pd.array(obj, dtype=x.dtype)
else:
return type(x)
# Need to convert each argument to a type that can be indexed and then
# convert back
original_types = [_return_type_creation_function(x) for x in args]
r = [pd.Series(x)[nonmissing_mask].tolist() if x is not None else x for x in args]
# Reapply the index for pd.Series
r = [
pd.Series(data, index=pd.Series(orig_data)[nonmissing_mask].index)
if isinstance(orig_data, pd.Series)
else data
for data, orig_data in zip(r, args)
]
# reproduce the type of each array in the result
r = [(t(x) if x is not None else x) for t, x in zip(original_types, r)]
if len(args) == 1:
r = r[0]
return r
# TODO: (p2) create choose_variables_df that only works with pd.DataFrames as input, and wrap it with something that deals with Sample.
# This would help clarify the logic of each function.
def choose_variables(
*dfs: Union[pd.DataFrame, Any],
variables: Optional[Union[List, set]] = None,
df_for_var_order: int = 0,
) -> List[str]:
"""
Returns a list of joint (intersection of) variables present in all the input dataframes and also in the `variables` set or list
if provided. The order of the returned variables is conditional on the input:
- If a `variables` argument is supplied as a list - the order will be based on the order in the variables list.
- If a `variables` is not a list (e.g.: set or None), the order is determined by the order of the columns in the dataframes
supplied. The dataframe chosen for the order is determined by the `df_for_var_order` argument. 0 means the order from the first df,
1 means the order from the second df, etc.
Args:
*dfs (Union[pd.DataFrame, Any]): One or more pandas.DataFrames or balance.Samples.
variables (Optional[Union[List, set]]): The variables to choose from. If None, returns all joint variables found
in the input dataframes. Defaults to None.
df_for_var_order (int): Index of the dataframe used to determine the order of the variables in the output list.
Defaults to 0. This is used only if the `variables` argument is not a list (e.g.: a set or None).
Raises:
ValueError: If one or more requested variables are not present in all dataframes.
Returns:
List[str]: A list of the joint variables present in all dataframes and in the `variables` set or list, ordered
based on the input conditions specified.
Examples:
::
import pandas as pd
from balance.util import choose_variables
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6], 'E': [1,1], 'F': [1,1]})
df2 = pd.DataFrame({'C': [7, 8], 'J': [9, 10], 'B': [11, 12], 'K': [1,1], 'A': [1,1]})
print(choose_variables(df1, df2))
print(choose_variables(df1, df2,df_for_var_order = 1))
print(choose_variables(df1, df2,variables=["B", "A"]))
# WARNING (2023-04-02 10:12:01,337) [util/choose_variables (line 1206)]: Ignoring variables not present in all Samples: {'K', 'F', 'E', 'J'}
# WARNING (2023-04-02 10:12:01,338) [util/choose_variables (line 1206)]: Ignoring variables not present in all Samples: {'K', 'F', 'E', 'J'}
# WARNING (2023-04-02 10:12:01,340) [util/choose_variables (line 1206)]: Ignoring variables not present in all Samples: {'K', 'F', 'E', 'J'}
# ['A', 'B', 'C']
# ['C', 'B', 'A']
# ['B', 'A']
"""
if (variables is not None) and (len(variables) == 0):
variables = None
# This is a list of lists with the variable names of the input dataframes
dfs_variables = [
d.covars().names() if _isinstance_sample(d) else d.columns.values.tolist()
for d in dfs
if d is not None
]
var_list_for_order = (
variables if (isinstance(variables, list)) else dfs_variables[df_for_var_order]
)
intersection_variables = set(
reduce(lambda x, y: set(x).intersection(set(y)), dfs_variables)
)
union_variables = reduce(lambda x, y: set(x).union(set(y)), dfs_variables)
if len(set(union_variables).symmetric_difference(intersection_variables)) > 0:
logger.warning(
f"Ignoring variables not present in all Samples: {union_variables.difference(intersection_variables)}"
)
if variables is None:
variables = intersection_variables
else:
variables = set(variables)
variables_not_in_df = variables.difference(intersection_variables)
if len(variables_not_in_df) > 0:
logger.warning(
"These variables are not included in the dataframes: {variables_not_in_df}"
)
raise ValueError(
f"{len(variables_not_in_df)} requested variables are not in all Samples: "
f"{variables_not_in_df}"
)
variables = intersection_variables.intersection(variables)
logger.debug(f"Joint variables in all dataframes: {list(variables)}")
if (variables is None) or (len(variables) == 0):
logger.warning("Sample and target have no variables in common")
return []
ordered_variables = []
for val in var_list_for_order:
if val in variables and val not in ordered_variables:
ordered_variables.append(val)
# NOTE: the above is just like:
# seen = set()
# ordered_variables = [val for val in dfs_variables[df_for_var_order] if val in variables and val not in seen and not seen.add(val)]
# TODO: consider changing the return form list to a tuple. But doing so would require to deal with various edge cases around the codebase.
return ordered_variables
def auto_spread(
data: pd.DataFrame, features: Optional[list] = None, id_: str = "id"
) -> pd.DataFrame:
"""Automatically transform a 'long' DataFrame into a 'wide' DataFrame
by guessing which column should be used as a key, treating all
other columns as values. At the moment, this will only find a single key column
Args:
data (pd.DataFrame):
features (Optional[list], optional): Defaults to None.
id_ (str, optional): Defaults to "id".
Returns:
pd.DataFrame
"""
if features is None:
features = [c for c in data.columns.values if c != id_]
is_unique = {}
for c in features:
unique_userids = data.groupby(c)[id_].apply(lambda x: len(set(x)) == len(x))
is_unique[c] = all(unique_userids.values)
unique_groupings = [k for k, v in is_unique.items() if v]
if len(unique_groupings) < 1:
logger.warning(f"no unique groupings {is_unique}")
return data
elif len(unique_groupings) > 1:
logger.warning(
f"{len(unique_groupings)} possible groupings: {unique_groupings}"
)
# Always chooses the first unique grouping
unique_grouping = unique_groupings[0]
logger.warning(f"Grouping by {unique_grouping}")
data = data.loc[:, features + [id_]].pivot(index=id_, columns=unique_grouping)
data.columns = [
"_".join(map(str, ((unique_grouping,) + c[-1:] + c[:-1])))
for c in data.columns.values
]
data = data.reset_index()
return data
def auto_aggregate(
data: pd.DataFrame,
features: None = None,
_id: str = "id",
# NOTE: we use str as default since using a lambda function directly would make this argument mutable -
# so if one function call would change it, another function call would get the revised aggfunc argument.
# Thus, using str is important so to keep our function idempotent.
aggfunc: Union[str, Callable] = "sum",
) -> pd.DataFrame:
# The default aggregation function is a lambda around sum(x), because as of
# Pandas 0.22.0, Series.sum of an all-na Series is 0, not nan
if features is not None:
warnings.warn(
"features argument is unused, it will be removed in the future",
warnings.DeprecationWarning,
)
if isinstance(aggfunc, str):
if aggfunc == "sum":
def _f(x):
return sum(x)
aggfunc = _f
else:
raise ValueError(
f"unknown aggregate function name {aggfunc}, accepted values are ('sum',)."
)
try:
data_without_id = data.drop(columns=[_id])
except KeyError:
raise ValueError(f"data must have a column named {_id}")
all_columns = data_without_id.columns.to_list()
numeric_columns = data_without_id.select_dtypes(
include=[np.number]
).columns.to_list()
if set(all_columns) != set(numeric_columns):
raise ValueError(
"Not all covariates are numeric. The function will not aggregate automatically."
)
return pd.pivot_table(data, index=_id, aggfunc=aggfunc).reset_index()
def fct_lump(s: pd.Series, prop: float = 0.05) -> pd.Series:
"""Lumps infrequent levels into '_lumped_other'.
Note that all values with proportion less than prop output the same value '_lumped_other'.
Args:
s (pd.Series): pd.series to lump, with dtype of integer, numeric, object, or category (category will be converted to object)
prop (float, optional): the proportion of infrequent levels to lump. Defaults to 0.05.
Returns:
pd.Series: pd.series (with category dtype converted to object, if applicable)
Examples:
::
from balance.util import fct_lump
import pandas as pd
s = pd.Series(['a','a','b','b','c','a','b'], dtype = 'category')
fct_lump(s, 0.25)
# 0 a
# 1 a
# 2 b
# 3 b
# 4 _lumped_other
# 5 a
# 6 b
# dtype: object
"""
props = s.value_counts() / s.shape[0]
small_categories = props[props < prop].index.tolist()
remainder_category_name = "_lumped_other"
while remainder_category_name in props.index:
remainder_category_name = remainder_category_name * 2
if s.dtype.name == "category":
s = s.astype( # pyre-ignore[9]: this use is for pd.Series (not defined currently for pd.DataFrame)
"object"
)
s.loc[s.apply(lambda x: x in small_categories)] = remainder_category_name
return s
def fct_lump_by(s: pd.Series, by: pd.Series, prop: float = 0.05) -> pd.Series:
"""Lumps infrequent levels into '_lumped_other, only does so per
value of the grouping variable `by`. Useful, for example, for keeping the
most important interactions in a model.
Args:
s (pd.Series): pd.series to lump
by (pd.Series): pd.series according to which group the data
prop (float, optional): the proportion of infrequent levels to lump. Defaults to 0.05.
Returns:
pd.Series: pd.series, we keep the index of s as the index of the result.
Examples:
::
s = pd.Series([1,1,1,2,3,1,2])
by = pd.Series(['a','a','a','a','a','b','b'])
fct_lump_by(s, by, 0.5)
# 0 1
# 1 1
# 2 1
# 3 _lumped_other
# 4 _lumped_other
# 5 1
# 6 2
# dtype: object
"""
# The reindexing is required in order to overcome bug before pandas 1.2
# https://github.com/pandas-dev/pandas/issues/16646
# we keep the index of s as the index of the result
s_index = s.index
s = s.reset_index( # pyre-ignore[9]: this use is for pd.Series (not defined currently for pd.DataFrame)
drop=True
)
by = by.reset_index( # pyre-ignore[9]: this use is for pd.Series (not defined currently for pd.DataFrame)‰
drop=True
)
res = s.groupby(by).apply(lambda x: fct_lump(x, prop=prop))
res.index = s_index
return res
# TODO: add tests
def _pd_convert_all_types(
df: pd.DataFrame, input_type: str, output_type: str
) -> pd.DataFrame:
"""Converts columns in the input dataframe to a specified type.
Args:
df (pd.DataFrame): Input df
input_type (str): A string of the input type to change.
output_type (str): A string of the desired output type for the columns of type input_type.
Returns:
pd.DataFrame: Output df with columns converted from input_type to output_type.
Examples:
::
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": pd.array([1,2], dtype = pd.Int64Dtype()), "a2": pd.array([1,2], dtype = np.int64)})
df.dtypes
# a Int64
# a2 int64
# dtype: object
df.dtypes.to_numpy()
# array([Int64Dtype(), dtype('int64')], dtype=object)
df2 =_pd_convert_all_types(df, "Int64", "int64")
df2.dtypes.to_numpy()
# array([dtype('int64'), dtype('int64')], dtype=object)
# Might be requires some casting to float64 so that it will handle missing values
# For details, see: https://stackoverflow.com/a/53853351
df3 =_pd_convert_all_types(df, "Int64", "float64")
df3.dtypes.to_numpy()
# array([dtype('float64'), dtype('float64')], dtype=object)
"""
df = copy.deepcopy(df)
# source: https://stackoverflow.com/a/56944992/256662
df.loc[:, df.dtypes == input_type] = df.select_dtypes([input_type]).apply(
lambda x: x.astype(output_type)
)
return df
# TODO: add tests
def find_items_index_in_list(a_list: List[Any], items: List[Any]) -> List[int]:
"""Finds the index location of a given item in an array.
Helpful references:
- https://stackoverflow.com/a/48898363
- https://stackoverflow.com/a/176921
Args:
x (List[Any]): a list of items to find their index
items (List[Any]): a list of items to search for
Returns:
List[int]: a list of indices of the items in x that appear in the items list.
Examples:
::
l = [1,2,3,4,5,6,7]
items = [2,7]
find_items_index_in_list(l, items)
# [1, 6]
items = [1000]
find_items_index_in_list(l, items)
# []
l = ["a", "b", "c"]
items = ["c", "c", "a"]
find_items_index_in_list(l, items)
# [2, 2, 0]
type(find_items_index_in_list(l, items)[0])
# int
"""
# TODO: checking that i is in set each time is expensive -
# there are probably faster ways to do it.
return [a_list.index(i) for i in items if i in set(a_list)]
# TODO: add tests
def get_items_from_list_via_indices(a_list: List[Any], indices: List[int]) -> List[Any]:
"""Gets a subset of items from a list via indices
Source code (there doesn't seem to be a better solution): https://stackoverflow.com/a/6632209
Args:
a_list (List[Any]): a list of items to extract a list from
indices (List[int]): a list of indexes of items to get
Returns:
List[Any]: a list of extracted items
Examples:
::
l = ["a", "b", "c", "d"]
get_items_from_list_via_indices(l, [2, 0])
# ['c', 'a']
get_items_from_list_via_indices(l, [100])
# IndexError
"""
return [a_list[i] for i in indices]
################################################################################
# logging
################################################################################
def _truncate_text(s: str, length: int) -> str:
"""Truncate string s to be of length 'length'. If the length of s is larger than 'length', then the
function will add '...' at the end of the truncated text.
Args:
s (str):
length (int):
Returns:
str:
"""
return s[:length] + "..." * (len(s) > length)
class TruncationFormatter(logging.Formatter):
"""
Logging formatter which truncates the logged message to 500 characters.
This is useful in the cases where the logging message includes objects
--- like DataFrames --- whose string representation is very long.
"""
def __init__(self, *args, **kwargs) -> None:
super(TruncationFormatter, self).__init__(*args, **kwargs)
def format(self, record: logging.LogRecord):
result = super(TruncationFormatter, self).format(record)
return _truncate_text(result, 2000)
################################################################################
# File handling
################################################################################
def _to_download(
df: pd.DataFrame,
tempdir: Optional[str] = None,
) -> FileLink:
"""Creates a downloadable link of the DataFrame (df).
File name starts with tmp_balance_out_, and some random file name (using :func:`uuid.uuid4`).
Args:
self (BalanceDF): Object.
tempdir (Optional[str], optional): Defaults to None (which then uses a temporary folder using :func:`tempfile.gettempdir`).
Returns:
FileLink: Embedding a local file link in an IPython session, based on path. Using :func:FileLink.
"""
if tempdir is None:
tempdir = tempfile.gettempdir()
path = f"{tempdir}/tmp_balance_out_{uuid.uuid4()}.csv"
df.to_csv(path_or_buf=path, index=False)
return FileLink(path, result_html_prefix="Click here to download: ")
################################################################################
# pandas utils
################################################################################
def _dict_intersect(d: Dict, d_for_keys: Dict) -> Dict:
"""Returns dict 1, but only with the keys that are also in d2
Args:
d1 (Dict): First dictionary.
d2 (Dict): Second dictionary.
Returns:
Dict: Intersection of d1 and d2 (with values from d1)
Examples:
::
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "b": 2}
_dict_intersect(d1, d2)
# {'b': 2}
"""
intersect_keys = d.keys() & d_for_keys.keys()
return {k: d[k] for k in intersect_keys}
# TODO: using _astype_in_df_from_dtypes to turn sample.df to original df dtypes may not be a good long term solution.
# A better solution might require a redesign of some core features.
def _astype_in_df_from_dtypes(
df: pd.DataFrame, target_dtypes: pd.Series
) -> pd.DataFrame:
"""Returns df with dtypes cast as specified in df_orig.
Columns that were not in the original dataframe are kept the same.
Args:
df (pd.DataFrame): df to convert
target_dtypes (pd.Series): DataFrame.dtypes to use as target dtypes for conversion
Returns:
pd.DataFrame: df with dtypes cast as specified in target_dtypes
Examples:
::
df = pd.DataFrame({"id": ("1", "2"), "a": (1.0, 2.0), "weight": (1.0,2.0)})
df_orig = pd.DataFrame({"id": (1, 2), "a": (1, 2), "forest": ("tree", "banana")})
df.dtypes.to_dict()
# {'id': dtype('O'), 'a': dtype('float64'), 'weight': dtype('float64')}
df_orig.dtypes.to_dict()
# {'id': dtype('int64'), 'a': dtype('int64'), 'forest': dtype('O')}
target_dtypes = df_orig.dtypes
_astype_in_df_from_dtypes(df, target_dtypes).dtypes.to_dict()
# {'id': dtype('int64'), 'a': dtype('int64'), 'weight': dtype('float64')}
"""
dict_of_target_dtypes = _dict_intersect(
# pyre-ignore[6]: using to_dict on pd.Series will work fine:
target_dtypes.to_dict(),
df.dtypes.to_dict(),
)
# pyre-ignore[7]: we expect the input and output to be df (and not pd.Series)
return df.astype(dict_of_target_dtypes)
def _true_false_str_to_bool(x: str) -> bool:
"""Changes strings such as 'false' to False and 'true' to True.
Args:
x (str): String to be converted (ideally 'true' or 'false' - case is ignored).
Raises:
ValueError: If x is not 'true' or 'false'.
Returns:
bool: True if x is 'true', False if x is 'false'.
Examples:
::
_true_false_str_to_bool('falsE') # False
_true_false_str_to_bool('TrUe') # True
_true_false_str_to_bool('Banana')
# ValueError: Banana is not an accepted value, please pass either 'True' or 'False' (lower/upper case is ignored)
"""
if x.lower() == "false":
return False
elif x.lower() == "true":
return True
else:
raise ValueError(
f"{x} is not an accepted value, please pass either 'True' or 'False' (lower/upper case is ignored)"
)
def _are_dtypes_equal(
dt1: pd.Series, dt2: pd.Series
) -> Dict[str, Union[bool, pd.Series, set]]:
"""Returns True if both dtypes are the same and False otherwise.
If dtypes have an unequal set of items, the comparison will only be about the same set of keys.
If there are no shared keys, then return False.
Args:
dt1 (pd.Series): first dtype (output from DataFrame.dtypes)
dt2 (pd.Series): second dtype (output from DataFrame.dtypes)
Returns:
Dict[str, Union[bool, pd.Series, set]]: a dict of the following structure
{
'is_equal': False,
'comparison_of_dtypes':
flt True
int False
dtype: bool,
'shared_keys': {'flt', 'int'}
}
Examples:
::
df1 = pd.DataFrame({'int':np.arange(5), 'flt':np.random.randn(5)})
df2 = pd.DataFrame({'flt':np.random.randn(5), 'int':np.random.randn(5)})
df11 = pd.DataFrame({'int':np.arange(5), 'flt':np.random.randn(5), 'miao':np.random.randn(5)})
_are_dtypes_equal(df1.dtypes, df1.dtypes)['is_equal'] # True
_are_dtypes_equal(df1.dtypes, df2.dtypes)['is_equal'] # False
_are_dtypes_equal(df11.dtypes, df2.dtypes)['is_equal'] # False
"""
shared_keys = set.intersection(set(dt1.keys()), set(dt2.keys()))
shared_keys_list = list(shared_keys)
comparison_of_dtypes = dt1[shared_keys_list] == dt2[shared_keys_list]
is_equal = np.all(comparison_of_dtypes)
return {
"is_equal": is_equal,
"comparison_of_dtypes": comparison_of_dtypes,
"shared_keys": shared_keys,
}
def _warn_of_df_dtypes_change(
original_df_dtypes: pd.Series,
new_df_dtypes: pd.Series,
original_str: str = "df",
new_str: str = "new_df",
) -> None:
"""Prints a warning if the dtypes of some original df and some modified df differs.
Args:
original_df_dtypes (pd.Series): dtypes of original dataframe
new_df_dtypes (pd.Series): dtypes of modified dataframe
original_str (str, optional): string to use for warnings when referring to the original. Defaults to "df".
new_str (str, optional): string to use for warnings when referring to the modified df. Defaults to "new_df".
Examples:
::
import numpy as np
import pandas as pd
from copy import deepcopy
import balance
df = pd.DataFrame({"int": np.arange(5), "flt": np.random.randn(5)})
new_df = deepcopy(df)
new_df.int = new_df.int.astype(float)
new_df.flt = new_df.flt.astype(int)
balance.util._warn_of_df_dtypes_change(df.dtypes, new_df.dtypes)
# WARNING (2023-02-07 08:01:19,961) [util/_warn_of_df_dtypes_change (line 1696)]: The dtypes of new_df were changed from the original dtypes of the input df, here are the differences -
# WARNING (2023-02-07 08:01:19,963) [util/_warn_of_df_dtypes_change (line 1707)]: The (old) dtypes that changed for df (before the change):
# WARNING (2023-02-07 08:01:19,966) [util/_warn_of_df_dtypes_change (line 1710)]:
# flt float64
# int int64
# dtype: object
# WARNING (2023-02-07 08:01:19,971) [util/_warn_of_df_dtypes_change (line 1711)]: The (new) dtypes saved in df (after the change):
# WARNING (2023-02-07 08:01:19,975) [util/_warn_of_df_dtypes_change (line 1712)]:
# flt int64
# int float64
# dtype: object
"""
compare_df_dtypes_before_and_after = _are_dtypes_equal(
original_df_dtypes, new_df_dtypes
)
if not compare_df_dtypes_before_and_after["is_equal"]:
logger.warning(
f"The dtypes of {new_str} were changed from the original dtypes of the input {original_str}, here are the differences - "
)
compared_dtypes = compare_df_dtypes_before_and_after["comparison_of_dtypes"]
dtypes_that_changed = (
# pyre-ignore[16]: we're only using the pd.Series, so no worries
compared_dtypes[np.bitwise_not(compared_dtypes.values)]
.keys()
.to_list()
)
logger.debug(compare_df_dtypes_before_and_after)
logger.warning(
f"The (old) dtypes that changed for {original_str} (before the change):"
)
logger.warning("\n" + str(original_df_dtypes[dtypes_that_changed]))
logger.warning(f"The (new) dtypes saved in {original_str} (after the change):")
logger.warning("\n" + str(new_df_dtypes[dtypes_that_changed]))
def _make_df_column_names_unique(df: pd.DataFrame) -> pd.DataFrame:
"""Make DataFrame column names unique by adding suffixes to duplicates.
This function iterates through the column names of the input DataFrame
and appends a suffix to duplicate column names to make them distinct.
The suffix is an underscore followed by an integer value representing
the number of occurrences of the column name.
Args:
df (pd.DataFrame): The input DataFrame with potentially duplicate
column names.
Returns:
pd.DataFrame: A DataFrame with unique column names where any
duplicate column names have been renamed with a suffix.
Examples:
::
import pandas as pd
# Sample DataFrame with duplicate column names
data = {
"A": [1, 2, 3],
"B": [4, 5, 6],
"A2": [7, 8, 9],
"C": [10, 11, 12],
}
df1 = pd.DataFrame(data)
df1.columns = ["A", "B", "A", "C"]
_make_df_column_names_unique(df1).to_dict()
# {'A': {0: 1, 1: 2, 2: 3},
# 'B': {0: 4, 1: 5, 2: 6},
# 'A_1': {0: 7, 1: 8, 2: 9},
# 'C': {0: 10, 1: 11, 2: 12}}
"""
# Check if all column names are unique
unique_columns = set(df.columns)
if len(unique_columns) == len(df.columns):
return df
# Else: fix duplicate column names
logger.warning(
"""Duplicate column names exists in the DataFrame.
A suffix will be added to them but their order might change from one iteration to another.
To avoid issues, make sure to change your original column names to be unique (and without special characters)."""
)
col_counts = {}
new_columns = []
for col in df.columns:
if col in col_counts:
col_counts[col] += 1
new_col_name = f"{col}_{col_counts[col]}"
logger.warning(
f"Column {col} already exists in the DataFrame, renaming it to be {new_col_name}"
)
else:
col_counts[col] = 0
new_col_name = col
new_columns.append(new_col_name)
df.columns = new_columns
return df
| balance-main | balance/util.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import logging
from typing import Optional
from balance.balancedf_class import ( # noqa
BalanceCovarsDF, # noqa
BalanceOutcomesDF, # noqa
BalanceWeightsDF, # noqa
)
from balance.datasets import load_data # noqa
from balance.sample_class import Sample # noqa
from balance.util import TruncationFormatter # noqa
# TODO: which objects do we want to explicitly externalize?
# TODO: verify this works.
global __version__
__version__ = "0.9.1"
def setup_logging(
logger_name: Optional[str] = __package__,
level: str = "INFO",
removeHandler: bool = True,
) -> logging.Logger:
"""
Initiates a nicely formatted logger called "balance", with level "info".
"""
if removeHandler:
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logger = logging.getLogger(logger_name)
logger.setLevel(getattr(logging, level))
formatter = TruncationFormatter(
"%(levelname)s (%(asctime)s) [%(module)s/%(funcName)s (line %(lineno)d)]: %(message)s"
)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
logger: logging.Logger = setup_logging()
logger.info(f"Using {__package__} version {__version__}")
# TODO: add example in the notebooks for using this function.
def set_warnings(level: str = "WARNING") -> None:
logger.setLevel(getattr(logging, level))
| balance-main | balance/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import annotations
import collections
import inspect
import logging
from copy import deepcopy
from typing import Callable, Dict, List, Literal, Optional, Union
import numpy as np
import pandas as pd
from balance import adjustment as balance_adjustment, util as balance_util
from balance.stats_and_plots import weights_stats
from balance.stats_and_plots.weighted_comparisons_stats import outcome_variance_ratio
from balance.typing import FilePathOrBuffer
from IPython.lib.display import FileLink
logger: logging.Logger = logging.getLogger(__package__)
class Sample:
"""
A class used to represent a sample.
Sample is the main object of balance. It contains a dataframe of unit's observations,
associated with id and weight.
Attributes
----------
id_column : pd.Series
a column representing the ids of the units in sample
weight_column : pd.Series
a column representing the weights of the units in sample
"""
# The following attributes are updated when initiating Sample using Sample.from_frame
_df = None
id_column = None
_outcome_columns = None
weight_column = None
_links = None
_adjustment_model = None
_df_dtypes = None
def __init__(self) -> None:
# The following checks if the call to Sample() was initiated inside the class itself using from_frame, or outside of it
# If the call was made internally, it will enable the creation of an instance of the class.
# This is used when from_frame calls `sample = Sample()`. Keeping the full stack allows this also to work by a child of Sample.
# If Sample() is called outside of the class structure, it will return the NotImplementedError error.
try:
calling_functions = [x.function for x in inspect.stack()]
except Exception:
raise NotImplementedError(
"cannot construct Sample class directly... yet (only by invoking Sample.from_frame(...)"
)
if "from_frame" not in calling_functions:
raise NotImplementedError(
"cannot construct Sample class directly... yet (only by invoking Sample.from_frame(...)"
)
pass
def __repr__(self: "Sample") -> str:
return (
f"({self.__class__.__module__}.{self.__class__.__qualname__})\n"
f"{self.__str__()}"
)
def __str__(self: "Sample", pkg_source: str = __package__) -> str:
is_adjusted = self.is_adjusted() * "Adjusted "
n_rows = self._df.shape[0]
n_variables = self._covar_columns().shape[1]
has_target = self.has_target() * " with target set"
adjustment_method = (
" using " + self.model()["method"] # pyre-ignore[16]
# (None is eliminated by if statement)
if self.model() is not None
else ""
)
variables = ",".join(self._covar_columns_names())
id_column_name = self.id_column.name if self.id_column is not None else "None"
weight_column_name = (
self.weight_column.name if self.weight_column is not None else "None"
)
outcome_column_names = (
",".join(self._outcome_columns.columns.tolist())
if self._outcome_columns is not None
else "None"
)
desc = f"""
{is_adjusted}{pkg_source} Sample object{has_target}{adjustment_method}
{n_rows} observations x {n_variables} variables: {variables}
id_column: {id_column_name}, weight_column: {weight_column_name},
outcome_columns: {outcome_column_names}
"""
if self.has_target():
common_variables = balance_util.choose_variables(
self, self._links["target"], variables=None
)
target_str = self._links["target"].__str__().replace("\n", "\n\t")
n_common = len(common_variables)
common_variables = ",".join(common_variables)
desc += f"""
target:
{target_str}
{n_common} common variables: {common_variables}
"""
return desc
################################################################################
# Public API
################################################################################
@classmethod
def from_frame(
cls: type["Sample"],
df: pd.DataFrame,
id_column: Optional[str] = None,
outcome_columns: Optional[Union[list, tuple, str]] = None,
weight_column: Optional[str] = None,
check_id_uniqueness: bool = True,
standardize_types: bool = True,
use_deepcopy: bool = True,
) -> "Sample":
"""
Create a new Sample object.
NOTE that all integer columns will be converted by defaults into floats. This behavior can be turned off
by setting standardize_types argument to False.
The reason this is done by default is because of missing value handling combined with balance current lack of support
for pandas Integer types:
1. Native numpy integers do not support missing values (NA), while pandas Integers do,
as well numpy floats. Also,
2. various functions in balance do not support pandas Integers, while they do support numpy floats.
3. Hence, since some columns might have missing values, the safest solution is to just convert all integers into numpy floats.
The id_column is stored as a string, even if the input is an integer.
Args:
df (pd.DataFrame): containing the sample's data
id_column (Optional, Optional[str]): the column of the df which contains the respondent's id
(should be unique). Defaults to None.
outcome_columns (Optional, Optional[Union[list, tuple, str]]): names of columns to treat as outcome
weight_column (Optional, Optional[str]): name of column to treat as weight. If not specified, will
be guessed (either "weight" or "weights"). If not found, a new column will be created ("weight") and filled with 1.0.
check_id_uniqueness (Optional, bool): Whether to check if ids are unique. Defaults to True.
standardize_types (Optional, bool): Whether to standardize types. Defaults to True.
Int64/int64 -> float64
Int32/int32 -> float64
string -> object
pandas.NA -> numpy.nan (within each cell)
This is slightly memory intensive (since it copies the data twice),
but helps keep various functions working for both Int64 and Int32 input columns.
use_deepcopy (Optional, bool): Whether to have a new df copy inside the sample object.
If False, then when the sample methods update the internal df then the original df will also be updated.
Defaults to True.
Returns:
Sample: a sample object
"""
# Inititate a Sample() class, inside a from_frame constructor
sample = cls()
sample._df_dtypes = df.dtypes
if use_deepcopy:
sample._df = deepcopy(df)
else:
sample._df = df
# id column
id_column = balance_util.guess_id_column(df, id_column)
if any(sample._df[id_column].isnull()):
raise ValueError("Null values are not allowed in the id_column")
if not set(map(type, sample._df[id_column].tolist())) == { # pyre-fixme[6] ???
str
}:
logger.warning("Casting id column to string")
sample._df.loc[:, id_column] = sample._df.loc[:, id_column].astype(str)
if (check_id_uniqueness) and (
sample._df[id_column].nunique() != len(sample._df[id_column])
):
raise ValueError("Values in the id_column must be unique")
sample.id_column = sample._df[id_column]
# TODO: in the future, if we could have all functions work with the original data types, that would be better.
if standardize_types:
# Move from some pandas Integer types to numpy float types.
# NOTE: The rationale is that while pandas integers support missing values,
# numpy float types do (storing it as np.nan).
# Furthermore, other functions in the package don't handle pandas Integer objects well, so
# they must be converted to numpy integers (if they have no missing values).
# But since we can't be sure that none of the various objects with the same column will not have NAs,
# we just convert them all to float (either 32 or 64).
# For more details, see: https://stackoverflow.com/a/53853351
# This line is after the id_column is set, so to make sure that the conversion happens after it is stored as a string.
# Move from Int64Dtype() to dtype('int64'):
# TODO: convert all numeric values (no matter what the original is) to "float64"?
# (Instead of mentioning all different types)
# using is_numeric_dtype: https://pandas.pydata.org/docs/reference/api/pandas.api.types.is_numeric_dtype.html?highlight=is_numeric_dtype#pandas.api.types.is_numeric_dtype
# Also, consider using
# https://pandas.pydata.org/docs/reference/api/pandas.api.types.is_string_dtype.html
# or https://pandas.pydata.org/docs/reference/api/pandas.api.types.is_object_dtype.html
# from non-numeric.
# e.d.: balance/util.py?lines=512.
# for x in df.columns:
# if (is_numeric_dtype(df[x])) and (not is_bool_dtype(df[x])):
# df[x] = df[x].astype("float64")
input_type = ["Int64", "Int32", "int64", "int32", "int16", "int8", "string"]
output_type = [
"float64",
"float32", # This changes Int32Dtype() into dtype('int32') (from pandas to numpy)
"float64",
"float32",
"float16",
"float16", # Using float16 since float8 doesn't exist, see: https://stackoverflow.com/a/40507235/256662
"object",
]
for i_input, i_output in zip(input_type, output_type):
sample._df = balance_util._pd_convert_all_types(
sample._df, i_input, i_output
)
# Replace any pandas.NA with numpy.nan:
sample._df = sample._df.fillna(np.nan)
balance_util._warn_of_df_dtypes_change(
sample._df_dtypes,
sample._df.dtypes,
"df",
"sample._df",
)
# weight column
if weight_column is None:
if "weight" in sample._df.columns:
logger.warning("Guessing weight column is 'weight'")
weight_column = "weight"
elif "weights" in sample._df.columns:
logger.warning("Guessing weight column is 'weights'")
weight_column = "weights"
else:
# TODO: The current default when weights are not available is "weight", while the method in balanceDF is called "weights",
# and the subclass is called BalanceWeightsDF (with and 's' at the end)
# In the future, it would be better to be more consistent and use the same name for all variations (e.g.: "weight").
# Unless, we move to use more weights columns, and this method could be used to get all of them.
logger.warning(
"No weights passed. Adding a 'weight' column and setting all values to 1"
)
weight_column = "weight"
sample._df.loc[:, weight_column] = 1
sample.weight_column = sample._df[weight_column]
# outcome columns
if outcome_columns is None:
sample._outcome_columns = None
else:
if isinstance(outcome_columns, str):
outcome_columns = [outcome_columns]
try:
sample._outcome_columns = sample._df.loc[:, outcome_columns]
except KeyError:
_all_columns = sample._df.columns.values.tolist()
raise ValueError(
f"outcome columns {outcome_columns} not in df columns {_all_columns}"
)
sample._links = collections.defaultdict(list)
return sample
####################
# Class base methods
####################
@property
def df(self: "Sample") -> pd.DataFrame:
"""Produce a DataFrame (of the self) from a Sample object.
Args:
self (Sample): Sample object.
Returns:
pd.DataFrame: with id_columns, and the df values of covars(), outcome() and weights() of the self in the Sample object.
"""
return pd.concat(
(
self.id_column,
self.covars().df if self.covars() is not None else None,
self.outcomes().df if self.outcomes() is not None else None,
self.weights().df if self.weights() is not None else None,
),
axis=1,
)
def outcomes(
self: "Sample",
): # -> "Optional[Type[BalanceOutcomesDF]]" (not imported due to circular dependency)
"""
Produce a BalanceOutcomeDF from a Sample object.
See :class:BalanceOutcomesDF.
Args:
self (Sample): Sample object.
Returns:
BalanceOutcomesDF or None
"""
if self._outcome_columns is not None:
# NOTE: must import here so to avoid circular dependency
from balance.balancedf_class import BalanceOutcomesDF
return BalanceOutcomesDF(self)
else:
return None
def weights(
self: "Sample",
): # -> "Optional[Type[BalanceWeightsDF]]" (not imported due to circular dependency)
"""
Produce a BalanceWeightsDF from a Sample object.
See :class:BalanceWeightsDF.
Args:
self (Sample): Sample object.
Returns:
BalanceWeightsDF
"""
# NOTE: must import here so to avoid circular dependency
from balance.balancedf_class import BalanceWeightsDF
return BalanceWeightsDF(self)
def covars(
self: "Sample",
): # -> "Optional[Type[BalanceCovarsDF]]" (not imported due to circular dependency)
"""
Produce a BalanceCovarsDF from a Sample object.
See :class:BalanceCovarsDF.
Args:
self (Sample): Sample object.
Returns:
BalanceCovarsDF
"""
# NOTE: must import here so to avoid circular dependency
from balance.balancedf_class import BalanceCovarsDF
return BalanceCovarsDF(self)
def model(
self: "Sample",
) -> Optional[Dict]:
"""
Returns the name of the model used to adjust Sample if adjusted.
Otherwise returns None.
Args:
self (Sample): Sample object.
Returns:
str or None: name of model used for adjusting Sample
"""
if hasattr(self, "_adjustment_model"):
return self._adjustment_model
else:
return None
def model_matrix(self: "Sample") -> pd.DataFrame:
"""
Returns the model matrix of sample using :func:`model_matrix`,
while adding na indicator for null values (see :func:`add_na_indicator`).
Returns:
pd.DataFrame: model matrix of sample
"""
res = balance_util.model_matrix(self, add_na=True)["sample"]
return res # pyre-ignore[7]: ["sample"] only chooses the DataFrame
############################################
# Adjusting and adapting weights of a sample
############################################
def adjust(
self: "Sample",
target: Optional["Sample"] = None,
method: Union[
Literal["cbps", "ipw", "null", "poststratify", "rake"], Callable
] = "ipw",
*args,
**kwargs,
) -> "Sample":
"""
Perform adjustment of one sample to match another.
This function returns a new sample.
Args:
target (Optional["Sample"]): Second sample object which should be matched.
If None, the set target of the object is used for matching.
method (str): method for adjustment: cbps, ipw, null, poststratify, rake
Returns:
Sample: an adjusted Sample object
"""
if target is None:
self._no_target_error()
target = self._links["target"]
new_sample = deepcopy(self)
if isinstance(method, str):
adjustment_function = balance_adjustment._find_adjustment_method(method)
elif callable(method):
adjustment_function = method
else:
raise ValueError("Method should be one of existing weighting methods")
adjusted = adjustment_function(
sample_df=self.covars().df,
sample_weights=self.weight_column,
target_df=target.covars().df,
target_weights=target.weight_column,
*args,
**kwargs,
)
new_sample.set_weights(adjusted["weight"])
new_sample._adjustment_model = adjusted["model"]
new_sample._links["unadjusted"] = self
new_sample._links["target"] = target
return new_sample
def set_weights(self, weights: Optional[Union[pd.Series, float]]) -> None:
"""
Adjusting the weights of a Sample object.
This will overwrite the weight_column of the Sample.
Note that the weights are assigned by index if weights is a pd.Series
(of Sample.df and weights series)
Args:
weights (Optional[Union[pd.Series, float]]): Series of weights to add to sample.
If None or float values, the same weight (or None) will be assigned to all units.
Returns:
None, but adapting the Sample weight column to weights
"""
if isinstance(weights, pd.Series):
if not all(idx in weights.index for idx in self.df.index):
logger.warning(
"""Note that not all Sample units will be assigned weights,
since weights are missing some of the indices in Sample.df"""
)
self._df.loc[:, self.weight_column.name] = weights
self.weight_column = self._df[self.weight_column.name]
####################################
# Handling links to other dataframes
####################################
def set_unadjusted(self, second_sample: "Sample") -> "Sample":
"""
Used to set the unadjusted link to Sample.
This is useful in case one wants to compare two samples.
Args:
second_sample (Sample): A second Sample to be set as unadjusted of Sample.
Returns:
Sample: a new copy of Sample with unadjusted link attached to the self object.
"""
if isinstance(second_sample, Sample):
newsample = deepcopy(self)
newsample._links["unadjusted"] = second_sample
return newsample
else:
raise TypeError(
"set_unadjusted must be called with second_sample argument of type Sample"
)
def is_adjusted(self) -> bool:
"""Check if a Sample object is adjusted and has target attached
Returns:
bool: whether the Sample is adjusted or not.
"""
return ("unadjusted" in self._links) and ("target" in self._links)
def set_target(self, target: "Sample") -> "Sample":
"""
Used to set the target linked to Sample.
Args:
target (Sample): A Sample object to be linked as target
Returns:
Sample: new copy of Sample with target link attached
"""
if isinstance(target, Sample):
newsample = deepcopy(self)
newsample._links["target"] = target
return newsample
else:
raise ValueError("A target, a Sample object, must be specified")
def has_target(self) -> bool:
"""
Check if a Sample object has target attached.
Returns:
bool: whether the Sample has target attached
"""
return "target" in self._links
##############################
# Metrics for adjusted samples
##############################
def covar_means(self: "Sample") -> pd.DataFrame:
"""
Compare the means of covariates (after using :func:`BalanceDF.model_matrix`) before and after adjustment as compared with target.
Args:
self (Sample): A Sample object produces after running :func:`Sample.adjust`.
It should include 3 components: "unadjusted", "adjusted", "target".
Returns:
pd.DataFrame: A DataFrame with 3 columns ("unadjusted", "adjusted", "target"),
and a row for each feature of the covariates.
The cells show the mean value. For categorical features, they are first transformed into the one-hot encoding.
For these columns, since they are all either 0 or 1, their means should be interpreted as proportions.
Examples:
::
from balance import Sample
import pandas as pd
s = Sample.from_frame(
pd.DataFrame(
{"a": (0, 1, 2), "c": ("a", "b", "c"), "o": (1,3,5), "id": (1, 2, 3)}
),
outcome_columns=("o"),
)
s_adjusted = s.set_target(s).adjust(method = 'null')
print(s_adjusted.covar_means())
# source unadjusted adjusted target
# a 1.000000 1.000000 1.000000
# c[a] 0.333333 0.333333 0.333333
# c[b] 0.333333 0.333333 0.333333
# c[c] 0.333333 0.333333 0.333333
"""
self._check_if_adjusted()
means = self.covars().mean()
means = (
means.rename(index={"self": "adjusted"})
.reindex(["unadjusted", "adjusted", "target"])
.transpose()
)
return means
def design_effect(self) -> np.float64:
"""
Return the design effect of the weights of Sample. Uses :func:`weights_stats.design_effect`.
Args:
self (Sample): A Sample object
Returns:
np.float64: Design effect
"""
return weights_stats.design_effect(self.weight_column)
def design_effect_prop(self) -> np.float64:
"""
Return the relative difference in design effect of the weights of the unadjusted sample and the adjusted sample.
I.e. (Deff of adjusted - Deff of unadjusted) / Deff of unadjusted.
Uses :func:`weights_stats.design_effect`.
Args:
self (Sample): A Sample object produces after running :func:`Sample.adjust`.
It should include 3 components: "unadjusted", "adjusted", "target".
Returns:
np.float64: relative difference in design effect.
"""
self._check_if_adjusted()
deff_unadjusted = self._links["unadjusted"].design_effect()
deff_adjusted = self.design_effect()
return (deff_adjusted - deff_unadjusted) / deff_unadjusted
# TODO: add unittest for this function
def plot_weight_density(self) -> None:
"""Plot the density of weights of Sample.
Examples:
::
import numpy as np
import pandas as pd
from balance.sample_class import Sample
np.random.seed(123)
df = pd.DataFrame(
{
"a": np.random.uniform(size=100),
"c": np.random.choice(
["a", "b", "c", "d"],
size=100,
replace=True,
p=[0.01, 0.04, 0.5, 0.45],
),
"id": range(100),
"weight": np.random.uniform(size=100) + 0.5,
}
)
a = Sample.from_frame(df)
sample.weights().plot()
# The same as:
sample.plot_weight_density()
"""
self.weights().plot()
##########################################
# Metrics for outcomes of adjusted samples
##########################################
def outcome_sd_prop(self) -> pd.Series:
"""
Return the difference in outcome weighted standard deviation (sd) of the unadjusted
sample and the adjusted sample, relative to the unadjusted weighted sd.
I.e. (weighted sd of adjusted - weighted sd of unadjusted) / weighted sd of unadjusted.
Uses :func:`BalanceDF.weighted_stats.weighted_sd`.
Args:
self (Sample): A Sample object produces after running :func:`Sample.adjust`.
It should include 3 components: "unadjusted", "adjusted", "target".
Returns:
pd.Series: (np.float64) relative difference in outcome weighted standard deviation.
"""
self._check_if_adjusted()
self._check_outcomes_exists()
outcome_std = self.outcomes().std()
adjusted_outcome_sd = outcome_std.loc["self"]
unadjusted_outcome_sd = outcome_std.loc["unadjusted"]
return (adjusted_outcome_sd - unadjusted_outcome_sd) / unadjusted_outcome_sd
def outcome_variance_ratio(self: "Sample") -> pd.Series:
"""The empirical ratio of variance of the outcomes before and after weighting.
See :func:`outcome_variance_ratio` for details.
Args:
self (Sample): A Sample object produces after running :func:`Sample.adjust`.
It should include 3 components: "unadjusted", "adjusted", "target".
Returns:
pd.Series: (np.float64) A series of calculated ratio of variances for each outcome.
"""
return outcome_variance_ratio(
self.outcomes().df,
self._links["unadjusted"].outcomes().df,
self.weights().df["weight"],
self._links["unadjusted"].weights().df["weight"],
)
# TODO: Add a method that plots the distribution of the outcome (adjusted v.s. unadjusted
# if adjusted, and only unadjusted otherwise)
##############################################
# Summary of metrics and diagnostics of Sample
##############################################
def summary(self) -> str:
"""
Provides a summary of covariate balance, design effect and model properties (if applicable)
of a sample.
For more details see: :func:`BalanceDF.asmd`, :func:`BalanceDF.asmd_improvement`
and :func:`weights_stats.design_effect`
Returns:
str: a summary description of properties of an adjusted sample.
"""
# asmd
if self.is_adjusted() or self.has_target():
asmd = self.covars().asmd()
n_asmd_covars = len(
asmd.columns.values[asmd.columns.values != "mean(asmd)"]
)
# asmd improvement
if self.is_adjusted():
asmd_before = asmd.loc["unadjusted", "mean(asmd)"]
asmd_improvement = 100 * self.covars().asmd_improvement()
if self.has_target():
asmd_now = asmd.loc["self", "mean(asmd)"]
# design effect
design_effect = self.design_effect()
# model performance
if self.model() is not None:
if (
self.model()["method"] # pyre-ignore[16]
# (None is eliminated by if statement)
== "ipw"
):
model_summary = (
"Model proportion deviance explained: {dev_exp:.3f}".format(
dev_exp=self.model()["perf"]["prop_dev_explained"][0]
)
)
else:
# TODO: add model performance for other types of models
model_summary = None
else:
model_summary = None
out = (
(
# pyre-fixme[61]: `asmd_improvement` is undefined, or not always
# defined.
f"Covar ASMD reduction: {asmd_improvement:.1f}%, design effect: {design_effect:.3f}\n"
if self.is_adjusted()
else ""
)
# pyre-fixme[61]: `n_asmd_covars` is undefined, or not always defined.
+ (f"Covar ASMD ({n_asmd_covars} variables): " if self.has_target() else "")
# pyre-fixme[61]: `asmd_before` is undefined, or not always defined.
+ (f"{asmd_before:.3f} -> " if self.is_adjusted() else "")
# pyre-fixme[61]: `asmd_now` is undefined, or not always defined.
+ (f"{asmd_now:.3f}\n" if self.has_target() else "")
+ (
f"Model performance: {model_summary}"
if (model_summary is not None)
else ""
)
)
return out
def diagnostics(self: "Sample") -> pd.DataFrame:
# TODO: mention the other diagnostics
# TODO: update/improve the wiki pages doc is linking to.
# TODO: move explanation on weights normalization to some external page
"""
Output a table of diagnostics about adjusted Sample object.
size
======================
All values in the "size" metrics are AFTER any rows/columns were filtered.
So, for example, if we use respondents from previous days but filter them for diagnostics purposes, then
sample_obs and target_obs will NOT include them in the counting. The same is true for sample_covars and target_covars.
In the "size" metrics we have the following 'var's:
- sample_obs - number of respondents
- sample_covars - number of covariates (main covars, before any transformations were used)
- target_obs - number of users used to represent the target pop
- target_covars - like sample_covars, but for target.
weights_diagnostics
======================
In the "weights_diagnostics" metric we have the following 'var's:
- design effect (de), effective sample size (n/de), effective sample ratio (1/de). See also:
- https://en.wikipedia.org/wiki/Design_effect
- https://en.wikipedia.org/wiki/Effective_sample_size
- sum
- describe of the (normalized to sample size) weights (mean, median, std, etc.)
- prop of the (normalized to sample size) weights that are below or above some numbers (1/2, 1, 2, etc.)
- nonparametric_skew and weighted_median_breakdown_point
Why is the diagnostics focused on weights normalized to sample size
-------------------------------------------------------------------
There are 3 well known normalizations of weights:
1. to sum to 1
2. to sum to target population
3. to sum to n (sample size)
Each one has their own merits:
1. is good if wanting to easily calculate avg of some response var (then we just use sum(w*y) and no need for /sum(w))
2. is good for sum of stuff. For example, how many people in the US use android? For this we'd like the weight of
each person to represent their share of the population and then we just sum the weights of the people who use android in the survey.
3. is good for understanding relative "importance" of a respondent as compared to the weights of others in the survey.
So if someone has a weight that is >1 it means that this respondent (conditional on their covariates) was 'rare' in the survey,
so the model we used decided to give them a larger weight to account for all the people like him/her that didn't answer.
For diagnostics purposes, option 3 is most useful for discussing the distribution of the weights
(e.g.: how many respondents got a weight >2 or smaller <0.5).
This is a method (standardized across surveys) to helping us identify how many of the respondents are "dominating"
and have a large influence on the conclusion we draw from the survey.
model_glance
======================
Properties of the model fitted, depends on the model used for weighting.
covariates ASMD
======================
Includes covariates ASMD before and after adjustment (per level of covariate and aggregated) and the ASMD improvement.
Args:
self (Sample): only after running an adjustment with Sample.adjust.
Returns:
pd.DataFrame: with 3 columns: ("metric", "val", "var"),
indicating various tracking metrics on the model.
"""
logger.info("Starting computation of diagnostics of the fitting")
self._check_if_adjusted()
diagnostics = pd.DataFrame(columns=("metric", "val", "var"))
# ----------------------------------------------------
# Properties of the Sample object (dimensions of the data)
# ----------------------------------------------------
n_sample_obs, n_sample_covars = self.covars().df.shape
n_target_obs, n_target_covars = self._links["target"].covars().df.shape
diagnostics = pd.concat(
(
diagnostics,
pd.DataFrame(
{
"metric": "size",
"val": [
n_sample_obs,
n_sample_covars,
n_target_obs,
n_target_covars,
],
"var": [
"sample_obs",
"sample_covars",
"target_obs",
"target_covars",
],
}
),
)
)
# ----------------------------------------------------
# Diagnostics on the weights
# ----------------------------------------------------
the_weights_summary = self.weights().summary()
# Add all the weights_diagnostics to diagnostics
diagnostics = pd.concat(
(
diagnostics,
pd.DataFrame(
{
"metric": "weights_diagnostics",
"val": the_weights_summary["val"],
"var": the_weights_summary["var"],
}
),
)
)
# ----------------------------------------------------
# Diagnostics on the model
# ----------------------------------------------------
model = self.model()
diagnostics = pd.concat(
(
diagnostics,
pd.DataFrame(
{
"metric": "adjustment_method",
"val": (0,),
"var": model["method"], # pyre-ignore[16]
# (None is eliminated by if statement)
}
),
)
)
if model["method"] == "ipw":
# Scalar values from 'perf' key of dictionary
fit_single_values = pd.concat(
[
pd.DataFrame({"metric": "model_glance", "val": v, "var": k})
for k, v in model["fit"].items()
if (isinstance(v, np.ndarray) and v.shape == (1,))
]
)
diagnostics = pd.concat((diagnostics, fit_single_values))
# Extract glmnet output about this regularisation parameter
lambda_ = model["lambda"]
lambda_index = model["fit"]["lambdau"] == lambda_
fit_values = pd.concat(
[
pd.DataFrame(
{"metric": "model_glance", "val": v[lambda_index], "var": k}
)
for k, v in self.model()["fit"].items()
if (isinstance(v, np.ndarray) and v.shape) == lambda_index.shape
]
)
diagnostics = pd.concat((diagnostics, fit_values))
# Scalar values from 'perf' key of dictionary
perf_single_values = pd.concat(
[
pd.DataFrame({"metric": "model_glance", "val": v, "var": k})
for k, v in model["perf"].items()
if (isinstance(v, np.ndarray) and v.shape == (1,))
]
)
diagnostics = pd.concat((diagnostics, perf_single_values))
# Model coefficients
coefs = (
model["perf"]["coefs"]
.reset_index()
.rename({0: "val", "index": "var"}, axis=1)
.assign(metric="model_coef")
)
diagnostics = pd.concat((diagnostics, coefs))
elif model["method"] == "cbps":
beta_opt = pd.DataFrame(
{"val": model["beta_optimal"], "var": model["X_matrix_columns"]}
).assign(metric="beta_optimal")
diagnostics = pd.concat((diagnostics, beta_opt))
metric = [
"rescale_initial_result",
"balance_optimize_result",
"gmm_optimize_result_glm_init",
"gmm_optimize_result_bal_init",
]
metric = [x for x in metric for _ in range(2)]
var = ["success", "message"] * 4
val = [model[x][y] for (x, y) in zip(metric, var)]
optimizations = pd.DataFrame({"metric": metric, "var": var, "val": val})
diagnostics = pd.concat((diagnostics, optimizations))
# TODO: add model diagnostics for other models
# ----------------------------------------------------
# Diagnostics on the covariates correction
# ----------------------------------------------------
asmds = self.covars().asmd()
# Per-covariate ASMDs
covar_asmds = (
asmds.transpose()
.rename(
{
"self": "covar_asmd_adjusted",
"unadjusted": "covar_asmd_unadjusted",
"unadjusted - self": "covar_asmd_improvement",
},
axis=1,
)
.reset_index()
.melt(id_vars="index")
.rename({"source": "metric", "value": "val", "index": "var"}, axis=1)
)
diagnostics = pd.concat((diagnostics, covar_asmds))
# Per-main-covariate ASMDs
asmds_main = self.covars().asmd(aggregate_by_main_covar=True)
covar_asmds_main = (
asmds_main.transpose()
.rename(
{
"self": "covar_main_asmd_adjusted",
"unadjusted": "covar_main_asmd_unadjusted",
"unadjusted - self": "covar_main_asmd_improvement",
},
axis=1,
)
.reset_index()
# TODO:
# column index name is different here.
# think again if that's the best default or not for
# asmd(aggregate_by_main_covar = True)
.rename({"main_covar_names": "index"}, axis=1)
.melt(id_vars="index")
.rename({"source": "metric", "value": "val", "index": "var"}, axis=1)
)
# sort covar_asmds_main to have mean(asmd) at the end of it (for when doing quick checks)
covar_asmds_main = (
covar_asmds_main.assign(
has_mean_asmd=(covar_asmds_main["var"] == "mean(asmd)")
)
.sort_values(by=["has_mean_asmd", "var"])
.drop(columns="has_mean_asmd")
)
diagnostics = pd.concat((diagnostics, covar_asmds_main))
# ----------------------------------------------------
# Diagnostics if there was an adjustment_failure
# ----------------------------------------------------
# This field is used in the cli and filled with an alternative value if needed.
diagnostics = pd.concat(
(
diagnostics,
pd.DataFrame({"metric": ("adjustment_failure",), "val": (0,)}),
)
)
diagnostics = diagnostics.reset_index(drop=True)
logger.info("Done computing diagnostics")
return diagnostics
############################################
# Column and rows modifiers - use carefully!
############################################
def keep_only_some_rows_columns(
self: "Sample",
rows_to_keep: Optional[str] = None,
columns_to_keep: Optional[List[str]] = None,
) -> "Sample":
# TODO: split this into two functions (one for rows and one for columns)
"""
This function returns a **copy** of the sample object
after removing ALL columns from _df and _links objects
(which includes unadjusted and target objects).
This function is useful when wanting to calculate metrics, such as ASMD, but only on some of the features,
or part of the observations.
Args:
self (Sample): a sample object (preferably after adjustment)
rows_to_keep (Optional[str], optional): A string with a condition to eval (on some of the columns).
This will run df.eval(rows_to_keep) which will return a pd.Series of bool by which
we will filter the Sample object.
This effects both the df of covars AND the weights column (weight_column)
AND the outcome column (_outcome_columns), AND the id_column column.
Input should be a boolean feature, or a condition such as: 'gender == "Female" & age >= 18'.
Defaults to None.
columns_to_keep (Optional[List[str]], optional): the covariates of interest.
Defaults to None, which returns all columns.
Returns:
Sample: A copy of the original object. If both rows and columns to keep are None,
returns the copied object unchanged.
If some are not None, will update - first the rows - then the columns.
This performs the transformation on both the sample's df and its linked dfs (unadjusted, target).
"""
if (rows_to_keep is None) and (columns_to_keep is None):
return self
# Let's make sure to not ruin our old object:
self = deepcopy(self)
if rows_to_keep is not None:
# let's filter the weights Series and then the df rows
ss = self.df.eval(rows_to_keep) # rows to keep after the subset # noqa
logger.info(
f"From self -> (rows_filtered/total_rows) = ({ss.sum()}/{len(ss)})"
)
# filter ids
self.id_column = self.id_column[ss]
# filter weights
self.weight_column = self.weight_column[ss]
# filter _df
self._df = self._df[ss]
# filter outcomes
if self._outcome_columns is not None:
self._outcome_columns = self._outcome_columns[ss]
# filter links
for k, v in self._links.items():
try:
ss = v.df.eval(rows_to_keep) # rows to keep after the subset # noqa
logger.info(
f"From {k} -> (rows_filtered/total_rows) = ({ss.sum()}/{len(ss)})"
)
v.id_column = v.id_column[ss]
v.weight_column = v.weight_column[ss]
v._df = v._df[ss]
if v._outcome_columns is not None:
v._outcome_columns = v._outcome_columns[ss]
except pd.core.computation.ops.UndefinedVariableError:
# This can happen, for example, if the row filtering condition depends somehow on a feature that is
# in the sample but not in the _links. For example, if filtering over one of the
# outcome variables, it would filter out these rows from sample, but it wouldn't have this column to
# use in target. So this is meant to capture that when this happens the function won't fail but simply
# report it to the user.
logger.warning(
f"couldn't filter _links['{k}'] using {rows_to_keep}"
)
if columns_to_keep is not None:
if not (set(columns_to_keep) <= set(self.df.columns)):
logger.warning(
"Note that not all columns_to_keep are in Sample. Only those exists are removed"
)
# let's remove columns...
self._df = self._df.loc[:, self._df.columns.isin(columns_to_keep)]
for v in self._links.values():
v._df = v._df.loc[:, v._df.columns.isin(columns_to_keep)]
return self
################
# Saving results
################
def to_download(self, tempdir: Optional[str] = None) -> FileLink:
"""Creates a downloadable link of the DataFrame of the Sample object.
File name starts with tmp_balance_out_, and some random file name (using :func:`uuid.uuid4`).
Args:
self (Sample): Object.
tempdir (Optional[str], optional): Defaults to None (which then uses a temporary folder using :func:`tempfile.gettempdir`).
Returns:
FileLink: Embedding a local file link in an IPython session, based on path. Using :func:FileLink.
"""
return balance_util._to_download(self.df, tempdir)
def to_csv(
self, path_or_buf: Optional[FilePathOrBuffer] = None, **kwargs
) -> Optional[str]:
"""Write df with ids from BalanceDF to a comma-separated values (csv) file.
Uses :func:`pd.DataFrame.to_csv`.
If an 'index' argument is not provided then it defaults to False.
Args:
self: Object.
path_or_buf (Optional[FilePathOrBuffer], optional): location where to save the csv.
Returns:
Optional[str]: If path_or_buf is None, returns the resulting csv format as a string. Otherwise returns None.
"""
if "index" not in kwargs:
kwargs["index"] = False
return self.df.to_csv(path_or_buf=path_or_buf, **kwargs)
################################################################################
# Private API
################################################################################
##################
# Column accessors
##################
def _special_columns_names(self: "Sample") -> List[str]:
"""
Returns names of all special columns (id column,
wegiht column and outcome columns) in Sample.
Returns:
List[str]: names of special columns
"""
return [
i.name for i in [self.id_column, self.weight_column] if i is not None
] + (
self._outcome_columns.columns.tolist()
if self._outcome_columns is not None
else []
)
def _special_columns(self: "Sample") -> pd.DataFrame:
"""
Returns dataframe of all special columns (id column,
weight column and outcome columns) in Sample.
Returns:
pd.DataFrame: special columns
"""
return self._df[self._special_columns_names()]
def _covar_columns_names(self: "Sample") -> List[str]:
"""
Returns names of all covars in Sample.
Returns:
List[str]: names of covars
"""
return [
c for c in self._df.columns.values if c not in self._special_columns_names()
]
def _covar_columns(self: "Sample") -> pd.DataFrame:
"""
Returns dataframe of all covars columns in Sample.
Returns:
pd.DataFrame: covars columns
"""
return self._df[self._covar_columns_names()]
################
# Errors checks
################
def _check_if_adjusted(self) -> None:
"""
Raises a ValueError if sample is not adjusted
"""
if not self.is_adjusted():
raise ValueError(
"This is not an adjusted Sample. Use sample.adjust to adjust the sample to target"
)
def _no_target_error(self: "Sample") -> None:
"""
Raises a ValueError if sample doesn't have target
"""
if not self.has_target():
raise ValueError(
"This Sample does not have a target set. Use sample.set_target to add target"
)
def _check_outcomes_exists(self) -> None:
"""
Raises a ValueError if sample doesn't have outcome_columns specified.
"""
if self.outcomes() is None:
raise ValueError("This Sample does not have outcome columns specified")
| balance-main | balance/sample_class.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import inspect
import logging
from argparse import ArgumentParser, FileType, Namespace
from typing import Dict, List, Optional, Tuple, Type, Union
import balance
import pandas as pd
from balance import __version__ # @manual
from balance.sample_class import Sample as balance_sample_cls # @manual
logger: logging.Logger = logging.getLogger(__package__)
class BalanceCLI:
def __init__(self, args) -> None:
self.args = args
# Create attributes (to be populated later, which will be used in main)
(
self._transformations,
self._formula,
self._penalty_factor,
self._one_hot_encoding,
self._max_de,
self._weight_trimming_mean_ratio,
self._sample_cls,
self._sample_package_name,
self._sample_package_version,
) = (None, None, None, None, None, None, None, None, None)
def check_input_columns(self, columns: Union[List[str], pd.Index]) -> None:
needed_columns = []
needed_columns.append(self.sample_column())
needed_columns.append(self.id_column())
needed_columns.append(self.weight_column())
needed_columns.extend(self.covariate_columns())
if self.has_batch_columns():
needed_columns.extend(self.batch_columns())
if self.has_keep_columns():
needed_columns.extend(self.keep_columns())
if self.has_keep_row_column():
needed_columns.append(self.keep_row_column())
for nc in needed_columns:
assert nc in columns, f"{nc} not in input colums"
# TODO: decide if to explicitly mention/check here the option of methods or not
def method(self) -> str:
return self.args.method
def sample_column(self) -> str:
return self.args.sample_column
def id_column(self) -> str:
return self.args.id_column
def weight_column(self) -> str:
return self.args.weight_column
def covariate_columns(self) -> str:
return self.args.covariate_columns.split(",")
def covariate_columns_for_diagnostics(self) -> List[str]:
out = self.args.covariate_columns_for_diagnostics
return None if out is None else out.split(",")
def rows_to_keep_for_diagnostics(self) -> str:
return self.args.rows_to_keep_for_diagnostics
def has_batch_columns(self) -> bool:
return self.args.batch_columns is not None
def batch_columns(self) -> str:
return self.args.batch_columns.split(",")
def has_keep_columns(self) -> bool:
return self.args.keep_columns is not None
def keep_columns(self): # TODO: figure out how to type hint this one.
if self.args.keep_columns:
return self.args.keep_columns.split(",")
def has_keep_row_column(self) -> bool:
return self.args.keep_row_column is not None
def keep_row_column(self) -> str:
return self.args.keep_row_column
def max_de(self) -> Optional[float]:
return self.args.max_de
def transformations(self) -> Optional[str]:
if (self.args.transformations is None) or (self.args.transformations == "None"):
return None
else:
return self.args.transformations
def formula(self) -> Optional[str]:
return self.args.formula
def one_hot_encoding(self) -> Optional[bool]:
return balance.util._true_false_str_to_bool(self.args.one_hot_encoding)
def standardize_types(self) -> bool:
return balance.util._true_false_str_to_bool(self.args.standardize_types)
def weight_trimming_mean_ratio(self) -> float:
return self.args.weight_trimming_mean_ratio
def split_sample(self, df: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame]:
in_sample = df[self.sample_column()] == 1
sample_df = df[in_sample]
target_df = df[~in_sample]
return sample_df, target_df
def process_batch(
self,
batch_df: pd.DataFrame,
transformations: Union[Dict, str, None] = "default",
formula=None,
penalty_factor=None,
one_hot_encoding: bool = False,
max_de: Optional[float] = 1.5,
weight_trimming_mean_ratio: float = 20,
sample_cls: Type[balance_sample_cls] = balance_sample_cls,
sample_package_name: str = __package__,
) -> Dict[str, pd.DataFrame]:
# TODO: add unit tests
sample_df, target_df = self.split_sample(batch_df)
if sample_df.shape[0] == 0:
return {
"adjusted": pd.DataFrame(),
"diagnostics": pd.DataFrame(
{
"metric": ("adjustment_failure", "adjustment_failure_reason"),
"var": (None, None),
"val": (1, "No input data"),
}
),
}
# Stuff everything that is not id, weight, or covariate into outcomes
outcome_columns = tuple(
set(batch_df.columns)
- {self.id_column(), self.weight_column()}
- set(self.covariate_columns())
)
# definitions for diagnostics
covariate_columns_for_diagnostics = self.covariate_columns_for_diagnostics()
rows_to_keep_for_diagnostics = self.rows_to_keep_for_diagnostics()
sample = sample_cls.from_frame(
sample_df,
id_column=self.id_column(),
weight_column=self.weight_column(),
outcome_columns=outcome_columns,
check_id_uniqueness=False,
standardize_types=self.standardize_types(),
)
logger.info("%s sample object: %s" % (sample_package_name, str(sample)))
target = sample_cls.from_frame(
target_df,
id_column=self.id_column(),
weight_column=self.weight_column(),
outcome_columns=outcome_columns,
check_id_uniqueness=False,
standardize_types=self.standardize_types(),
)
logger.info("%s target object: %s" % (sample_package_name, str(target)))
try:
adjusted = sample.set_target(target).adjust(
method=self.method(), # pyre-ignore[6] it gets str, but the function will verify internally if it's the str it should be.
transformations=transformations,
formula=formula,
penalty_factor=penalty_factor,
one_hot_encoding=one_hot_encoding,
max_de=max_de,
weight_trimming_mean_ratio=weight_trimming_mean_ratio,
)
logger.info("Succeeded with adjusting sample to target")
logger.info("%s adjusted object: %s" % (sample_package_name, str(adjusted)))
logger.info(
"Condition on which rows to keep for diagnostics: %s "
% rows_to_keep_for_diagnostics
)
logger.info(
"Names of columns to keep for diagnostics: %s "
% covariate_columns_for_diagnostics
)
diagnostics = adjusted.keep_only_some_rows_columns(
rows_to_keep=rows_to_keep_for_diagnostics,
columns_to_keep=covariate_columns_for_diagnostics,
).diagnostics()
logger.info(
"%s diagnostics object: %s" % (sample_package_name, str(diagnostics))
)
# Update dtypes
if self.args.return_df_with_original_dtypes:
df_to_return = balance.util._astype_in_df_from_dtypes(
adjusted.df, adjusted._df_dtypes
)
balance.util._warn_of_df_dtypes_change(
adjusted.df.dtypes,
df_to_return.dtypes,
"df_after_adjust",
"df_returned_by_the_cli",
)
else:
df_to_return = adjusted.df
rval = {"adjusted": df_to_return, "diagnostics": diagnostics}
except Exception as e:
if self.args.succeed_on_weighting_failure:
logger.error(
"Adjustment failed. Because '--succeed_on_weighting_failure' was set: returning empty weights."
)
sample.set_weights(None)
module = inspect.getmodule(inspect.trace()[-1][0])
module_name = module.__name__ if module is not None else None
error_message = f"{module_name}: {e}"
logger.exception("The error message is: " + error_message)
# Update dtypes
if self.args.return_df_with_original_dtypes:
df_to_return = balance.util._astype_in_df_from_dtypes(
sample.df, sample._df_dtypes
)
balance.util._warn_of_df_dtypes_change(
sample.df.dtypes,
df_to_return.dtypes,
"df_without_adjusting",
"df_returned_by_the_cli",
)
else:
df_to_return = sample.df
rval = {
"adjusted": df_to_return,
"diagnostics": pd.DataFrame(
{
"metric": (
"adjustment_failure",
"adjustment_failure_reason",
),
"var": (None, None),
"val": (1, error_message),
}
),
}
else:
raise e
return rval
def adapt_output(self, output_df: pd.DataFrame) -> pd.DataFrame:
"""Filter raw output dataframe to user's requested rows/columns.
- First we filter to the rows we are supposed to keep.
- Next we select the columns that need to be returned.
"""
if output_df.empty:
return output_df
if self.has_keep_row_column():
keep_rows = output_df[self.keep_row_column()] == 1
output_df = output_df[keep_rows]
if self.has_keep_columns():
output_df = output_df[ # pyre-ignore[9]: this uses the DataFrame also.
self.keep_columns()
]
return output_df
def load_and_check_input(self) -> pd.DataFrame:
# TODO: Add unit tests for function
# Load and check input
input_df = pd.read_csv(self.args.input_file, sep=self.args.sep_input_file)
logger.info("Number of rows in input file: %d" % input_df.shape[0])
if self.has_keep_row_column():
logger.info(
"Number of rows to keep in input file: %d"
% input_df[input_df[self.keep_row_column()] == 1].shape[0]
)
logger.info("Number of columns in input file: %d" % input_df.shape[1])
return input_df
def write_outputs(self, output_df, diagnostics_df) -> None:
# TODO: Add unit tests for function
# Write output
output_df.to_csv(
path_or_buf=self.args.output_file,
index=False,
header=(not self.args.no_output_header),
sep=self.args.sep_output_file,
)
self.args.output_file.close()
if self.args.diagnostics_output_file is not None:
diagnostics_df.to_csv(
path_or_buf=self.args.diagnostics_output_file,
index=False,
header=(not self.args.no_output_header),
sep=self.args.sep_diagnostics_output_file,
)
self.args.diagnostics_output_file.close()
def update_attributes_for_main_used_by_adjust(self) -> None:
"""
Prepares all the defaults for main to use.
"""
# TODO: future version might include conditional control over these attributes based on some input
transformations = self.transformations()
formula = self.formula()
penalty_factor = None
one_hot_encoding = self.one_hot_encoding()
max_de = self.max_de()
weight_trimming_mean_ratio = self.weight_trimming_mean_ratio()
sample_cls, sample_package_name, sample_package_version = (
balance_sample_cls,
__package__,
__version__,
)
# update all attributes (to be later used in main)
(
self._transformations,
self._formula,
self._penalty_factor,
self._one_hot_encoding,
self._max_de,
self._weight_trimming_mean_ratio,
self._sample_cls,
self._sample_package_name,
self._sample_package_version,
) = (
transformations,
formula,
penalty_factor,
one_hot_encoding,
max_de,
weight_trimming_mean_ratio,
sample_cls,
sample_package_name,
sample_package_version,
)
def main(self) -> None:
# update all the objects from self attributes
(
transformations,
formula,
penalty_factor,
one_hot_encoding,
max_de,
weight_trimming_mean_ratio,
sample_cls,
sample_package_name,
sample_package_version,
) = (
self._transformations,
self._formula,
self._penalty_factor,
self._one_hot_encoding,
self._max_de,
self._weight_trimming_mean_ratio,
self._sample_cls,
self._sample_package_name,
self._sample_package_version,
)
logger.info(
"Running cli.main() using %s version %s"
% (sample_package_name, sample_package_version)
)
# Logging arguments used by main:
keys = (
"transformations",
"formula",
"penalty_factor",
"one_hot_encoding",
"max_de",
"weight_trimming_mean_ratio",
"sample_cls",
"sample_package_name",
"sample_package_version",
)
values = (
transformations,
formula,
penalty_factor,
one_hot_encoding,
max_de,
weight_trimming_mean_ratio,
sample_cls,
sample_package_name,
sample_package_version,
)
main_config = dict(zip(keys, values))
logger.info("Attributes used by main() for running adjust: %s" % main_config)
# Load and check input
input_df = self.load_and_check_input()
self.check_input_columns(input_df.columns)
# Run process_batch on input_df, and adjustment arguments
if self.has_batch_columns():
results = []
diagnostics = []
for batch_name, batch_df in input_df.groupby(self.batch_columns()):
logger.info("Running weighting for batch = %s " % str(batch_name))
processed = self.process_batch(
batch_df,
transformations,
formula,
penalty_factor,
one_hot_encoding,
max_de,
weight_trimming_mean_ratio,
sample_cls,
sample_package_name,
)
results.append(processed["adjusted"])
diagnostics.append(processed["diagnostics"])
logger.info("Done processing batch %s" % str(batch_name))
if (len(results) == 0) and len(diagnostics) == 0:
output_df = pd.DataFrame()
diagnostics_df = pd.DataFrame()
else:
output_df = pd.concat(results)
diagnostics_df = pd.concat(diagnostics)
else:
processed = self.process_batch(
input_df,
transformations,
formula,
penalty_factor,
one_hot_encoding,
max_de,
weight_trimming_mean_ratio,
sample_cls,
sample_package_name,
)
output_df = processed["adjusted"]
diagnostics_df = processed["diagnostics"]
logger.info("Done fitting the model, writing output")
# Remove unneeded rows and columns
output_df = self.adapt_output(output_df)
# Write output
self.write_outputs(output_df, diagnostics_df)
def __del__(self) -> None:
for handle in [self.args.input_file, self.args.output_file]:
try:
handle.close()
except FileNotFoundError:
pass
def _float_or_none(value: Union[float, int, str, None]) -> Optional[float]:
"""Return a float (if float or int) or None if it's None or "None"
This is so as to be clear that some input returned type is float or None.
Args:
value (Union[float, int, str, None]): A value to be converted.
Returns:
Optional[float]: None or float.
"""
if (value is None) or (value == "None"):
return None
return float(value)
def add_arguments_to_parser(parser: ArgumentParser) -> ArgumentParser:
# TODO: add checks for validity of input (including None as input)
# TODO: add arguments for formula when used as a list and for penalty_factor
parser.add_argument(
"--input_file",
type=FileType("r"),
required=True,
help="Path to input sample/target",
)
parser.add_argument(
"--output_file",
type=FileType("w"),
required=True,
help="Path to write output weights",
)
parser.add_argument(
"--diagnostics_output_file",
type=FileType("w"),
required=False,
help="Path to write adjustment diagnostics",
)
parser.add_argument(
"--method", default="ipw", help="Method to use for weighting [default=ipw]"
)
parser.add_argument(
"--sample_column",
default="is_respondent",
help="Path to target population [default=is_respondent]",
)
parser.add_argument(
"--id_column",
default="id",
help="Column that identifies units [default=id]",
)
parser.add_argument(
"--weight_column",
default="weight",
help="Column that identifies weights of samples [default=weight]",
)
parser.add_argument(
"--covariate_columns", required=True, help="Set of columns used for adjustment"
)
parser.add_argument(
"--covariate_columns_for_diagnostics",
required=False,
default=None,
help="Set of columns used for diagnostics reporting (if not supplied the default is None, which means to use all columns from --covariate_columns)",
)
parser.add_argument(
"--rows_to_keep_for_diagnostics",
required=False,
default=None,
help="A string with a condition for filtering rows (to be used for diagnostics reporting). \
The condition should be based on the list of covariate_columns and result in a bool pd.Series \
(e.g.: 'is_married' or 'is_married & age >= 18', etc.) \
(if not supplied the default is None, which means to use all rows without filtering",
)
parser.add_argument(
"--batch_columns",
required=False,
help="Set of columns used to indicate batches of data",
)
parser.add_argument(
"--keep_columns",
type=str,
required=False,
help="Set of columns we include in the output csv file",
)
parser.add_argument(
"--keep_row_column",
type=str,
required=False,
help="Column indicating which rows we include in the output csv file",
)
parser.add_argument(
"--sep_input_file",
type=str,
required=False,
default=",",
help="A 1 character for indicating the delimiter for the output file. If not supplied it defaults to a comma (,)",
)
parser.add_argument(
"--sep_output_file",
type=str,
required=False,
default=",",
help="A 1 character for indicating the delimiter for the output file. If not supplied it defaults to a comma (,)",
)
parser.add_argument(
"--sep_diagnostics_output_file",
type=str,
required=False,
default=",",
help="A 1 character for indicating the delimiter for the diagnostics output file. If not supplied it defaults to a comma (,)",
)
parser.add_argument(
"--no_output_header",
default=False,
action="store_true",
help="Turn off header in the output csv file",
)
parser.add_argument(
"--succeed_on_weighting_failure",
action="store_true",
help=(
"If adjustment fails (e.g. because the input data has too few "
"rows), then do not fail, but instead return the input data with "
"all weights null"
),
)
parser.add_argument(
"--max_de",
type=_float_or_none,
required=False,
default=1.5,
help=(
"Upper bound for the design effect of the computed weights. "
"If not supplied it defaults to 1.5. If set to 'None', then it uses 'lambda_1se'. "
"Only used if method is ipw or CBPS."
),
)
parser.add_argument(
"--weight_trimming_mean_ratio",
type=_float_or_none,
required=False,
default=20.0,
help=(
"The ratio according to which weights are trimmed from above by mean(weights) * ratio. "
"Defaults to 20. "
"Used only for CBPS and ipw."
"For ipw this is only used if max_de is set to 'None',otherwise, the trimming ratio is chosen by the algorithm."
),
)
parser.add_argument(
"--one_hot_encoding",
type=str,
default="True",
required=False,
help=(
"Set the value of the one_hot_encoding parameter. Accepts a string with one a value of 'True' or 'False' (treats it as a bool). Default is 'True'"
),
)
# TODO: Ideally we would like transformations argument to be able to get three types of values: None (for no transformations),
# "default" for default transformations or a dictionary of transformations.
# However, as a first step I added the option for "default" (which is also the default) and None (for no transformations).
parser.add_argument(
"--transformations",
default="default",
required=False,
help=(
"Define the transformations for the covariates. Can be set to None for no transformations or"
"'default' for default transformations."
),
),
# TODO: we currently support only the option of a string formula (or None), not a list of formulas.
parser.add_argument(
"--formula",
default=None,
required=False,
help=(
"The formula of the model matrix (in ipw or cbps). If None (default), the formula will be setted to an additive formula using all the covariates."
),
)
parser.add_argument(
"--return_df_with_original_dtypes",
action="store_true",
help=(
"If the input table has unsupported column types (e.g.: int32), then when using Sample.from_frame it will be changed (e.g.: float32). "
"The returned df from the cli will use the transformed DataFrame. If this flag is used, then the cli will attempt to restore the original dtypes of the input table"
"before returning it."
"WARNING: sometimes the pd.astype command might lead to odd behaviors, so it is generally safer to NOT use this flag but to manually specify the desired dtypes in the input/output tables."
"For example, dealing with missing values could lead to many issues (e.g.: there is np.nan and pd.NA, and these do not play nicely with type conversions)"
),
)
parser.add_argument(
"--standardize_types",
type=str,
default="True",
required=False,
help=(
"Control the standardize_types argument in Sample.from_frame (which is used on the files read by the cli)"
"The default is True. It is generally not advised to use False since this step is needed to deal with converting input types that are not supported by various functions."
"For example, if a column of Int64 has pandas.NA, it could fail on various functions. Current default (True) will turn that column into float64"
"(the pandas.NA will be converted into numpy.nan)."
"Setting the current flag to 'False' might lead to failures. The advantage is that it would keep most columns dtype as is"
" (which might be helpful for some downstream operations that assume the output dtypes are the same as the input dtypes)."
"NOTE: regardless if this flag is set to true or false, the weight column will be turned into a float64 type anyway."
),
)
return parser
def make_parser() -> ArgumentParser:
parser = ArgumentParser()
parser = add_arguments_to_parser(parser)
return parser
if __name__ == "__main__":
parser: ArgumentParser = make_parser()
args: Namespace = parser.parse_args()
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
| balance-main | balance/cli.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import io
import re
import sys
import unittest
from contextlib import contextmanager
from typing import Any, Union
import numpy as np
import pandas as pd
def _assert_frame_equal_lazy(
x: pd.DataFrame, y: pd.DataFrame, lazy: bool = True
) -> None:
"""Wrapper around pd.testing.assert_frame_equal, which transforms the
dataframes to ignore some errors.
Ignores order of columns
Args:
x (pd.DataFrame): DataFrame to compare
y (pd.DataFrame): DataFrame to compare
lazy (bool, optional): Should Ignores be applied. Defaults to True.
Returns:
None.
"""
if lazy:
x = x.sort_index(axis=0).sort_index(axis=1)
y = y.sort_index(axis=0).sort_index(axis=1)
return pd.testing.assert_frame_equal(x, y)
def _assert_index_equal_lazy(x: pd.Index, y: pd.Index, lazy: bool = True) -> None:
"""
Wrapper around pd.testing.assert_index_equal which transforms the
dataindexs to ignore some errors.
Ignores:
- order of entries
Args:
x (pd.Index): Index to compare
y (pd.Index): Index to compare
lazy (bool, optional): Should Ignores be applied. Defaults to True.
"""
if lazy:
x = x.sort_values()
y = y.sort_values()
return pd.testing.assert_index_equal(x, y)
@contextmanager
def _capture_output():
redirect_out, redirect_err = io.StringIO(), io.StringIO()
original_out, original_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = redirect_out, redirect_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = original_out, original_err
class BalanceTestCase(unittest.TestCase):
# Some Warns
def assertIfWarns(self, callable, *args, **kwargs) -> None:
with self.assertLogs(level="NOTSET") as cm:
callable(*args, **kwargs)
self.assertTrue(len(cm.output) > 0, "No warning produced.")
def assertNotWarns(self, callable, *args, **kwargs) -> None:
output = None
try:
with self.assertLogs() as cm:
callable(*args, **kwargs)
output = cm
except AssertionError:
return
raise AssertionError(f"Warning produced {output.output}.")
def assertWarnsRegexp(self, regexp, callable, *args, **kwargs) -> None:
with self.assertLogs(level="NOTSET") as cm:
callable(*args, **kwargs)
self.assertTrue(
any((re.search(regexp, c) is not None) for c in cm.output),
f"Warning {cm.output} does not match regex {regexp}.",
)
def assertNotWarnsRegexp(self, regexp, callable, *args, **kwargs) -> None:
with self.assertLogs(level="NOTSET") as cm:
callable(*args, **kwargs)
self.assertFalse(
any((re.search(regexp, c) is not None) for c in cm.output),
f"Warning {cm.output} matches regex {regexp}.",
)
# Some Equal
def assertEqual(
self,
first: Union[np.ndarray, pd.DataFrame, pd.Index, pd.Series, Any],
second: Union[np.ndarray, pd.DataFrame, pd.Index, pd.Series, Any],
msg: Any = ...,
**kwargs,
) -> None:
"""
Check if first and second are equal.
Uses np.testing.assert_array_equal for np.ndarray,
_assert_frame_equal_lazy for pd.DataFrame,
assert_series_equal for pd.DataFrame,
_assert_index_equal_lazy for pd.Index,
or unittest.TestCase.assertEqual otherwise.
Args:
first (Union[np.ndarray, pd.DataFrame, pd.Index, pd.Series]): first element to compare.
second (Union[np.ndarray, pd.DataFrame, pd.Index, pd.Series]): second element to compare.
msg (Any, optional): The error message on failure.
"""
lazy: bool = kwargs.get("lazy", False)
if isinstance(first, np.ndarray) or isinstance(second, np.ndarray):
np.testing.assert_array_equal(first, second, **kwargs)
elif isinstance(first, pd.DataFrame) or isinstance(second, pd.DataFrame):
_assert_frame_equal_lazy(
first,
second,
lazy,
)
elif isinstance(first, pd.Series) or isinstance(second, pd.Series):
pd.testing.assert_series_equal(first, second)
elif isinstance(first, pd.Index) or isinstance(second, pd.Index):
_assert_index_equal_lazy(first, second, lazy)
else:
super().assertEqual(first, second, msg=msg, **kwargs)
# Some Prints
def assertPrints(self, callable, *args, **kwargs) -> None:
with _capture_output() as (out, err):
callable(*args, **kwargs)
out, err = out.getvalue(), err.getvalue()
self.assertTrue((len(out) + len(err)) > 0, "No printed output.")
def assertNotPrints(self, callable, *args, **kwargs) -> None:
with _capture_output() as (out, err):
callable(*args, **kwargs)
out, err = out.getvalue(), err.getvalue()
self.assertTrue(
(len(out) + len(err)) == 0,
f"Printed output is longer than 0: {(out, err)}.",
)
def assertPrintsRegexp(self, regexp, callable, *args, **kwargs) -> None:
with _capture_output() as (out, err):
callable(*args, **kwargs)
out, err = out.getvalue(), err.getvalue()
self.assertTrue(
any((re.search(regexp, o) is not None) for o in (out, err)),
f"Printed output {(out, err)} does not match regex {regexp}.",
)
def assertNotPrintsRegexp(self, regexp, callable, *args, **kwargs) -> None:
with _capture_output() as (out, err):
callable(*args, **kwargs)
out, err = out.getvalue(), err.getvalue()
self.assertFalse(
any((re.search(regexp, o) is not None) for o in (out, err)),
f"Printed output {(out, err)} matches regex {regexp}.",
)
| balance-main | balance/testutil.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# LICENSE file in the root directory of this source tree.
from pathlib import Path
from typing import AnyStr, IO, Union
FilePathOrBuffer = Union[str, Path, IO[AnyStr]]
| balance-main | balance/typing.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from typing import Callable, Dict, List, Literal, Tuple, Union
import numpy as np
import pandas as pd
import scipy
from balance import util as balance_util
from balance.weighting_methods import (
adjust_null as balance_adjust_null,
cbps as balance_cbps,
ipw as balance_ipw,
poststratify as balance_poststratify,
rake as balance_rake,
)
from pandas.api.types import is_bool_dtype, is_numeric_dtype
logger: logging.Logger = logging.getLogger(__package__)
BALANCE_WEIGHTING_METHODS = {
"ipw": balance_ipw.ipw,
"cbps": balance_cbps.cbps,
"null": balance_adjust_null.adjust_null,
"poststratify": balance_poststratify.poststratify,
"rake": balance_rake.rake,
}
def trim_weights(
weights: Union[pd.Series, np.ndarray],
# TODO: add support to more types of input weights? (e.g. list? other?)
weight_trimming_mean_ratio: Union[float, int, None] = None,
weight_trimming_percentile: Union[float, None] = None,
verbose: bool = False,
keep_sum_of_weights: bool = True,
) -> pd.Series:
"""Trim extreme weights.
The user cannot supply both weight_trimming_mean_ratio and weight_trimming_percentile.
If none are supplied, the original weights are returned.
If weight_trimming_mean_ratio is not none, the weights are trimmed from above by
mean(weights) * ratio. The weights are then normalized to have the original mean.
Note that trimmed weights aren't actually bounded by trimming.ratio because the
reduced weight is redistributed to arrive at the original mean
Note that weight_trimming_percentile clips both sides of the distribution, unlike
trimming that only trims the weights from above.
For example, `weight_trimming_percentile=0.1` trims below the 10th percentile
AND above the 90th. If you only want to trim the upper side, specify
`weight_trimming_percentile = (0, 0.9)`.
Args:
weights (Union[pd.Series, np.ndarray]): pd.Series of weights to trim. np.ndarray will be turned into pd.Series) of weights.
weight_trimming_mean_ratio (Union[float, int], optional): indicating the ratio from above according to which
the weights are trimmed by mean(weights) * ratio. Defaults to None.
weight_trimming_percentile (Union[float], optional): if weight_trimming_percentile is not none,
then we apply winsorization using :func:`scipy.stats.mstats.winsorize`.
See also: [https://en.wikipedia.org/wiki/Winsorizing].
Defaults to None.
verbose (bool, optional): whether to add to logger printout of trimming process.
Defaults to False.
keep_sum_of_weights (bool, optional): Set if the sum of weights after trimming
should be the same as the sum of weights before trimming.
Defaults to True.
Raises:
TypeError: If weights is not np.array or pd.Series.
ValueError: If both weight_trimming_mean_ratio and weight_trimming_percentile are set.
Returns:
pd.Series (of type float64): Trimmed weights
Examples:
::
import pandas as pd
from balance.adjustment import trim_weights
print(trim_weights(pd.Series([1,2,3,40]), weight_trimming_mean_ratio = None))
# 0 1.0
# 1 2.0
# 2 3.0
# 3 40.0
# dtype: float64
print(trim_weights(pd.Series([1,2,3,40]), weight_trimming_mean_ratio = 2))
# 0 1.586207
# 1 3.172414
# 2 4.758621
# 3 36.482759
# dtype: float64
"""
if isinstance(weights, pd.Series):
pass
elif isinstance(weights, np.ndarray):
weights = pd.Series(weights)
else:
raise TypeError(
f"weights must be np.array or pd.Series, are of type: {type(weights)}"
)
if (weight_trimming_mean_ratio is not None) and (
weight_trimming_percentile is not None
):
raise ValueError(
"Only one of weight_trimming_mean_ratio and "
"weight_trimming_percentile can be set"
)
original_mean = np.mean(weights)
if weight_trimming_mean_ratio is not None:
max_val = weight_trimming_mean_ratio * original_mean
percent_trimmed = weights[weights > max_val].count() / weights.count()
weights = weights.clip(upper=max_val)
if verbose:
if percent_trimmed > 0:
logger.debug("Clipping weights to %s (before renormalizing)" % max_val)
logger.debug("Clipped %s of the weights" % percent_trimmed)
else:
logger.debug("No extreme weights were trimmed")
elif weight_trimming_percentile is not None:
# Winsorize
weights = scipy.stats.mstats.winsorize(
weights, limits=weight_trimming_percentile, inplace=False
)
if verbose:
logger.debug(
"Winsorizing weights to %s percentile" % str(weight_trimming_percentile)
)
if keep_sum_of_weights:
weights = weights / np.mean(weights) * original_mean
return weights
def default_transformations(
dfs: Union[Tuple[pd.DataFrame, ...], List[pd.DataFrame]]
) -> Dict[str, Callable]:
"""
Apply default transformations to dfs, i.e.
quantize to numeric columns and fct_lump to non-numeric and boolean
Args:
dfs (Union[Tuple[pd.DataFrame, ...], List[pd.DataFrame]]): A list or tuple of dataframes
Returns:
Dict[str, Callable]: Dict of transformations
"""
dtypes = {}
for d in dfs:
dtypes.update(d.dtypes.to_dict())
transformations = {}
for k, v in dtypes.items():
# Notice that in pandas: pd.api.types.is_numeric_dtype(pd.Series([True, False])) == True
# Hence, we need to explicitly check that not is_bool_dtype(v)
# see: https://github.com/pandas-dev/pandas/issues/38378
if (is_numeric_dtype(v)) and (not is_bool_dtype(v)):
transformations[k] = balance_util.quantize
else:
transformations[k] = balance_util.fct_lump
return transformations
def apply_transformations(
dfs: Tuple[pd.DataFrame, ...],
transformations: Union[Dict[str, Callable], str, None],
drop: bool = True,
) -> Tuple[pd.DataFrame, ...]:
"""Apply the transformations specified in transformations to all of the dfs
- if a column specified in `transformations` does not exist in the dataframes,
it is added
- if a column is not specified in `transformations`, it is dropped,
unless drop==False
- the dfs are concatenated together before transformations are applied,
so functions like `max` are relative to the column in all dfs
- Cannot transform the same variable twice, or add a variable and then transform it
(i.e. the definition of the added variable should include the transformation)
- if you get a cryptic error about mismatched data types, make sure your
transformations are not being treated as additions because of missing
columns (use `_set_warnings("DEBUG")` to check)
Args:
dfs (Tuple[pd.DataFrame, ...]): The DataFrames on which to operate
transformations (Union[Dict[str, Callable], str, None]): Mapping from column name to function to apply.
Transformations of existing columns should be specified as functions
of those columns (e.g. `lambda x: x*2`), whereas additions of new
columns should be specified as functions of the DataFrame
(e.g. `lambda x: x.column_a + x.column_b`).
drop (bool, optional): Whether to drop columns which are
not specified in `transformations`. Defaults to True.
Raises:
NotImplementedError: When passing an unknown "transformations" argument.
Returns:
Tuple[pd.DataFrame, ...]: tuple of pd.DataFrames
Examples:
::
from balance.adjustment import apply_transformations
import pandas as pd
import numpy as np
apply_transformations(
(pd.DataFrame({'d': [1, 2, 3], 'e': [4, 5, 6]}),),
{'d': lambda x: x*2, 'f': lambda x: x.d+x.e}
)
# ( f d
# 0 5 2
# 1 7 4
# 2 9 6,)
"""
# TODO: change assert to raise
assert isinstance(dfs, tuple), "'dfs' argument must be a tuple of DataFrames"
assert all(
isinstance(x, pd.DataFrame) for x in dfs
), "'dfs' must contain DataFrames"
if transformations is None:
return dfs
elif isinstance(transformations, str):
if transformations == "default":
transformations = default_transformations(dfs)
else:
raise NotImplementedError(f"Unknown transformations {transformations}")
ns = [0] + list(np.cumsum([x.shape[0] for x in dfs]))
boundaries = [(ns[i], ns[i + 1]) for i in range(0, len(ns) - 1)]
indices = [x.index for x in dfs]
all_data = pd.concat(dfs).reset_index(drop=True)
# This is to avoid issues with trnasformations that cannot
# be done on object with duplicate indecies
# additions is new columns to add to data. i.e.: column names that appear in transformations
# but are not present in all_data.
additions = {k: v for k, v in transformations.items() if k not in all_data.columns}
transformations = {
k: v for k, v in transformations.items() if k in all_data.columns
}
logger.info(f"Adding the variables: {list(additions.keys())}")
logger.info(f"Transforming the variables: {list(transformations.keys())}")
logger.debug(
f"Total number of added or transformed variables: {len(additions) + len(transformations)}"
)
# TODO: change assert to raise
assert (
len(additions) + len(transformations)
) > 0, "No transformations or additions passed"
if len(additions) > 0:
added = all_data.assign(**additions).loc[:, list(additions.keys())]
else:
added = None
if len(transformations) > 0:
# NOTE: .copy(deep=False) is used to avoid a false alarm that sometimes happen.
# When we take a slice of the DataFrame (all_data[k]), it is passed to a function
# inside v from transformations (e.g.: fct_lump), it would then sometimes raise:
# SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
# Adding .copy(deep=False) solves this.
# See: https://stackoverflow.com/a/54914752
transformed = pd.DataFrame(
{k: v(all_data.copy(deep=False)[k]) for k, v in transformations.items()}
)
else:
transformed = None
out = pd.concat((added, transformed), axis=1)
dropped_columns = list(set(all_data.columns.values) - set(out.columns.values))
if len(dropped_columns) > 0:
if drop:
logger.warning(f"Dropping the variables: {dropped_columns}")
else:
out = pd.concat((out, all_data.loc[:, dropped_columns]), axis=1)
logger.info(f"Final variables in output: {list(out.columns)}")
for column in out:
logger.debug(
f"Frequency table of column {column}:\n{out[column].value_counts(dropna=False)}"
)
logger.debug(
f"Number of levels of column {column}:\n{out[column].nunique(dropna=False)}"
)
res = tuple(out[i:j] for (i, j) in boundaries)
res = tuple(x.set_index(i) for x, i in zip(res, indices))
return res
def _find_adjustment_method(
method: Literal["cbps", "ipw", "null", "poststratify", "rake"],
WEIGHTING_METHODS: Dict[str, Callable] = BALANCE_WEIGHTING_METHODS,
) -> Callable:
"""This function translates a string method argument to the function itself.
Args:
method (Literal["cbps", "ipw", "null", "poststratify", "rake"]): method for adjustment: cbps, ipw, null, poststratify
WEIGHTING_METHODS (Dict[str, Callable]): A dict where keys are strings of function names, and the values are
the functions themselves.
Returns:
Callable: The function for adjustment
"""
if method in WEIGHTING_METHODS.keys():
adjustment_function = WEIGHTING_METHODS[method]
else:
raise ValueError(f"Unknown adjustment method: '{method}'")
return adjustment_function
| balance-main | balance/adjustment.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import pathlib
from typing import Literal, Optional, Tuple
import numpy as np
import pandas as pd
# TODO: move the functions from datasets/__init__.py to some other file (e.g.: datasets/loading_data.py),
# and then import the functions from that file in the init file (so the behavior would remain the same)
# TODO: add tests
def load_sim_data(
version: str = "01",
) -> Tuple[Optional[pd.DataFrame], Optional[pd.DataFrame]]:
"""Load simulated data for target and sample of interest
Version 01 returns two dataframes containing the columns gender ("Male", "Female" and nan),
age_group ("18-24", "25-34", "35-44", "45+"), income (some numbers from a normal distribution), and id.
The sample_df also has a column called happiness with a value from 0 to 100 that depends on the covariates.
The target_df DataFrame has 10000 rows, and sample_df has 1000 rows.
The sample_df is imbalanced when compared to target_df, as is demonstrated in the examples/tutorials.
If you want to see how this works, you can import balance and run this code:
import inspect
import balance
print(inspect.getsource(balance.datasets.load_sim_data))
Args:
version (str, optional): The version of simulated data. Currently available is only "01". Defaults to "01".
Returns:
Tuple[pd.DataFrame, pd.DataFrame]: Two DataFrames containing simulated data for the target and sample of interest.
"""
def _create_outcome_happiness(df, n):
# females are happier
# older people are happier
# people with higher income are happier
out = (
np.random.normal(40, 10, size=n)
+ np.where(df.gender == "Female", 1, 0) * np.random.normal(20, 1, size=n)
+ np.where(df.age_group == "35-44", 1, 0) * np.random.normal(5, 1, size=n)
+ np.where(df.age_group == "45+", 1, 0) * np.random.normal(20, 1, size=n)
+ np.random.normal((np.random.normal(3, 2, size=n) ** 2) / 20, 1, size=n)
)
# Truncate for max to be 100
out = np.where(out < 100, out, 100)
return out
if version == "01":
np.random.seed(2022 - 11 - 8) # for reproducibility
n_target = 10000
target_df = pd.DataFrame(
{
"id": (np.array(range(n_target)) + 100000).astype(str),
"gender": np.random.choice(
["Male", "Female"], size=n_target, replace=True, p=[0.5, 0.5]
),
"age_group": np.random.choice(
["18-24", "25-34", "35-44", "45+"],
size=n_target,
replace=True,
p=[0.20, 0.30, 0.30, 0.20],
),
"income": np.random.normal(3, 2, size=n_target) ** 2,
# "unrelated_variable": np.random.uniform(size = n_target),
# "weight": np.random.uniform(size = n_target) + 0.5,
}
)
target_df["happiness"] = _create_outcome_happiness(target_df, n_target)
# We also have missing values in gender
target_df.loc[3:900, "gender"] = np.nan
np.random.seed(2023 - 5 - 14) # for reproducibility
n_sample = 1000
sample_df = pd.DataFrame(
{
"id": (np.array(range(n_sample))).astype(str),
"gender": np.random.choice(
["Male", "Female"], size=n_sample, replace=True, p=[0.7, 0.3]
),
"age_group": np.random.choice(
["18-24", "25-34", "35-44", "45+"],
size=n_sample,
replace=True,
p=[0.50, 0.30, 0.15, 0.05],
),
"income": np.random.normal(2, 1.5, size=n_sample) ** 2,
# "unrelated_variable": np.random.uniform(size = n_sample),
# "weight": np.random.uniform(size = n_sample) + 0.5,
}
)
sample_df["happiness"] = _create_outcome_happiness(sample_df, n_sample)
# We also have missing values in gender
sample_df.loc[3:90, "gender"] = np.nan
return target_df, sample_df
return None, None
# TODO: add tests
def load_cbps_data() -> Tuple[Optional[pd.DataFrame], Optional[pd.DataFrame]]:
"""Load simulated data for CBPS comparison with R
The code in balance that implements CBPS attempts to mimic the code from the R package CBPS (https://cran.r-project.org/web/packages/CBPS/).
In the help page of the CBPS function in R (i.e.: `?CBPS::CBPS`) there is a simulated dataset that is used to showcase the CBPS function.
The output of that simulated dataset is saved in balance in order to allow for comparison of `balance` (Python) with `CBPS` (R).
You can view the structure of the simulated dataset by looking at the example below.
In the original simulation dataset (available in sim_data_cbps.csv), when the `treat` variable is 0, the row belongs to sample.
And when the `treat` variable is 1, the row belongs to target.
Returns:
Tuple[Optional[pd.DataFrame], Optional[pd.DataFrame]]: Two DataFrames containing simulated data for the target and sample of interest.
Example:
::
import balance
target_df, sample_df = balance.datasets.load_data("sim_data_cbps")
print(target_df.head())
# X1 X2 X3 X4 cbps_weights y id
# 1 0.723769 9.911956 0.189488 383.759778 0.003937 199.817495 2
# 3 0.347071 9.907768 0.096706 399.366071 0.003937 174.685348 4
# 11 0.691174 10.725262 0.214618 398.313184 0.003937 189.578368 12
# 12 0.779949 9.562130 0.181408 370.178863 0.003937 208.178724 13
# 13 0.818348 9.801834 0.210592 434.453795 0.003937 214.277306 14
print(target_df.info())
# <class 'pandas.core.frame.DataFrame'>
# Int64Index: 254 entries, 1 to 498
# Data columns (total 7 columns):
# # Column Non-Null Count Dtype
# --- ------ -------------- -----
# 0 X1 254 non-null float64
# 1 X2 254 non-null float64
# 2 X3 254 non-null float64
# 3 X4 254 non-null float64
# 4 cbps_weights 254 non-null float64
# 5 y 254 non-null float64
# 6 id 254 non-null int64
# dtypes: float64(6), int64(1)
# memory usage: 15.9 KB
"""
# NOTE: the reason we use __file__ and not importlib.resources is because the later one changed API in Python 3.11.
# so in order to be compliant with 3.7-3.10 and also 3.11, using __file__ is the safer option.
df_all = pd.read_csv(pathlib.Path(__file__).parent.joinpath("sim_data_cbps.csv"))
target_df = df_all[df_all.treat == 1].drop(["treat"], 1)
sample_df = df_all[df_all.treat == 0].drop(["treat"], 1)
return (target_df, sample_df)
def load_data(
source: Literal["sim_data_01", "sim_data_cbps"] = "sim_data_01",
) -> Tuple[Optional[pd.DataFrame], Optional[pd.DataFrame]]:
"""Returns a tuple of two DataFrames containing simulated data.
To learn more about each dataset, please refer to their help pages:
- sim_data_01: :func:`balance.datasets.load_sim_data`.
- sim_data_cbps: :func:`balance.datasets.load_cbps_data`.
Args:
source (Literal["sim_data_01", "sim_data_cbps"]): The name of the data to return. Defaults to "sim_data_01".
Returns:
Tuple[pd.DataFrame, pd.DataFrame]: The first dataframe contains simulated data of the "target" and the second dataframe contains simulated data of the "sample".
"""
if source == "sim_data_01":
target_df, sample_df = load_sim_data("01")
return (target_df, sample_df)
elif source == "sim_data_cbps":
target_df, sample_df = load_cbps_data()
return (target_df, sample_df)
return None, None
| balance-main | balance/datasets/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from typing import Optional
import pandas as pd
def relative_response_rates(
df: pd.DataFrame,
df_target: Optional[pd.DataFrame] = None,
per_column: bool = True,
) -> pd.DataFrame:
"""Produces a summary table of number of responses and proportion of completed responses.
Args:
df (pd.DataFrame): A DataFrame to calculate aggregated response rates for.
df_target (Optional[pd.DataFrame], optional): Defaults to None.
Determines what is the denominator from which notnull are a fraction of.
If None - it's the number of rows in df.
If some df is provided - then it is assumed that df is a subset of df_target, and the
response rate is calculated as the fraction of notnull values in df from (divided by)
the number of notnull values in df_target.
per_column (bool, optional): Default is True.
The per_column argument is relevant only if df_target is other than None (i.e.: trying to compare df to some df_target).
If per_column is True (default) - it indicates that the relative response rates of columns in df will be
by comparing each column in df to the same column in target.
If this is True, the columns in df and df_target must be identical.
If per_column is False then df is compared to the overall number of nonnull rows in the target df.
Returns:
pd.DataFrame: A column per column in the original df, and two rows:
One row with number of non-null observations, and
A second row with the proportion of non-null observations.
Examples:
::
import numpy as np
import pandas as pd
from balance.stats_and_plots.general_stats import relative_response_rates
df = pd.DataFrame({"o1": (7, 8, 9, 10), "o2": (7, 8, 9, np.nan), "id": (1, 2, 3, 4)})
relative_response_rates(df).to_dict()
# {'o1': {'n': 4.0, '%': 100.0},
# 'o2': {'n': 3.0, '%': 75.0},
# 'id': {'n': 4.0, '%': 100.0}}
df_target = pd.concat([df, df])
relative_response_rates(df, df_target).to_dict()
# {'o1': {'n': 4.0, '%': 50.0},
# 'o2': {'n': 3.0, '%': 50.0},
# 'id': {'n': 4.0, '%': 50.0}}
# Dividing by number of total notnull rows in df_rarget
df_target.notnull().all(axis=1).sum() # == 6
relative_response_rates(df, df_target, False).to_dict()
# {'o1': {'n': 4.0, '%': 66.66666666666666},
# 'o2': {'n': 3.0, '%': 50.0},
# 'id': {'n': 4.0, '%': 66.66666666666666}}
"""
df_n_notnull_rows = df.notnull().sum()
if df_target is None:
target_n_notnull_rows = df.shape[0]
elif per_column: # number of notnull rows, *per column*, in df_target
# verify that the columns of df and df_target are identical:
if (len(df.columns) != len(df_target.columns)) or (
df.columns.tolist() != df_target.columns.tolist()
):
raise ValueError(
f"""
df and df_target must have the exact same columns.
Instead, thes column names are, (df, df_target) = ({df.columns.tolist()}, {df_target.columns.tolist()})
"""
)
# If they are, we can proceed forward:
target_n_notnull_rows = df_target.notnull().sum()
else: # number of notnull *rows* (i.e.: complete rows) in df_target
target_n_notnull_rows = df_target.notnull().all(axis=1).sum()
if any(df_n_notnull_rows > target_n_notnull_rows):
raise ValueError(
f"""
The number of (notnull) rows in df MUST be smaller or equal to the number of rows in df_target.
These were, (df_n_notnull_rows, target_n_notnull_rows) = ({df_n_notnull_rows}, {target_n_notnull_rows})
"""
)
return pd.DataFrame(
{
"n": df_n_notnull_rows,
"%": 100 * (df_n_notnull_rows / target_n_notnull_rows),
}
).transpose()
| balance-main | balance/stats_and_plots/general_stats.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import collections
import logging
import re
from typing import List, Literal, Union
import numpy as np
import pandas as pd
from balance.stats_and_plots.weighted_stats import (
descriptive_stats,
weighted_mean,
weighted_var,
)
from balance.stats_and_plots.weights_stats import _check_weights_are_valid
logger: logging.Logger = logging.getLogger(__package__)
# TODO: add?
# from scipy.stats import wasserstein_distance
##########################################
# Weighted comparisons - functions to compare one or two data sources with one or two sources of weights
##########################################
# TODO: fix the r_indicator function. The current implementation is broken since it
# seems to wrongly estimate N.
# This seems to attempt to reproduce equation 2.2.2, in page 5 in
# "Indicators for the representativeness of survey response"
# by Jelke Bethlehem, Fannie Cobben, and Barry Schouten
# See pdf: https://www150.statcan.gc.ca/n1/en/pub/11-522-x/2008000/article/10976-eng.pdf?st=Zi4d4zld
# From: https://www150.statcan.gc.ca/n1/pub/11-522-x/2008000/article/10976-eng.pdf
# def r_indicator(sample_p: np.float64, target_p: np.float64) -> np.float64:
# p = np.concatenate((sample_p, target_p))
# N = len(sample_p) + len(target_p)
# return 1 - 2 * np.sqrt(1 / (N - 1) * np.sum((p - np.mean(p)) ** 2))
def _weights_per_covars_names(covar_names: List) -> pd.DataFrame:
# TODO (p2): consider if to give weights that are proportional to the proportion of this covar in the population
# E.g.: if merging varios platforms, maybe if something like windows has very few users, it's impact on the ASMD
# should be smaller (similar to how kld works).
# The current function structure won't support it, and this would require some extra input (i.e.: baseline target pop proportion)
"""
Figure out how much weight to give to each column name for ASMD averaging.
This is meant for post-processing df produced from model_matrix that include
one-hot categorical variables. This function helps to resolve the needed weight to add
to columns after they are broken down by the one-hot encoding used in model_matrix.
Each of these will count for 1/num_levels.
It's OK to assume that variables with '[]' in the name are one-hot
categoricals because model_matrix enforces it.
Args:
covar_names (List): A list with names of covariate.
Returns:
pd.DataFrame: with two columns, one for weights and another for main_covar_names,
with rows for each of the columns from 'covar_names'
Examples:
::
asmd_df = pd.DataFrame(
{
'age': 0.5,
'education[T.high_school]': 1,
'education[T.bachelor]': 1,
'education[T.masters]': 1,
'education[T.phd]': 1,
}, index = ('self', ))
input = asmd_df.columns.values.tolist()
# input
# ['age',
# 'education[T.high_school]',
# 'education[T. bachelor]',
# 'education[T. masters]',
# 'education[T. phd]']
_weights_per_covars_names(input).to_dict()
# Output:
# {'weight': {'age': 1.0,
# 'education[T.high_school]': 0.25,
# 'education[T.bachelor]': 0.25,
# 'education[T.masters]': 0.25,
# 'education[T.phd]': 0.25},
# 'main_covar_names': {'age': 'age',
# 'education[T.high_school]': 'education',
# 'education[T.bachelor]': 'education',
# 'education[T.masters]': 'education',
# 'education[T.phd]': 'education'}}
"""
columns_to_original_variable = {v: re.sub(r"\[.*\]$", "", v) for v in covar_names}
counts = collections.Counter(columns_to_original_variable.values())
weights = pd.DataFrame(
{k: 1 / counts[v] for k, v in columns_to_original_variable.items()},
index=("weight",),
)
_check_weights_are_valid(weights) # verify nothing odd has occurred.
main_covar_names = pd.DataFrame.from_dict(
columns_to_original_variable,
orient="index",
columns=[
"main_covar_names",
],
)
return pd.concat([weights.transpose(), main_covar_names], axis=1)
# TODO: add memoization
def asmd(
sample_df: pd.DataFrame,
target_df: pd.DataFrame,
sample_weights: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
target_weights: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
std_type: Literal["target", "sample", "pooled"] = "target",
aggregate_by_main_covar: bool = False,
) -> pd.Series:
"""
Calculate the Absolute Standardized Mean Deviation (ASMD) between the columns of two DataFrames (or BalanceDFs).
It uses weighted average and std for the calculations.
This is the same as taking the absolute value of Cohen's d statistic,
with a specific choice of the standard deviation (std).
https://en.wikipedia.org/wiki/Effect_size#Cohen's_d
As opposed to Cohen's d, the current asmd implementation has several options of std calculation,
see the arguments section for details.
Unlike in R package {cobalt}, in the current implementation of asmd:
- the absolute value is taken
- un-represented levels of categorical variables are treated as missing,
not as 0.
- differences for categorical variables are also weighted by default
The function omits columns that starts with the name "_is_na_"
If column names of sample_df and target_df are different, it will only calculate asmd for
the overlapping columns. The rest will be np.nan.
The mean(asmd) will be calculated while treating the nan values as 0s.
Args:
sample_df (pd.DataFrame): source group of the asmd comparison
target_df (pd.DataFrame): target group of the asmd comparison.
The column names should be the same as the ones from sample_df.
sample_weights (Union[ List, pd.Series, np.ndarray, ], optional): weights to use.
The default is None.
If no weights are passed (None), it will use an array of 1s.
target_weights (Union[ List, pd.Series, np.ndarray, ], optional): weights to use.
The default is None.
If no weights are passed (None), it will use an array of 1s.
std_type (Literal["target", "sample", "pooled"], optional):
How the standard deviation should be calculated.
The options are: "target", "sample" and "pooled". Defaults to "target".
"target" means we use the std from the target population.
"sample" means we use the std from the sample population.
"pooled" means we use the simple arithmetic average of
the variance from the sample and target population.
We then take the square root of that value to get the pooled std.
Notice that this is done while giving the same weight to both sources.
I.e.: there is NO over/under weighting sample or target based on their
respective sample sizes (in contrast to how pooled sd is calculated in
Cohen's d statistic).
aggregate_by_main_covar (bool):
If to use :func:`_aggregate_asmd_by_main_covar` to aggregate (average) the asmd based on variable name.
Default is False.
Returns:
pd.Series: a Series indexed on the names of the columns in the input DataFrames.
The values (of type np.float64) are of the ASMD calculation.
The last element is 'mean(asmd)', which is the average of the calculated ASMD values.
Examples:
::
import numpy as np
import pandas as pd
from balance.stats_and_plots import weighted_comparisons_stats
a1 = pd.Series((1, 2))
b1 = pd.Series((-1, 1))
a2 = pd.Series((3, 4))
b2 = pd.Series((-2, 2))
w1 = pd.Series((1, 1))
w2 = w1
r = weighted_comparisons_stats.asmd(
pd.DataFrame({"a": a1, "b": b1}),
pd.DataFrame({"a": a2, "b": b2}),
w1,
w2,
)
exp_a = np.abs(a1.mean() - a2.mean()) / a2.std()
exp_b = np.abs(b1.mean() - b2.mean()) / b2.std()
print(r)
print(exp_a)
print(exp_b)
# output:
# {'a': 2.82842712474619, 'b': 0.0, 'mean(asmd)': 1.414213562373095}
# 2.82842712474619
# 0.0
a1 = pd.Series((1, 2))
b1_A = pd.Series((1, 3))
b1_B = pd.Series((-1, -3))
a2 = pd.Series((3, 4))
b2_A = pd.Series((2, 3))
b2_B = pd.Series((-2, -3))
w1 = pd.Series((1, 1))
w2 = w1
r = weighted_comparisons_stats.asmd(
pd.DataFrame({"a": a1, "b[A]": b1_A, "b[B]": b1_B}),
pd.DataFrame({"a": a2, "b[A]": b2_A, "b[B]": b2_B}),
w1,
w2,
).to_dict()
print(r)
# {'a': 2.82842712474619, 'b[A]': 0.7071067811865475, 'b[B]': 0.7071067811865475, 'mean(asmd)': 1.7677669529663689}
# Check that using aggregate_by_main_covar works
r = weighted_comparisons_stats.asmd(
pd.DataFrame({"a": a1, "b[A]": b1_A, "b[B]": b1_B}),
pd.DataFrame({"a": a2, "b[A]": b2_A, "b[B]": b2_B}),
w1,
w2,
"target",
True,
).to_dict()
print(r)
# {'a': 2.82842712474619, 'b': 0.7071067811865475, 'mean(asmd)': 1.7677669529663689}
"""
if not isinstance(sample_df, pd.DataFrame):
raise ValueError(f"sample_df must be pd.DataFrame, is {type(sample_df)}")
if not isinstance(target_df, pd.DataFrame):
raise ValueError(f"target_df must be pd.DataFrame, is {type(target_df)}")
possible_std_type = ("sample", "target", "pooled")
if not (std_type in possible_std_type):
raise ValueError(f"std_type must be in {possible_std_type}, is {std_type}")
if sample_df.columns.values.tolist() != target_df.columns.values.tolist():
logger.warning(
f"""
sample_df and target_df must have the same column names.
sample_df column names: {sample_df.columns.values.tolist()}
target_df column names: {target_df.columns.values.tolist()}"""
)
sample_mean = descriptive_stats(sample_df, sample_weights, "mean")
target_mean = descriptive_stats(target_df, target_weights, "mean")
if std_type == "sample":
std = descriptive_stats(sample_df, sample_weights, "std")
elif std_type == "target":
std = descriptive_stats(target_df, target_weights, "std")
elif std_type == "pooled":
target_std = descriptive_stats(target_df, target_weights, "std")
sample_std = descriptive_stats(sample_df, sample_weights, "std")
std = np.sqrt(((sample_std**2) + (target_std**2)) / 2)
out = abs(sample_mean - target_mean) / std # pyre-ignore[61]: std is always defined
# Remove na indicator columns; it's OK to assume that these columns are
# indicators because add_na_indicator enforces it
out = out.loc[:, (c for c in out.columns.values if not c.startswith("_is_na_"))]
out = out.replace([np.inf, -np.inf], np.nan)
# TODO (p2): verify that df column names are unique (otherwise throw an exception).
# it should probably be upstream during in the Sample creation process.
weights = _weights_per_covars_names(out.columns.values.tolist())[
["weight"]
].transpose()
out = pd.concat((out, weights))
mean = weighted_mean(out.iloc[0], out.loc["weight"])
out["mean(asmd)"] = mean
out = out.iloc[0]
out.name = None
if aggregate_by_main_covar:
out = _aggregate_asmd_by_main_covar(out)
return out
def _aggregate_asmd_by_main_covar(asmd_series: pd.Series) -> pd.Series:
"""
This function helps to aggregate the ASMD, which is broken down per level for a category variable, into one value per covariate.
This is useful since it allows us to get high level view of features such as country, locale, etc.
It also allows us to filter out variables (such as is_today) before the overall averaging of the ASMD.
Args:
asmd_series (pd.Series): a value for each covariate. Covariate name are in the index, the values are the asmd values.
Returns:
pd.Series: If asmd_series had several items broken by one-hot encoding,
then they would be averaged (with equal weight to each).
Examples:
::
from balance.stats_and_plots.weighted_comparisons_stats import _aggregate_asmd_by_main_covar
asmd_series = pd.Series(
{
'age': 0.5,
'education[T.high_school]': 1,
'education[T.bachelor]': 2,
'education[T.masters]': 3,
'education[T.phd]': 4,
})
_aggregate_asmd_by_main_covar(asmd_series).to_dict()
# output:
# {'age': 0.5, 'education': 2.5}
"""
weights = _weights_per_covars_names(asmd_series.index.values.tolist())
# turn things into DataFrame to make it easy to aggregate.
out = pd.concat((asmd_series, weights), axis=1)
def _weighted_mean_for_our_df(x: pd.DataFrame) -> pd.Series:
values = x.iloc[:, 0]
weights = x["weight"]
weighted_mean = pd.Series(
((values * weights) / weights.sum()).sum(), index=["mean"]
)
return weighted_mean
out = out.groupby("main_covar_names").apply(_weighted_mean_for_our_df).iloc[:, 0]
out.name = None
out.index.name = None
return out
# TODO: (p2) sample_before and sample_after are redundant, the moment weights of
# before and after are supplied directly.
# In the future, we can either omit sample_after, or change the names to
# reflect a support a comparison of two panels to some target populations.
def asmd_improvement(
sample_before: pd.DataFrame,
sample_after: pd.DataFrame,
target: pd.DataFrame,
sample_before_weights: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
sample_after_weights: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
target_weights: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
) -> np.float64:
"""Calculates the improvement in mean(asmd) from before to after applying some weight adjustment.
Args:
sample_before (pd.DataFrame): DataFrame of the sample before adjustments.
sample_after (pd.DataFrame): DataFrame of the sample after adjustments
(should be identical to sample_before. But could be used to compare two populations).
target (pd.DataFrame): DataFrame of the target population.
sample_before_weights (Union[ List, pd.Series, np.ndarray, ], optional): Weights before adjustments (i.e.: design weights). Defaults to None.
sample_after_weights (Union[ List, pd.Series, np.ndarray, ], optional): Weights after some adjustment. Defaults to None.
target_weights (Union[ List, pd.Series, np.ndarray, ], optional): Design weights of the target population. Defaults to None.
Returns:
np.float64: The improvement is taking the (before_mean_asmd-after_mean_asmd)/before_mean_asmd.
The asmd is calculated using :func:`asmd`.
"""
asmd_mean_before = asmd(
sample_before, target, sample_before_weights, target_weights
).loc["mean(asmd)"]
asmd_mean_after = asmd(
sample_after, target, sample_after_weights, target_weights
).loc["mean(asmd)"]
return (asmd_mean_before - asmd_mean_after) / asmd_mean_before
def outcome_variance_ratio(
df_numerator: pd.DataFrame,
df_denominator: pd.DataFrame,
w_numerator: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
w_denominator: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
) -> pd.Series:
"""Calculate ratio of weighted variances of two DataFrames
Directly calculating the empirical ratio of variance of the outcomes before and after weighting.
Notice that this is different than design effect.
The Deff estimates the ratio of variances of the weighted means, while this function calculates the ratio
of empirical weighted variance of the data.
Args:
df_numerator (pd.DataFrame): df_numerator
df_denominator (pd.DataFrame): df_denominator
w_numerator (Union[ List, pd.Series, np.ndarray, None, ], optional): w_numerator. Defaults to None.
w_denominator (Union[ List, pd.Series, np.ndarray, None, ], optional): w_denominator. Defaults to None.
Returns:
pd.Series: (np.float64) A series of calculated ratio of variances for each outcome.
"""
numerator_w_var = weighted_var(df_numerator, w_numerator)
denominator_w_var = weighted_var(df_denominator, w_denominator)
return numerator_w_var / denominator_w_var
| balance-main | balance/stats_and_plots/weighted_comparisons_stats.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import random
from typing import Dict, List, Literal, Optional, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.graph_objs as go
import plotly.offline as offline
import seaborn as sns
from balance.stats_and_plots.weighted_stats import (
relative_frequency_table,
weighted_quantile,
)
from balance.util import choose_variables, rm_mutual_nas
from matplotlib.colors import rgb2hex
logger: logging.Logger = logging.getLogger(__package__)
################################################################################
# seaborn plots below
################################################################################
def _return_sample_palette(
names: List[str],
) -> Union[Dict[str, str], str]:
"""Returns sample palette for seaborn plots.
Named colors for matplotlib: https://stackoverflow.com/a/37232760
Args:
names (List[str]): e.g. ['self', 'target']
Returns:
Union[Dict[str, str], str]: e.g. {'self': 'tomato', 'target': 'dodgerblue'}
"""
# colors to match the plotly colors
col_unadjusted = rgb2hex((222 / 255, 45 / 255, 38 / 255, 0.8), keep_alpha=True)
col_adjusted = rgb2hex((52 / 255, 165 / 255, 48 / 255, 0.5), keep_alpha=True)
col_target = rgb2hex((158 / 255, 202 / 255, 225 / 255, 0.8), keep_alpha=True)
if set(names) == {"self", "target"}:
sample_palette = {
"self": col_unadjusted,
"target": col_target,
}
elif set(names) == {"self", "unadjusted"}:
sample_palette = {
"self": col_adjusted,
"unadjusted": col_unadjusted,
}
elif set(names) == {"self", "unadjusted", "target"}:
sample_palette = {
"self": col_adjusted,
"unadjusted": col_unadjusted,
"target": col_target,
}
elif set(names) == {"adjusted", "unadjusted", "target"}:
sample_palette = {
"adjusted": col_adjusted,
"unadjusted": col_unadjusted,
"target": col_target,
}
else:
sample_palette = "muted"
return sample_palette
def _plotly_marker_color(
name: Literal["sample", "unadjusted", "self", "adjusted"],
only_self_and_target: bool,
color_type: Literal["color", "line"],
) -> str:
"""
Returns a color string for a marker in a plotly plot based on the given parameters.
Args:
name (Literal["sample", "unadjusted", "self", "adjusted"]): Name of the marker.
only_self_and_target (bool): Determines if only self and target groups are available, or if it's self, unadjusted and target.
color_type (Literal["color", "line"]): The type of color, either "color" or "line".
Returns:
str: A string representing the color in RGBA format.
Raises:
ValueError: If the color_type is not one of the accepted options.
"""
if color_type == "color":
col1 = 0.8
col2 = 0.5
elif color_type == "line":
col1 = 1
col2 = 1
else:
raise ValueError(
"Invalid value for 'tycolor_typepe'. Must be either 'color' or 'line'."
)
if name.lower() in ["sample", "unadjusted"] or (
name.lower() == "self" and only_self_and_target
):
return f"rgba(222,45,38,{col1})"
elif name.lower() in ["self", "adjusted"]:
return f"rgba(52,165,48,{col2})"
else:
return f"rgb(158,202,225,{col1})"
def plot_bar(
dfs: List[Dict[str, Union[pd.DataFrame, pd.Series]]],
names: List[str],
column: str,
axis: Optional[plt.Axes] = None,
weighted: bool = True,
title: Optional[str] = None,
ylim: Optional[Tuple[float, float]] = None,
) -> None:
"""
Shows a (weighted) sns.barplot using a relative frequency table of several DataFrames (with optional control over the y-axis limits).
If weighted is True, then mutual NA values are removed using :func:`rm_mutual_nas`.
Args:
dfs (List[Dict[str, Union[pd.DataFrame, pd.Series]]]): a list (of length 1 or more) of dictionaries which describe the DataFrames and weights
The structure is as follows:
[
{'df': pd.DataFrame(...), "weight": pd.Series(...)},
...
]
The 'df' is a DataFrame which includes the column name that was supplied through 'column'.
The "weight" is a pd.Series of weights that are used when aggregating the variable using :func:`relative_frequency_table`.
names (List[str]): a list of the names of the DataFrames that are plotted. E.g.: ['adjusted', 'unadjusted', 'target']
column (str): The column to be used to aggregate using :func:`relative_frequency_table`.
axis (Optional[plt.Axes], optional): matplotlib Axes object to draw the plot onto, otherwise uses the current Axes. Defaults to None.
weighted (bool, optional): If to pass the weights from the dicts inside dfs. Defaults to True.
title (str, optional): Title of the plot. Defaults to "barplot of covar '{column}'".
ylim (Optional[Tuple[float, float]], optional): A tuple with two float values representing the lower and upper limits of the y-axis.
If not provided, the y-axis range is determined automatically. Defaults to None.
Examples:
::
from balance.stats_and_plots.weighted_comparisons_plots import plot_bar
import pandas as pd
import numpy as np
df = pd.DataFrame({
'group': ('a', 'b', 'c', 'c'),
'v1': (1, 2, 3, 4),
})
plot_bar(
[{"df": df, "weight": pd.Series((1, 1, 1, 1))}, {"df": df, "weight": pd.Series((2, 1, 1, 1))}],
names = ["self", "target"],
column = "group",
axis = None,
weighted = True)
# The same as above just with ylim set to (0, 1).
plot_bar(
[{"df": df, "weight": pd.Series((1, 1, 1, 1))}, {"df": df, "weight": pd.Series((2, 1, 1, 1))}],
names = ["self", "target"],
column = "group",
axis = None,
weighted = True,
ylim = (0, 1))
# Also deals with np.nan weights
a = plot_bar(
[{"df": df, "weight": pd.Series((1, 1, 1, np.nan))}, {"df": df, "weight": pd.Series((2, 1, 1, np.nan))}],
names = ["self", "target"],
column = "group",
axis = None,
weighted = True)
"""
plot_data = []
for ii, i in enumerate(dfs):
a_series = i["df"][column]
_w = i["weight"]
if weighted:
a_series, _w = rm_mutual_nas(a_series, _w)
a_series.name = column # rm_mutual_nas removes name, so we set it back
df_plot_data = relative_frequency_table(a_series, w=_w if weighted else None)
df_plot_data["dataset"] = names[ii] # a recycled column for barplot's hue.
plot_data.append(df_plot_data)
sample_palette = _return_sample_palette(names)
if title is None:
title = f"barplot of covar '{column}'"
ax = sns.barplot(
x=column,
y="prop",
hue="dataset",
data=pd.concat(plot_data),
ax=axis,
palette=sample_palette,
saturation=1,
alpha=0.6,
)
if ylim is not None:
ax.set_ylim(ylim)
ax.set_title(title)
def plot_hist_kde(
dfs: List[Dict[str, Union[pd.DataFrame, pd.Series]]],
names: List[str],
column: str,
axis: Optional[plt.Axes] = None,
weighted: bool = True,
dist_type: Literal["hist", "kde", "ecdf"] = "hist",
title: Optional[str] = None,
) -> None:
"""Shows a (weighted) distribution plot ():func:`sns.displot`) of data from several DataFrame objects.
Options include histogram (hist), kernel density estimate (kde), and empirical cumulative density function (ecdf).
Args:
dfs (List[Dict[str, Union[pd.DataFrame, pd.Series]]]): a list (of length 1 or more) of dictionaries which describe the DataFrames and weights
The structure is as follows:
[
{'df': pd.DataFrame(...), "weight": pd.Series(...)},
...
]
The 'df' is a DataFrame which includes the column name that was supplied through 'column'.
The "weight" is a pd.Series of weights that are used when aggregating the variable using :func:`relative_frequency_table`.
names (List[str]): a list of the names of the DataFrames that are plotted. E.g.: ['adjusted', 'unadjusted', 'target']
column (str): The column to be used to aggregate using :func:`relative_frequency_table`.
axis (Optional[plt.Axes], optional): matplotlib Axes object to draw the plot onto, otherwise uses the current Axes. Defaults to None.
weighted (bool, optional): If to pass the weights from the dicts inside dfs. Defaults to True.
dist_type (Literal["hist", "kde", "ecdf"], optional): The type of plot to draw. Defaults to "hist".
title (str, optional): Title of the plot. Defaults to "distribution plot of covar '{column}'".
Examples:
::
from balance.stats_and_plots.weighted_comparisons_plots import plot_hist_kde
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({
'group': ('a', 'b', 'c', 'c'),
'v1': (1, 2, 3, 4),
})
dfs1 = [{"df": pd.DataFrame(pd.Series([1,2,2,2,3,4,5,5,7,8,9,9,9,9,5,2,5,4,4,4], name = "v1")), "weight": None}, {"df": df, "weight": pd.Series((200, 1, 0, 20))}]
plt.figure(1)
# kde: no weights
plot_hist_kde(
dfs1,
names = ["self", "target"],
column = "v1",
axis = None,
weighted = False, dist_type = "kde")
plt.figure(2)
# kde: with weights
plot_hist_kde(
dfs1,
names = ["self", "target"],
column = "v1",
axis = None,
weighted = True, dist_type = "kde")
plt.figure(3)
# hist
plot_hist_kde(
dfs1,
names = ["self", "target"],
column = "v1",
axis = None,
weighted = True, dist_type = "hist")
plt.figure(4)
# ecdf
plot_hist_kde(
dfs1,
names = ["self", "target"],
column = "v1",
axis = None,
weighted = True, dist_type = "ecdf")
# can work nicely with plt.subplots:
f, axes = plt.subplots(1, 2, figsize=(7, 7 * 1))
plot_hist_kde(
dfs1,
names = ["self", "target"],
column = "v1",
axis = axes[0],
weighted = False, dist_type = "kde")
plot_hist_kde(
dfs1,
names = ["self", "target"],
column = "v1",
axis = axes[1],
weighted = False, dist_type = "kde")
"""
possible_dist_function = {
"hist": sns.histplot,
"kde": sns.kdeplot,
"ecdf": sns.ecdfplot,
}
dist_function = possible_dist_function[dist_type]
# NOTE: the reason we don't use sns.displot directly is that it doesn't accept an ax= kwarg.
# see also here: https://stackoverflow.com/a/63895570/256662
plot_data = []
for ii, i in enumerate(dfs):
a_series = i["df"][column]
_w = i["weight"]
if _w is None:
_w = pd.Series(np.ones(len(a_series)), index=a_series.index)
if weighted:
a_series, _w = rm_mutual_nas(a_series, _w)
a_series.name = column # rm_mutual_nas removes name, so we set it back
# TODO: verify if this normalization to sum to 1 is needed (if so, how come we don't do it when _w is None)?
_w = _w / np.sum(_w)
df_plot_data = pd.DataFrame({column: a_series, "_w": _w})
df_plot_data["dataset"] = names[ii] # a recycled column for barplot's hue.
plot_data.append(df_plot_data)
plot_data = pd.concat(plot_data)
sample_palette = _return_sample_palette(names)
if title is None:
title = f"distribution plot of covar '{column}'"
kwargs_for_dist_function = {
"data": plot_data,
"x": column,
"hue": "dataset",
"ax": axis,
"weights": plot_data["_w"] if weighted else None,
# common_norm:False,
"palette": sample_palette,
"linewidth": 2,
}
if dist_type != "ecdf":
kwargs_for_dist_function["common_norm"] = False
ax = dist_function(**kwargs_for_dist_function)
ax.set_title(title)
def plot_qq(
dfs: List[Dict[str, Union[pd.DataFrame, pd.Series]]],
names: List[str],
column: str,
axis: Optional[plt.Axes] = None,
weighted: bool = True,
) -> None:
"""Plots a qq plot of the weighted data from a DataFrame object against some target.
See: https://en.wikipedia.org/wiki/Q-Q_plot
Args:
dfs (List[Dict[str, Union[pd.DataFrame, pd.Series]]]): a list (of length 1 or more) of dictionaries which describe the DataFrames and weights
The structure is as follows:
[
{'df': pd.DataFrame(...), "weight": pd.Series(...)},
...
]
The 'df' is a DataFrame which includes the column name that was supplied through 'column'.
The "weight" is a pd.Series of weights that are used when aggregating the variable using :func:`weighted_quantile`.
Uses the last df item in the list as the target.
names (List[str]): a list of the names of the DataFrames that are plotted. E.g.: ['adjusted', 'unadjusted', 'target']
column (str): The column to be used to aggregate using :func:`weighted_quantile`.
axis (Optional[plt.Axes], optional): matplotlib Axes object to draw the plot onto, otherwise uses the current Axes. Defaults to None.
weighted (bool, optional): If to pass the weights from the dicts inside dfs. Defaults to True.
Examples:
::
import numpy as np
import pandas as pd
from balance.stats_and_plots.weighted_comparisons_plots import plot_qq
from numpy import random
df = pd.DataFrame({
'v1': random.uniform(size=100),
}).sort_values(by=['v1'])
dfs1 = [
{"df": df, "weight": pd.Series(np.ones(100))},
{"df": df, "weight": pd.Series(range(100))},
{"df": df, "weight": pd.Series(np.ones(100))},
]
# plot_qq(dfs1, names=["self", "unadjusted", "target"], column="v1", axis=None, weighted=False)
plot_qq(dfs1, names=["self", "unadjusted", "target"], column="v1", axis=None, weighted=True)
"""
target = dfs[-1] # assumes the last item is target
dfs = dfs[:-1] # assumes the non-last item are dfs to be compared to target
for ii, i in enumerate(dfs):
d = i["df"]
_w = i["weight"]
target_q = weighted_quantile(
target["df"][column],
np.arange(0, 1, 0.001),
# pyre-fixme[6]: TODO:
# This is because of using:
# dfs: List[Dict[str, Union[pd.DataFrame, pd.Series]]],
# When in fact we want to be clear that the first element is called
# "df" and the second "weight", and that the first is a pd.DataFrame and
# the second pd.Series. Until this is not clear - the following line will raise an error.
target["weight"] if weighted else None,
)
sample_q = weighted_quantile(
d.loc[:, column],
np.arange(0, 1, 0.001),
# pyre-fixme[6]
_w if weighted else None,
)
axis = sns.scatterplot(
x=target_q.iloc[:, 0].values,
y=sample_q.iloc[:, 0].values,
label=names[ii],
ax=axis,
)
set_xy_axes_to_use_the_same_lim(axis)
axis.plot(axis.get_xlim(), axis.get_ylim(), "--")
axis.set_title(f"quantile-quantile plot of covar '{column}' in target vs sample")
axis.legend()
def plot_qq_categorical(
dfs: List[Dict[str, Union[pd.DataFrame, pd.Series]]],
names: List[str],
column: str,
axis: Optional[plt.Axes] = None,
weighted: bool = True,
label_threshold: int = 30,
) -> None:
"""A scatter plot of weighted relative frequencies of categories from each df.
Notice that this is not a "real" qq-plot, but rather a scatter plot of (estimated, weighted) probabilities for each category.
X-axis is the sample (adjusted, unadjusted) and Y-axis is the target.
Args:
dfs (List[Dict[str, Union[pd.DataFrame, pd.Series]]]): a list (of length 1 or more) of dictionaries which describe the DataFrames and weights
The structure is as follows:
[
{'df': pd.DataFrame(...), "weight": pd.Series(...)},
...
]
The 'df' is a DataFrame which includes the column name that was supplied through 'column'.
The "weight" is a pd.Series of weights that are used when aggregating the variable using :func:`weighted_quantile`.
Uses the last df item in the list as the target.
names (List[str]): a list of the names of the DataFrames that are plotted. E.g.: ['adjusted', 'unadjusted', 'target']
column (str): The column to be used to aggregate using :func:`relative_frequency_table`.
axis (Optional[plt.Axes], optional): matplotlib Axes object to draw the plot onto, otherwise uses the current Axes. Defaults to None.
weighted (bool, optional): If to pass the weights from the dicts inside dfs. Defaults to True.
label_threshold (int, optional): All labels that are larger from the threshold will be omitted from the scatter plot (so to reduce clutter). Defaults to 30.
Examples:
::
import numpy as np
import pandas as pd
from balance.stats_and_plots.weighted_comparisons_plots import plot_qq_categorical
from numpy import random
df = pd.DataFrame({
'v1': random.random_integers(11111, 11114, size=100),
}).sort_values(by=['v1'])
dfs1 = [
{"df": df, "weight": pd.Series(np.ones(100))},
{"df": df, "weight": pd.Series(np.ones(99).tolist() + [1000])},
{"df": df, "weight": pd.Series(np.ones(100))},
]
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20, 6) # (w, h)
fig, axs = plt.subplots(1,3)
# Without using weights
plot_qq_categorical(dfs1, names=["self", "unadjusted", "target"], column="v1", axis=axs[0], weighted=False)
# With weights
plot_qq_categorical(dfs1, names=["self", "unadjusted", "target"], column="v1", axis=axs[1], weighted=True)
# With label trimming if the text is longer than 3.
plot_qq_categorical(dfs1, names=["self", "unadjusted", "target"], column="v1", axis=axs[2], weighted=True, label_threshold=3)
"""
target = dfs[-1]["df"]
target_weights = dfs[-1]["weight"]
dfs = dfs[:-1]
# pyre-fixme[6]
target_plot_data = relative_frequency_table(target, column, target_weights)
for ii, i in enumerate(dfs):
d = i["df"]
_w = i["weight"] if weighted else None
# pyre-fixme[6]
sample_plot_data = relative_frequency_table(d, column, _w)
plot_data = pd.merge(
sample_plot_data,
target_plot_data,
on=column,
how="outer",
suffixes=("_sample", "_target"),
)
axis = sns.scatterplot(
x=plot_data.prop_sample, y=plot_data.prop_target, label=names[ii], ax=axis
)
if plot_data.shape[0] < label_threshold:
for r in plot_data.itertuples():
# pyre-fixme[16]: `tuple` has no attribute `prop_sample`.
axis.text(x=r.prop_sample, y=r.prop_target, s=r[1])
axis.set_ylim(-0.1, 1.1)
axis.set_xlim(-0.1, 1.1)
axis.plot(axis.get_xlim(), axis.get_ylim(), "--")
axis.set_title(
f"proportion-proportion plot of covar '{column}' in target vs sample"
)
axis.legend()
# TODO: add control (or just change) the default theme
# TODO: add a separate dist_type control parameter for categorical and numeric variables.
def seaborn_plot_dist(
dfs: List[Dict[str, Union[pd.DataFrame, pd.Series]]],
names: Optional[List[str]] = None,
variables: Optional[List] = None,
numeric_n_values_threshold: int = 15,
weighted: bool = True,
dist_type: Optional[Literal["qq", "hist", "kde", "ecdf"]] = None,
return_axes: bool = False,
ylim: Optional[Tuple[float, float]] = None,
) -> Union[List[plt.Axes], np.ndarray, None]:
"""Plots to compare the weighted distributions of an arbitrary number of variables from
an arbitrary number of DataFrames.
Uses: :func:`plot_qq_categorical`, :func:`plot_qq`, :func:`plot_hist_kde`, :func:`plot_bar`.
Args:
dfs (List[Dict[str, Union[pd.DataFrame, pd.Series]]]): a list (of length 1 or more) of dictionaries which describe the DataFrames and weights
The structure is as follows:
[
{'df': pd.DataFrame(...), "weight": pd.Series(...)},
...
]
The 'df' is a DataFrame which includes the column name that was supplied through 'column'.
The "weight" is a pd.Series of weights that are used when aggregating by the column variable.
names (List[str]): a list of the names of the DataFrames that are plotted. E.g.: ['adjusted', 'unadjusted', 'target']
variables (Optional[List], optional): The list of variables to use, by default (None) will plot all of them.
numeric_n_values_threshold (int, optional): How many unique values (or less) should be in a column so that it is considered to be a "category"? Defaults to 15.
This is compared against the maximum number of distinct values (for each of the variables) across all DataFrames.
Setting this value to 0 will disable this check.
weighted (bool, optional): If to pass the weights from the dicts inside dfs. Defaults to True.
dist_type (Optional[str], optional): can be "hist", "kde", or "qq". Defaults to None.
return_axes (bool, optional): if to returns axes or None. Defaults to False,
ylim (Optional[Tuple[float, float]], optional): A tuple with two float values representing the lower and upper limits of the y-axis.
If not provided, the y-axis range is determined automatically. Defaults to None.
Passed only for categorical variables and when dist_type is not 'qq' (i.e.: for bar plots).
Returns:
Union[List[plt.Axes], np.ndarray, None]: Returns None.
However, if return_axes is True then either it returns a list or an np.array of matplotlib AxesSubplot (plt.Subplot).
NOTE: There is no AxesSubplot class until one is invoked and created on the fly.
See details here: https://stackoverflow.com/a/11690800/256662
Examples:
::
import numpy as np
import pandas as pd
from balance.stats_and_plots.weighted_comparisons_plots import seaborn_plot_dist
from numpy import random
df = pd.DataFrame({
'v1': random.random_integers(11111, 11114, size=100).astype(str),
'v2': random.normal(size = 100),
'v3': random.uniform(size = 100),
}).sort_values(by=['v2'])
dfs1 = [
{"df": df, "weight": pd.Series(np.ones(100))},
{"df": df, "weight": pd.Series(np.ones(99).tolist() + [1000])},
{"df": df, "weight": pd.Series(np.random.uniform(size=100))},
]
seaborn_plot_dist(dfs1, names=["self", "unadjusted", "target"], dist_type = "qq") # default
seaborn_plot_dist(dfs1, names=["self", "unadjusted", "target"], dist_type = "hist")
seaborn_plot_dist(dfs1, names=["self", "unadjusted", "target"], dist_type = "kde")
seaborn_plot_dist(dfs1, names=["self", "unadjusted", "target"], dist_type = "ecdf")
# With limiting the y axis range to (0,1)
seaborn_plot_dist(dfs1, names=["self", "unadjusted", "target"], dist_type = "kde", ylim = (0,1))
"""
if dist_type is None:
if len(dfs) == 1:
dist_type = "hist"
else:
dist_type = "qq"
# Choose set of variables to plot
variables = choose_variables(*(d["df"] for d in dfs), variables=variables)
logger.debug(f"plotting variables {variables}")
# Set up subplots
f, axes = plt.subplots(len(variables), 1, figsize=(7, 7 * len(variables)))
if not isinstance(axes, np.ndarray): # If only one subplot
axes = [axes]
# TODO: patch choose_variables to return outcome_types from multiple_objects
numeric_variables = dfs[0]["df"].select_dtypes(exclude=["object"]).columns.values
for io, o in enumerate(variables):
# Find the maximum number of non-missing values of this variable accross
# all the dataframes
n_values = max(len(set(rm_mutual_nas(d["df"].loc[:, o].values))) for d in dfs)
if n_values == 0:
logger.warning(f"No nonmissing values for variable '{o}', skipping")
continue
# Plot categorical variables as histogram
categorical = (o not in numeric_variables) or (
n_values < numeric_n_values_threshold
)
if categorical:
if dist_type == "qq":
# pyre-fixme[6]
plot_qq_categorical(dfs, names, o, axes[io], weighted)
else:
# pyre-fixme[6]
plot_bar(dfs, names, o, axes[io], weighted, ylim=ylim)
else:
if dist_type == "qq":
# pyre-fixme[6]
plot_qq(dfs, names, o, axes[io], weighted)
else:
# pyre-fixme[6]
plot_hist_kde(dfs, names, o, axes[io], weighted, dist_type)
if return_axes:
return axes
# else (default) will return None
def set_xy_axes_to_use_the_same_lim(ax: plt.Axes) -> None:
"""Set the x and y axes limits to be the same.
Done by taking the min and max from xlim and ylim and using these global min/max on both x and y axes.
Args:
ax (plt.Axes): matplotlib Axes object to draw the plot onto.
Examples:
::
import matplotlib.pyplot as plt
plt.figure(1)
plt.scatter(x= [1,2,3], y = [3,4,5])
plt.figure(2)
fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
plt.scatter(x= [1,2,3], y = [3,4,5])
set_xy_axes_to_use_the_same_lim(ax)
"""
xlim = ax.get_xlim()
ylim = ax.get_ylim()
ax.set_xlim(min(xlim[0], ylim[0]), max(xlim[1], ylim[1]))
ax.set_ylim(min(xlim[0], ylim[0]), max(xlim[1], ylim[1]))
################################################################################
# plotly plots below
################################################################################
def plotly_plot_qq(
dict_of_dfs: Dict[str, pd.DataFrame],
variables: List[str],
plot_it: bool = True,
return_dict_of_figures: bool = False,
**kwargs,
) -> Optional[Dict[str, go.Figure]]:
"""
Plots interactive QQ plot of the given variables.
Creates a plotly qq plot of the given variables from multiple DataFrames.
This ASSUMES there is a df with key 'target'.
Args:
dict_of_dfs (Dict[str, pd.DataFrame]): The key is the name of the DataFrame (E.g.: self, unadjusted, target),
and the value is the DataFrame that contains the variables that we want to plot.
variables (List[str]): a list of variables to use for plotting.
plot_it (bool, optional): If to plot the plots interactively instead of returning a dictionary. Defaults to True.
return_dict_of_figures (bool, optional): If to return the dictionary containing the plots rather than just returning None. Defaults to False.
**kwargs: Additional keyword arguments to pass to the update_layout method of the plotly figure object. (e.g.: width and height are 700 and 450, and could be set using the kwargs).
Returns:
Optional[Dict[str, go.Figure]]: Dictionary containing plots if return_dict_of_figures is True. None otherwise.
Examples:
::
import numpy as np
import pandas as pd
from numpy import random
from balance.stats_and_plots.weighted_comparisons_plots import plotly_plot_qq
random.seed(96483)
df = pd.DataFrame({
'v1': random.random_integers(11111, 11114, size=100).astype(str),
'v2': random.normal(size = 100),
'v3': random.uniform(size = 100),
}).sort_values(by=['v2'])
dict_of_dfs = {
"self": pd.concat([df, pd.Series(random.random(size = 100) + 0.5, name = "weight")], axis = 1),
"unadjusted": pd.concat([df, pd.Series(np.ones(99).tolist() + [1000], name = "weight")], axis = 1),
"target": pd.concat([df, pd.Series(np.ones(100), name = "weight")], axis = 1),
}
# It won't work with "v1" since it is not numeric.
plotly_plot_qq(dict_of_dfs, variables= ["v2", "v3"])
"""
dict_of_qqs = {}
for variable in variables:
variable_specific_dict_of_plots = {}
assert "target" in dict_of_dfs.keys(), "Must pass target"
# Extract 'col1' because weighted_quantile will return a DataFrame
# https://www.statsmodels.org/dev/_modules/statsmodels/stats/weightstats.html#DescrStatsW.quantile
line_data = list(
weighted_quantile(
dict_of_dfs["target"][variable],
np.arange(0, 1, 0.001),
dict_of_dfs["target"]["weight"]
if "weight" in dict_of_dfs["target"].columns
else None,
)["col1"]
)
# Indicate if we have only self and target (without unadjusted)
# since in this case the color of self should be red, since it's likely unadjusted.
only_self_and_target = set(dict_of_dfs.keys()) == {"self", "target"}
for name in dict_of_dfs:
if name.lower() == "target":
variable_specific_dict_of_plots[name] = go.Scatter(
x=line_data,
y=line_data,
showlegend=False,
line={"color": ("blue"), "width": 2, "dash": "dash"},
)
else:
variable_specific_dict_of_plots[name] = go.Scatter(
x=line_data,
y=list(
weighted_quantile(
dict_of_dfs[name][variable],
np.arange(0, 1, 0.001),
dict_of_dfs[name]["weight"]
if "weight" in dict_of_dfs[name].columns
else None,
)["col1"]
),
marker={
"color": _plotly_marker_color(
# pyre-ignore[6]: it cannot get to this point if name=="target".
name,
only_self_and_target,
"color",
)
},
mode="markers",
name=naming_legend(name, list(dict_of_dfs.keys())),
opacity=0.6,
)
data = [variable_specific_dict_of_plots[name] for name in dict_of_dfs]
layout = {
"title": f"QQ Plots of {variable}",
"paper_bgcolor": "rgb(255, 255, 255)",
"plot_bgcolor": "rgb(255, 255, 255)",
"xaxis": {
"zeroline": False,
"linewidth": 1,
"mirror": True,
"title": variable,
},
"yaxis": {"zeroline": False, "linewidth": 1, "mirror": True},
}
fig = go.Figure(data=data, layout=layout)
# Set the default PNG image size to 1400 x 1000 for when downloading the image
# pyre-ignore[16] update_layout IS defined.
fig.update_layout(**kwargs)
dict_of_qqs[variable] = fig
if plot_it:
offline.iplot(fig)
if return_dict_of_figures:
return dict_of_qqs
def plotly_plot_density(
dict_of_dfs: Dict[str, pd.DataFrame],
variables: List[str],
plot_it: bool = True,
return_dict_of_figures: bool = False,
plot_width: int = 800,
**kwargs,
) -> Optional[Dict[str, go.Figure]]:
"""
Plots interactive density plots of the given variables using kernel density estimation.
Creates a plotly plot of the kernel density estimate for each variable in the given list
across multiple DataFrames. The function assumes there is a DataFrame with the key 'target'.
The density plot shows the distribution of the variable for each DataFrame in the dictionary.
It looks for a `weights` column and uses it to normalize the data. If no weight column is found, it assumes all weights are equal to 1.
It relies on the seaborn library to create the KDE (`sns.kdeplot`).
Args:
dict_of_dfs (Dict[str, pd.DataFrame]): A dictionary where each key is a name for the DataFrame
and the value is the DataFrame that contains the variables to plot.
variables (List[str]): A list of variables to plot.
plot_it (bool, optional): Whether to plot the figures interactively using plotly. Defaults to True.
return_dict_of_figures (bool, optional): Whether to return a dictionary of plotly figures.
Defaults to False.
plot_width (int, optional): The width of the plot in pixels. Defaults to 800.
**kwargs: Additional keyword arguments to pass to the update_layout method of the plotly figure object. (e.g.: width and height are 700 and 450, and could be set using the kwargs).
Returns:
Optional[Dict[str, go.Figure]]: A dictionary containing plotly figures for each variable
in the given list if `return_dict_of_figures` is True. Otherwise, returns None.
Examples:
::
import numpy as np
import pandas as pd
from numpy import random
from balance.stats_and_plots.weighted_comparisons_plots import plotly_plot_density, plot_dist
random.seed(96483)
df = pd.DataFrame({
'v1': random.random_integers(11111, 11114, size=100).astype(str),
'v2': random.normal(size = 100),
'v3': random.uniform(size = 100),
}).sort_values(by=['v2'])
dict_of_dfs = {
"self": pd.concat([df, pd.Series(random.random(size = 100) + 0.5, name = "weight")], axis = 1),
"unadjusted": pd.concat([df, pd.Series(np.ones(99).tolist() + [1000], name = "weight")], axis = 1),
"target": pd.concat([df, pd.Series(np.ones(100), name = "weight")], axis = 1),
}
# It won't work with "v1" since it is not numeric.
plotly_plot_density(dict_of_dfs, variables= ["v2", "v3"], plot_width = 550)
# The above gives the same results as:
dfs1 = [
{"df": df, "weight": dict_of_dfs['self']["weight"]},
{"df": df, "weight": dict_of_dfs['unadjusted']["weight"]},
{"df": df, "weight": dict_of_dfs['target']["weight"]},
]
plot_dist(dfs1, names=["self", "unadjusted", "target"], library="seaborn", dist_type = "kde", variables= ["v2", "v3"])
# This gives the same shape of plots (notice how we must have the column "weight" for the plots to work)
df = pd.DataFrame({
'group': ('a', 'b', 'c', 'c'),
'v1': (1, 2, 3, 4),
})
dfs1 = [{"df": pd.DataFrame(pd.Series([1,2,2,2,3,4,5,5,7,8,9,9,9,9,5,2,5,4,4,4], name = "v1")), "weight": None}, {"df": df, "weight": pd.Series((200, 1, 0, 200000))}]
# dfs1[1]{'df'}
dict_of_dfs = {
"self": dfs1[0]['df'], # pd.concat([df, pd.Series(random.random(size = 100) + 0.5, name = "weight")], axis = 1),
"target": pd.concat([dfs1[1]['df'], pd.Series(dfs1[1]["weight"], name = "weight")], axis = 1),
}
plotly_plot_density(dict_of_dfs, variables= ["v1"], plot_width = 550)
plot_dist(dfs1, names=["self", "target"], library="seaborn", dist_type = "kde", variables= ["v1"],numeric_n_values_threshold = 1)
"""
dict_of_density_plots = {}
for variable in variables:
data = []
# Indicate if we have only self and target (without unadjusted)
# since in this case the color of self should be red, since it's likely unadjusted.
only_self_and_target = set(dict_of_dfs.keys()) == {"self", "target"}
for name, df in dict_of_dfs.items():
if "weight" in df.columns:
weights = df["weight"]
# TODO: verify if this normalization to sum to 1 is needed (if so, how come we don't do it when _w is None)?
weights = weights / weights.sum() # normalize weights by sum of weights
else:
weights = np.ones(len(df))
# Convert the data to long format
long_df = pd.DataFrame({"value": df[variable], "weight": weights})
# Replace KDE calculation with sns.kdeplot
with plt.xkcd():
plt.figure()
ax = sns.kdeplot(
data=long_df, x="value", weights="weight", common_norm=False
)
x = ax.get_lines()[-1].get_xdata()
y = ax.get_lines()[-1].get_ydata()
# print(name)
# print(x)
# print(y)
plt.close()
trace = go.Scatter(
x=x,
y=y,
mode="lines",
name=naming_legend(name, list(dict_of_dfs.keys())),
line={
# pyre-ignore[6]: it cannot get to this point if name=="target".
"color": _plotly_marker_color(name, only_self_and_target, "line"),
"width": 1.5,
},
)
data.append(trace)
layout = {
"title": f"Density Plots of '{variable}'",
"paper_bgcolor": "rgb(255, 255, 255)",
"plot_bgcolor": "rgb(255, 255, 255)",
"width": plot_width,
"xaxis": {
"title": variable,
"gridcolor": "rgba(128, 128, 128, 0.5)",
"gridwidth": 1,
"showgrid": True,
},
"yaxis": {
"title": "Density",
"gridcolor": "rgba(128, 128, 128, 0.5)",
"gridwidth": 1,
"showgrid": True,
},
}
fig = go.Figure(data=data, layout=layout)
dict_of_density_plots[variable] = fig
# pyre-ignore[16]: the update_layout exists
fig.update_layout(**kwargs)
if plot_it:
offline.iplot(fig)
if return_dict_of_figures:
return dict_of_density_plots
def plotly_plot_bar(
dict_of_dfs: Dict[str, pd.DataFrame],
variables: List[str],
plot_it: bool = True,
return_dict_of_figures: bool = False,
ylim: Optional[Tuple[float, float]] = None,
**kwargs,
) -> Optional[Dict[str, go.Figure]]:
"""
Plots interactive bar plots of the given variables (with optional control over the y-axis limits).
Args:
dict_of_dfs (Dict[str, pd.DataFrame]): A dictionary with keys as names of the DataFrame (e.g., 'self', 'unadjusted', 'target'),
and values as the DataFrames containing the variables to plot.
variables (List[str]): A list of variables to use for plotting.
plot_it (bool, optional): If True, plots the graphs interactively instead of returning a dictionary. Defaults to True.
return_dict_of_figures (bool, optional): If True, returns the dictionary containing the plots rather than just returning None. Defaults to False.
ylim (Optional[Tuple[float, float]], optional): A tuple with two float values representing the lower and upper limits of the y-axis.
If not provided, the y-axis range is determined automatically. Defaults to None.
**kwargs: Additional keyword arguments to pass to the update_layout method of the plotly figure object. (e.g.: width and height are 700 and 450, and could be set using the kwargs).
Returns:
Optional[Dict[str, go.Figure]]: Dictionary containing plots if return_dict_of_figures is True. None otherwise.
Examples:
::
import numpy as np
import pandas as pd
from numpy import random
from balance.stats_and_plots.weighted_comparisons_plots import plotly_plot_bar
random.seed(96483)
df = pd.DataFrame({
'v1': random.random_integers(11111, 11114, size=100).astype(str),
'v2': random.normal(size = 100),
'v3': random.uniform(size = 100),
}).sort_values(by=['v2'])
dict_of_dfs = {
"self": pd.concat([df, pd.Series(random.random(size = 100) + 0.5, name = "weight")], axis = 1),
"unadjusted": pd.concat([df, pd.Series(np.ones(99).tolist() + [1000], name = "weight")], axis = 1),
"target": pd.concat([df, pd.Series(np.ones(100), name = "weight")], axis = 1),
}
# It can work with "v2" and "v3", but it would be very sparse
plotly_plot_bar(dict_of_dfs, variables= ["v1"])
# Plots the same as above, but this time the range of the yaxis is from 0 to 1.
plotly_plot_bar(dict_of_dfs, variables= ["v1"], ylim = (0,1))
"""
dict_of_bars = {}
for variable in variables:
# for each variable
variable_specific_dict_of_plots = {}
# create plot for each df using that variable
# Indicate if we have only self and target (without unadjusted)
# since in this case the color of self should be red, since it's likely unadjusted.
only_self_and_target = set(dict_of_dfs.keys()) == {"self", "target"}
# filter dict_of_dfs
for name in dict_of_dfs:
df_plot_data = relative_frequency_table(
dict_of_dfs[name],
variable,
dict_of_dfs[name]["weight"]
if "weight" in dict_of_dfs[name].columns
else None,
)
variable_specific_dict_of_plots[name] = go.Bar(
x=list(df_plot_data[variable]),
y=list(df_plot_data["prop"]),
marker={
# pyre-ignore[6]: it cannot get to this point if name=="target".
"color": _plotly_marker_color(name, only_self_and_target, "color"),
"line": {
"color": _plotly_marker_color(
# pyre-ignore[6]: it cannot get to this point if name=="target".
name,
only_self_and_target,
"line",
),
"width": 1.5,
},
},
opacity=0.6,
name=naming_legend(name, list(dict_of_dfs.keys())),
visible=True,
)
data = [variable_specific_dict_of_plots[name] for name in dict_of_dfs]
layout = go.Layout(
title=f"Sample Vs Target {variable}",
paper_bgcolor="rgb(255, 255, 255)",
plot_bgcolor="rgb(255, 255, 255)",
xaxis={"title": variable},
yaxis={
"title": "Proportion of Total",
"range": ylim if ylim is not None else None,
},
)
fig = go.Figure(data=data, layout=layout)
# pyre-ignore[16]: the update_layout exists
fig.update_layout(**kwargs)
dict_of_bars[variable] = fig
if plot_it:
offline.iplot(fig)
if return_dict_of_figures:
return dict_of_bars
# TODO: add more plots other than qq for numeric (e.g.: hist, ecdf,)
# see https://plotly.com/python/distplot/
# Notice that these plots do not support the 'weight' column, so it requires a different approach.
# See the plotly_plot_density solution that uses seaborn's output
def plotly_plot_dist(
dict_of_dfs: Dict[str, pd.DataFrame],
variables: Optional[List[str]] = None,
numeric_n_values_threshold: int = 15,
weighted: bool = True,
dist_type: Optional[Literal["kde", "qq"]] = None,
plot_it: bool = True,
return_dict_of_figures: bool = False,
ylim: Optional[Tuple[float, float]] = None,
**kwargs,
) -> Optional[Dict[str, go.Figure]]:
"""
Plots interactive distribution plots (qq and bar plots) of the given variables.
The plots compare the weighted distributions of an arbitrary number
of variables from an arbitrary number of DataFrames.
Numeric variables are plotted as either qq's using :func:`plotly_plot_qq`, or as kde desnity plots using :func:`plotly_plot_density`.
categorical variables as barplots using :func:`plotly_plot_bar`.
Args:
dict_of_dfs (Dict[str, pd.DataFrame]): The key is the name of the DataFrame (E.g.: self, unadjusted, target),
and the value is the DataFrame that contains the variables that we want to plot.
variables (Optional[List[str]], optional): a list of variables to use for plotting. Defaults (i.e.: if None) is to use the list of all variables.
numeric_n_values_threshold (int, optional): How many numbers should be in a column so that it is considered to be a "category"? Defaults to 15.
weighted (bool, optional): If to use the weights with the plots. Defaults to True.
dist_type (Optional[Literal["kde", "qq"]], optional): The type of plot to draw (relevant only for numerical variables). Defaults to None (which fallbacks to "kde").
plot_it (bool, optional): If to plot the plots interactively instead of returning a dictionary. Defaults to True.
return_dict_of_figures (bool, optional): If to return the dictionary containing the plots rather than just returning None. Defaults to False.
If returned - the dictionary is of plots.
Keys in this dictionary are the variable names for each plot.
Values are plotly plot objects plotted like:
offline.iplot(dict_of_all_plots['age'])
Or simply:
dict_of_all_plots['age']
ylim (Optional[Tuple[float, float]], optional): A tuple with two float values representing the lower and upper limits of the y-axis.
If not provided, the y-axis range is determined automatically. Defaults to None.
passed to bar plots only.
**kwargs: Additional keyword arguments to pass to the update_layout method of the plotly figure object. (e.g.: width and height are 700 and 450, and could be set using the kwargs).
Returns:
Optional[Dict[str, go.Figure]]: Dictionary containing plots if return_dict_of_figures is True. None otherwise.
Examples:
::
import numpy as np
import pandas as pd
from numpy import random
from balance.stats_and_plots.weighted_comparisons_plots import plotly_plot_dist
random.seed(96483)
df = pd.DataFrame({
'v1': random.random_integers(11111, 11114, size=100).astype(str),
'v2': random.normal(size = 100),
'v3': random.uniform(size = 100),
}).sort_values(by=['v2'])
dict_of_dfs = {
"self": pd.concat([df, pd.Series(random.random(size = 100) + 0.5, name = "weight")], axis = 1),
"unadjusted": pd.concat([df, pd.Series(np.ones(99).tolist() + [1000], name = "weight")], axis = 1),
"target": pd.concat([df, pd.Series(np.ones(100), name = "weight")], axis = 1),
}
plotly_plot_dist(dict_of_dfs)
# Make sure the bar plot is plotted with y in the range of 0 to 1.
plotly_plot_dist(dict_of_dfs, ylim = (0,1))
# See the qqplots version
plotly_plot_dist(dict_of_dfs, dist_type="qq")
"""
dict_of_all_plots = {}
# Choose set of variables to plot
variables = choose_variables(
*(dict_of_dfs[name] for name in dict_of_dfs), variables=variables
)
variables = [v for v in variables if v != "weight"]
logger.debug(f"plotting variables {variables}")
# TODO: patch choose_variables to return outcome_types from multiple_objects
# find numeric values, using 'sample' df. If for some reason sample is
# not an option, use a random df.
if "sample" in dict_of_dfs:
numeric_variables = (
dict_of_dfs["sample"].select_dtypes(exclude=["object"]).columns.values
)
else:
numeric_variables = (
dict_of_dfs[random.choice(list(dict_of_dfs.keys()))]
.select_dtypes(exclude=["object"])
.columns.values
)
for _, o in enumerate(variables):
# Find the maximum number of non-missing values of this variable accross
# all the dataframes
# Look at the first element in the dict: (name, type and values)
logger.debug(list(dict_of_dfs.keys())[0])
logger.debug(type(dict_of_dfs[list(dict_of_dfs.keys())[0]].loc[:, o].values))
logger.debug(dict_of_dfs[list(dict_of_dfs.keys())[0]].loc[:, o].values)
n_values = max(
len(set(rm_mutual_nas(dict_of_dfs[name].loc[:, o].values)))
for name in dict_of_dfs
)
if n_values == 0:
logger.warning(f"No nonmissing values for variable '{o}', skipping")
continue
# Plot categorical variables as histogram
categorical = (o not in numeric_variables) or (
n_values < numeric_n_values_threshold
)
if (dist_type is None) or dist_type == "kde":
plotly_numeric_plot = plotly_plot_density
elif dist_type == "qq":
plotly_numeric_plot = plotly_plot_qq
else:
raise NotImplementedError(
f"dist_type of type {dist_type} is not implemented."
)
# the below functions will create plotly plots
if categorical:
dict_of_plot = plotly_plot_bar(
dict_of_dfs, [o], plot_it, return_dict_of_figures, ylim=ylim, **kwargs
)
else:
# plotly_plot_density
dict_of_plot = plotly_numeric_plot(
dict_of_dfs, [o], plot_it, return_dict_of_figures, **kwargs
)
# the below functions will add the plotly dict outputs
# to the dictionary 'dict_of_all_plots' (if return_dict_of_figures is True).
if dict_of_plot is not None and return_dict_of_figures:
dict_of_all_plots.update(dict_of_plot)
if return_dict_of_figures:
return dict_of_all_plots
def naming_legend(object_name: str, names_of_dfs: List[str]) -> str:
"""Returns a name for a legend of a plot given the other dfs.
If one of the dfs we would like to plot is "unadjusted", it means
that the Sample object contains the adjusted object as self.
If not, then the self object is sample.
Args:
object_name (str): the name of the object to plot.
names_of_dfs (List[str]): the names of the other dfs to plot.
Returns:
str: a string with the desired name
Examples:
::
naming_legend('self', ['self', 'target', 'unadjusted']) #'adjusted'
naming_legend('unadjusted', ['self', 'target', 'unadjusted']) #'sample'
naming_legend('self', ['self', 'target']) #'sample'
naming_legend('other_name', ['self', 'target']) #'other_name'
"""
if object_name in names_of_dfs:
return {
"unadjusted": "sample",
"self": "adjusted" if "unadjusted" in names_of_dfs else "sample",
"target": "population",
}[object_name]
else:
return object_name
# TODO: set colors of the lines and dots in plots to be fixed by the object name
# (sample, target and adjusted sample).
# See the examples in Balance wiki Diagnostic_Plots page for the current plots
# (the original sample is green when we don't plot the adjusted and red when we are)
################################################################################
# A master plotting function to navigate between seaborn and plotly plots
################################################################################
def plot_dist(
dfs: List[Dict[str, Union[pd.DataFrame, pd.Series]]],
names: Optional[List[str]] = None,
variables: Optional[List[str]] = None,
numeric_n_values_threshold: int = 15,
weighted: bool = True,
dist_type: Optional[Literal["kde", "hist", "qq", "ecdf"]] = None,
library: Literal["plotly", "seaborn"] = "plotly",
ylim: Optional[Tuple[float, float]] = None,
**kwargs,
) -> Union[Union[List, np.ndarray], Dict[str, go.Figure], None]:
"""Plots the variables of a DataFrame by using either seaborn or plotly.
If using plotly then using kde (or qq) plots for numeric variables and bar plots for categorical variables. Uses :func:`plotly_plot_dist`.
If using seaborn then various types of plots are possible for the variables (see dist_type for details). Uses :func:`seaborn_plot_dist`
Args:
dfs (List[Dict[str, Union[pd.DataFrame, pd.Series]]]): a list (of length 1 or more) of dictionaries which describe the DataFrames and weights
The structure is as follows:
[
{'df': pd.DataFrame(...), "weight": pd.Series(...)},
...
]
The 'df' is a DataFrame which includes the column name that was supplied through 'column'.
The "weight" is a pd.Series of weights that are used when aggregating the variable using :func:`relative_frequency_table`.
names (List[str]): a list of the names of the DataFrames that are plotted. E.g.: ['adjusted', 'unadjusted', 'target']
If None, then all DataFrames will be plotted, but only if library == "seaborn". (TODO: to remove this restriction)
variables (Optional[List[str]], optional): a list of variables to use for plotting. Default (i.e.: if None) is to use the list of all variables.
numeric_n_values_threshold (int, optional): How many numbers should be in a column so that it is considered to be a "category"? Defaults to 15.
weighted (bool, optional): If to use the weights with the plots. Defaults to True.
dist_type (Literal["kde", "hist", "qq", "ecdf"], optional): The type of plot to draw. The 'qq' and 'kde' options are available for library="plotly",
While all options are available if using library="seaborn". Defaults to "kde".
library (Literal["plotly", "seaborn"], optional): Whichever library to use for the plot. Defaults to "plotly".
ylim (Optional[Tuple[float, float]], optional): A tuple with two float values representing the lower and upper limits of the y-axis.
If not provided, the y-axis range is determined automatically. Defaults to None.
passed to bar plots only.
**kwargs: Additional keyword arguments to pass to plotly_plot_dist or seaborn_plot_dist.
Raises:
ValueError: if library is not in ("plotly", "seaborn").
Returns:
Union[Union[List, np.ndarray], Dict[str, go.Figure], None]:
If library="plotly" then returns a dictionary containing plots if return_dict_of_figures is True. None otherwise.
If library="seaborn" then returns None, unless return_axes is True. Then either a list or an np.array of matplotlib axis.
Examples:
::
import numpy as np
import pandas as pd
from numpy import random
from balance.stats_and_plots.weighted_comparisons_plots import plotly_plot_bar
random.seed(96483)
df = pd.DataFrame({
'v1': random.random_integers(11111, 11114, size=100).astype(str),
'v2': random.normal(size = 100),
'v3': random.uniform(size = 100),
}).sort_values(by=['v2'])
dfs1 = [
{"df": df, "weight": pd.Series(random.random(size = 100) + 0.5)},
{"df": df, "weight": pd.Series(np.ones(99).tolist() + [1000])},
{"df": df, "weight": pd.Series(np.ones(100))},
]
from balance.stats_and_plots.weighted_comparisons_plots import plot_dist
# defaults to plotly with bar and qq plots. Returns None.
plot_dist(dfs1, names=["self", "unadjusted", "target"])
# Using seaborn, deafults to kde plots
plot_dist(dfs1, names=["self", "unadjusted", "target"], library="seaborn") # like using dist_type = "kde"
plot_dist(dfs1, names=["self", "unadjusted", "target"], library="seaborn", dist_type = "hist")
plot_dist(dfs1, names=["self", "unadjusted", "target"], library="seaborn", dist_type = "qq")
plot_dist(dfs1, names=["self", "unadjusted", "target"], library="seaborn", dist_type = "ecdf")
plot_dist(dfs1, names=["self", "unadjusted", "target"], ylim = (0,1))
plot_dist(dfs1, names=["self", "unadjusted", "target"], library="seaborn", dist_type = "qq", ylim = (0,1))
"""
if library not in ("plotly", "seaborn"):
raise ValueError(f"library must be either 'plotly' or 'seaborn', is {library}")
# Set default names for samples
# TODO: this will work only with seaborn. Will need to change to something that also works for plotly.
if names is None:
names = [f"sample {i}" for i in range(1, len(dfs) + 1)]
if library == "seaborn":
return seaborn_plot_dist(
dfs=dfs,
names=names,
variables=variables,
numeric_n_values_threshold=numeric_n_values_threshold,
weighted=weighted,
dist_type=dist_type,
ylim=ylim,
**kwargs,
)
elif library == "plotly":
dict_of_dfs = dict(
zip(
names,
(
pd.concat((d["df"], pd.Series(d["weight"], name="weight")), axis=1)
for d in dfs
),
)
)
if dist_type is not None:
logger.warning("plotly plots ignore dist_type. Consider library='seaborn'")
return plotly_plot_dist(
dict_of_dfs,
variables,
numeric_n_values_threshold,
weighted,
# pyre-ignore[6]: plotly_plot_dist will raise a NotImplemented error if dist_type is not None, 'kde', or 'qq'
dist_type=dist_type,
ylim=ylim,
**kwargs,
)
# TODO: add plots to compare ASMD
| balance-main | balance/stats_and_plots/weighted_comparisons_plots.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
| balance-main | balance/stats_and_plots/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from typing import List, Literal, Optional, Tuple, Union
import numpy as np
import pandas as pd
from balance.stats_and_plots.weights_stats import _check_weights_are_valid
from balance.util import model_matrix, rm_mutual_nas
from scipy.stats import norm
from statsmodels.stats.weightstats import DescrStatsW
logger: logging.Logger = logging.getLogger(__package__)
##########################################
# Weighted statistics
##########################################
def _prepare_weighted_stat_args(
v: Union[ # pyre-ignore[11]: np.matrix is a type
List,
pd.Series,
pd.DataFrame,
np.ndarray,
np.matrix,
],
w: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
inf_rm: bool = False,
) -> Tuple[pd.DataFrame, pd.Series]:
"""
Checks that the values (v) and weights (w) are of the supported types and of the same length. Can also replace np.Inf to np.nan.
Args:
v (Union[List, pd.Series, pd.DataFrame, np.ndarray, np.matrix,]): a series of values. Notice that pd.DataFrame and np.matrix should store the Series/np.ndarry as columns (not rows).
w (Union[List, pd.Series, np.ndarray, None]): a series of weights to be used with v (could also be none). Defaults to None.
inf_rm (bool, optional): should np.inf values be replaced by np.nan? Defaults to False.
Returns:
Tuple[pd.DataFrame, pd.Series]: the original v and w after they have been validated, and turned to pd.DataFrame and pd.Series (if needed).
The values might be int64 or float64, depending on the input.
"""
supported_types = (
list,
pd.Series,
np.ndarray,
)
tmp_supported_types = supported_types + (
pd.DataFrame,
np.matrix,
)
if type(v) not in tmp_supported_types:
raise TypeError(f"argument must be {tmp_supported_types}, is {type(v)}")
tmp_supported_types = supported_types + (type(None),)
if type(w) not in supported_types + (type(None),):
raise TypeError(f"argument must be {tmp_supported_types}, is {type(w)}")
# NOTE: np.matrix is an instance of np.ndarray, so we must turn it to pd.Dataframe before moving forward.
if isinstance(v, np.matrix):
v = pd.DataFrame(v)
if isinstance(v, np.ndarray) or isinstance(v, list):
v = pd.Series(v)
if isinstance(v, pd.Series):
v = v.to_frame()
if isinstance(w, np.ndarray) or isinstance(w, list):
w = pd.Series(w)
if w is None:
w = pd.Series(np.ones(len(v)), index=v.index)
if v.shape[0] != w.shape[0]:
raise ValueError(
f"weights (w) and data (v) must have same number of rows, ({v.shape[0]}, {w.shape[0]})"
)
dtypes = v.dtypes if hasattr(v.dtypes, "__iter__") else [v.dtypes]
if not all(np.issubdtype(x, np.number) for x in dtypes):
raise TypeError("all columns must be numeric")
if inf_rm:
v = v.replace([np.inf, -np.inf], np.nan)
w = w.replace([np.inf, -np.inf], np.nan)
v = v.reset_index(drop=True)
w = w.reset_index( # pyre-ignore[16]: w is a pd.Series which has a reset_index method.
drop=True
)
_check_weights_are_valid(w)
return v, w
def weighted_mean(
v: Union[
List,
pd.Series,
pd.DataFrame,
np.matrix,
],
w: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
inf_rm: bool = False,
) -> pd.Series:
"""
Computes the weighted average of a pandas Series or DataFrame.
If no weights are supplied, it just computes the simple arithmetic mean.
See:
https://en.wikipedia.org/wiki/Weighted_arithmetic_mean
Uses :func:`_prepare_weighted_stat_args`.
Args:
v (Union[ List, pd.Series, pd.DataFrame, np.matrix, ]): values to average. None (or np.nan) values are treated like 0.
If v is a DataFrame than the average of the values from each column will be returned, all using the same set of weights from w.
w (Union[ List, pd.Series], optional): weights. Defaults to None.
If there is None value in the weights, that value will be ignored from the calculation.
inf_rm (bool, optional): whether to remove infinite (from weights or values) from the computation. Defaults to False.
Returns:
pd.Series(dtype=np.float64): The weighted mean.
If v is a DataFrame with several columns than the pd.Series will have a value for the weighted mean of each of the columns.
If inf_rm=False then:
If v has Inf then the output will be Inf.
If w has Inf then the output will be np.nan.
Examples:
::
from balance.stats_and_plots.weighted_stats import weighted_mean
weighted_mean(pd.Series((1, 2, 3, 4)))
# 0 2.5
# dtype: float64
weighted_mean(pd.Series((1, 2, 3, 4)), pd.Series((1, 2, 3, 4)))
# 0 3.0
# dtype: float64
df = pd.DataFrame(
{"a": [1,2,3,4], "b": [1,1,1,1]}
)
w = pd.Series((1, 2, 3, 4))
weighted_mean(df, w)
# a 3.0
# b 1.0
# dtype: float64
"""
v, w = _prepare_weighted_stat_args(v, w, inf_rm)
return v.multiply(w, axis="index").sum() / w.sum()
def var_of_weighted_mean(
v: Union[List, pd.Series, pd.DataFrame, np.matrix],
w: Optional[Union[List, pd.Series, np.ndarray]] = None,
inf_rm: bool = False,
) -> pd.Series:
"""
Computes the variance of the weighted average (pi estimator for ratio-mean) of a list of values and their corresponding weights.
If no weights are supplied, it assumes that all values have equal weights of 1.0.
See: https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Variance_of_the_weighted_mean_(%CF%80-estimator_for_ratio-mean)
Uses :func:`_prepare_weighted_stat_args`.
v (Union[List, pd.Series, pd.DataFrame, np.matrix]): A series of values. If v is a DataFrame, the weighted variance will be calculated for each column using the same set of weights from `w`.
w (Optional[Union[List, pd.Series, np.ndarray]]): A series of weights to be used with `v`. If None, all values will be weighted equally.
inf_rm (bool, optional): Whether to remove infinite (from weights or values) from the computation. Defaults to False.
Returns:
pd.Series: The variance of the weighted mean. If `v` is a DataFrame with several columns, the pd.Series will have a value for the weighted variance of each column. The values are of data type `np.float64`.
If `inf_rm` is False:
If `v` has infinite values, the output will be `Inf`.
If `w` has infinite values, the output will be `np.nan`.
Examples:
::
from balance.stats_and_plots.weighted_stats import var_of_weighted_mean
# In R: sum((1:4 - mean(1:4))^2 / 4) / (4)
# [1] 0.3125
var_of_weighted_mean(pd.Series((1, 2, 3, 4)))
# pd.Series(0.3125)
# For a reproducible R example, see: https://gist.github.com/talgalili/b92cd8cdcbfc287e331a8f27db265c00
var_of_weighted_mean(pd.Series((1, 2, 3, 4)), pd.Series((1, 2, 3, 4)))
# pd.Series(0.24)
df = pd.DataFrame(
{"a": [1,2,3,4], "b": [1,1,1,1]}
)
w = pd.Series((1, 2, 3, 4))
var_of_weighted_mean(df, w)
# a 0.24
# b 0.00
# dtype: float64
"""
v, w = _prepare_weighted_stat_args(v, w, inf_rm)
weighed_mean_of_v = weighted_mean(v, w, inf_rm) # This is a pd.Series
# NOTE: the multiply needs to be called from the pd.Series. Unfortunately this makes the code less readable.
sum_of_squared_weighted_diffs = (
((v - weighed_mean_of_v).multiply(w, axis="index")).pow(2).sum()
)
squared_sum_of_w = w.sum() ** 2 # This is a pd.series
return sum_of_squared_weighted_diffs / squared_sum_of_w
def ci_of_weighted_mean(
v: Union[List[float], pd.Series, pd.DataFrame, np.ndarray],
w: Optional[Union[List[float], pd.Series, np.ndarray]] = None,
conf_level: float = 0.95,
round_ndigits: Optional[int] = None,
inf_rm: bool = False,
) -> pd.Series:
"""
Computes the confidence interval of the weighted mean of a list of values and their corresponding weights.
If no weights are supplied, it assumes that all values have equal weights of 1.0.
v (Union[List[float], pd.Series, pd.DataFrame, np.ndarray]): A series of values. If v is a DataFrame, the weighted mean and its confidence interval will be calculated for each column using the same set of weights from `w`.
w (Optional[Union[List[float], pd.Series, np.ndarray]]): A series of weights to be used with `v`. If None, all values will be weighted equally.
conf_level (float, optional): Confidence level for the interval, between 0 and 1. Defaults to 0.95.
round_ndigits (Optional[int], optional): Number of decimal places to round the confidence interval. If None, the values will not be rounded. Defaults to None.
inf_rm (bool, optional): Whether to remove infinite (from weights or values) from the computation. Defaults to False.
Returns:
pd.Series: The confidence interval of the weighted mean. If `v` is a DataFrame with several columns, the pd.Series will have a value for the confidence interval of each column. The values are of data type Tuple[np.float64, np.float64].
If `inf_rm` is False:
If `v` has infinite values, the output will be `Inf`.
If `w` has infinite values, the output will be `np.nan`.
Examples:
::
from balance.stats_and_plots.weighted_stats import ci_of_weighted_mean
ci_of_weighted_mean(pd.Series((1, 2, 3, 4)))
# 0 (1.404346824279273, 3.5956531757207273)
# dtype: object
ci_of_weighted_mean(pd.Series((1, 2, 3, 4)), round_ndigits = 3).to_list()
# [(1.404, 3.596)]
ci_of_weighted_mean(pd.Series((1, 2, 3, 4)), pd.Series((1, 2, 3, 4)))
# 0 (2.039817664728938, 3.960182335271062)
# dtype: object
ci_of_weighted_mean(pd.Series((1, 2, 3, 4)), pd.Series((1, 2, 3, 4)), round_ndigits = 3).to_list()
# [(2.04, 3.96)]
df = pd.DataFrame(
{"a": [1,2,3,4], "b": [1,1,1,1]}
)
w = pd.Series((1, 2, 3, 4))
ci_of_weighted_mean(df, w, conf_level = 0.99, round_ndigits = 3)
# a (1.738, 4.262)
# b (1.0, 1.0)
# dtype: object
ci_of_weighted_mean(df, w, conf_level = 0.99, round_ndigits = 3).to_dict()
# {'a': (1.738, 4.262), 'b': (1.0, 1.0)}
"""
v, w = _prepare_weighted_stat_args(v, w, inf_rm)
weighed_mean_of_v = weighted_mean(v, w, inf_rm)
var_weighed_mean_of_v = var_of_weighted_mean(v, w, inf_rm)
z_value = norm.ppf((1 + conf_level) / 2)
if isinstance(v, pd.Series):
ci_index = v.index
elif isinstance(v, pd.DataFrame):
ci_index = v.columns
else:
ci_index = None
ci = pd.Series(
[
(
weighed_mean_of_v[i] - z_value * np.sqrt(var_weighed_mean_of_v[i]),
weighed_mean_of_v[i] + z_value * np.sqrt(var_weighed_mean_of_v[i]),
)
for i in range(len(weighed_mean_of_v))
],
index=ci_index,
)
if round_ndigits is not None:
# Apply a lambda function to round a pd.Series of tuples to x decimal places
ci = ci.apply(lambda t: tuple(round(x, round_ndigits) for x in t))
# pyre-ignore[7]: pyre thinks this function could return a DataFrame because of ci = ci.apply(round_tuple). It's wrong.
return ci
def weighted_var(
v: Union[
List,
pd.Series,
pd.DataFrame,
np.ndarray,
np.matrix,
],
w: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
inf_rm: bool = False,
) -> pd.Series:
"""
Calculate the sample weighted variance (a.k.a 'reliability weights').
This is described here:
https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Reliability_weights_2
And also used in SDMTools, see:
https://www.gnu.org/software/gsl/doc/html/statistics.html#weighted-samples
Uses :func:`weighted_mean` and :func:`_prepare_weighted_stat_args`.
Args:
v (Union[ List, pd.Series, pd.DataFrame, np.matrix, ]): values to get the weighted variance for. None values are treated like 0.
If v is a DataFrame than the average of the values from each column will be returned, all using the same set of weights from w.
w (Union[ List, pd.Series], optional): weights. Defaults to None.
If there is None value in the weights, that value will be ignored from the calculation.
inf_rm (bool, optional): whether to remove infinite (from weights or values) from the computation. Defaults to False.
Returns:
pd.Series[np.float64]: The weighted variance.
If v is a DataFrame with several columns than the pd.Series will have a value for the weighted mean of each of the columns.
If inf_rm=False then:
If v has Inf then the output will be Inf.
If w has Inf then the output will be np.nan.
"""
v, w = _prepare_weighted_stat_args(v, w, inf_rm)
means = weighted_mean(v, w)
v1 = w.sum()
v2 = (w**2).sum()
return (v1 / (v1**2 - v2)) * ((v - means) ** 2).multiply(w, axis="index").sum()
def weighted_sd(
v: Union[
List,
pd.Series,
pd.DataFrame,
np.matrix,
],
w: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
inf_rm: bool = False,
) -> pd.Series:
"""Calculate the sample weighted standard deviation
See :func:`weighted_var` for details.
Args:
v (Union[ List, pd.Series, pd.DataFrame, np.matrix, ]): Values.
w (Union[ List, pd.Series, np.ndarray, None, ], optional): Weights. Defaults to None.
inf_rm (bool, optional): Remove inf. Defaults to False.
Returns:
pd.Series: np.sqrt of :func:`weighted_var` (np.float64)
"""
return np.sqrt(weighted_var(v, w, inf_rm))
def weighted_quantile(
v: Union[
List,
pd.Series,
pd.DataFrame,
np.ndarray,
np.matrix,
],
quantiles: Union[
List,
pd.Series,
np.ndarray,
],
w: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
inf_rm: bool = False,
) -> pd.DataFrame:
"""
Calculates the weighted quantiles (q) of values (v) based on weights (w).
See :func:`_prepare_weighted_stat_args` for the pre-processing done to v and w.
Based on :func:`statsmodels.stats.weightstats.DescrStatsW`.
Args:
v (Union[ List, pd.Series, pd.DataFrame, np.array, np.matrix, ]): values to get the weighted quantiles for.
quantiles (Union[ List, pd.Series, ]): the quantiles to calculate.
w (Union[ List, pd.Series, np.array, ] optional): weights. Defaults to None.
inf_rm (bool, optional): whether to remove infinite (from weights or values) from the computation. Defaults to False.
Returns:
pd.DataFrame: The index (names p) has the values from quantiles. The columns are based on v:
If it's a pd.Series it's one column, if it's a pd.DataFrame with several columns, than each column
in the output corrosponds to the column in v.
"""
v, w = _prepare_weighted_stat_args(v, w, inf_rm)
v = np.array(v)
w = np.array(w)
quantiles = np.array(quantiles)
d = DescrStatsW(v.astype(float), weights=w)
return d.quantile(quantiles)
def descriptive_stats(
df: pd.DataFrame,
weights: Union[
List,
pd.Series,
np.ndarray,
None,
] = None,
stat: Literal["mean", "std", "var_of_mean", "ci_of_mean", "..."] = "mean",
# relevant only if stat is None
weighted: bool = True,
# relevant only if we have non-numeric columns and we want to use model_matrix on them
numeric_only: bool = False,
add_na: bool = True,
**kwargs,
) -> pd.DataFrame:
"""Computes weighted statistics (e.g.: mean, std) on a DataFrame
This function gets a DataFrame + weights and apply some weighted aggregation function (mean, std, or DescrStatsW).
The main benefit of the function is that if the DataFrame includes non-numeric columns, then descriptive_stats will first
run :func:`model_matrix` to create some numeric dummary variable that will then be processed.
Args:
df (pd.DataFrame): Some DataFrame to get stats (mean, std, etc.) for.
weights (Union[ List, pd.Series, np.ndarray, ], optional): Weights to apply for the computation. Defaults to None.
stat (Literal["mean", "std", "var_of_mean", ...], optional): Which statistic to calculate on the data.
If mean - uses :func:`weighted_mean` (with inf_rm=True)
If std - uses :func:`weighted_sd` (with inf_rm=True)
If var_of_mean - uses :func:`var_of_weighted_mean` (with inf_rm=True)
If ci_of_mean - uses :func:`ci_of_weighted_mean` (with inf_rm=True)
If something else - tries to use :func:`statsmodels.stats.weightstats.DescrStatsW`.
This supports stat such as: std_mean, sum_weights, nobs, etc. See function documentation to see more.
(while removing mutual nan using :func:`rm_mutual_nas`)
Defaults to "mean".
weighted (bool, optional): If stat is not "mean" or "std", if to use the weights with the DescrStatsW function.
Defaults to True.
numeric_only (bool, optional): Should the statistics be computed only on numeric columns?
If True - then non-numeric columns will be omitted.
If False - then :func:`model_matrix` (with no formula argument) will be used to transfer non-numeric columns to dummy variables.
Defaults to False.
add_na (bool, optional): Passed to :func:`model_matrix`.
Relevant only if numeric_only == False and df has non-numeric columns.
Defaults to True.
**kwargs: extra args to be passed to functions (e.g.: ci_of_weighted_mean)
Returns:
pd.DataFrame: Returns pd.DataFrame of the output (based on stat argument), for each of the columns in df.
Examples:
::
import numpy as np
import pandas as pd
from balance.stats_and_plots.weighted_stats import descriptive_stats, weighted_mean, weighted_sd
# Without weights
x = [1, 2, 3, 4]
print(descriptive_stats(pd.DataFrame(x), stat="mean"))
print(np.mean(x))
print(weighted_mean(x))
# 0
# 0 2.5
# 2.5
# 0 2.5
# dtype: float64
print(descriptive_stats(pd.DataFrame(x), stat="var_of_mean"))
# 0
# 0 0.3125
print(descriptive_stats(pd.DataFrame(x), stat="std"))
print(weighted_sd(x))
x2 = pd.Series(x)
print(np.sqrt( np.sum((x2 - x2.mean())**2) / (len(x)-1) ))
# 0
# 0 1.290994
# 0 1.290994
# dtype: float64
# 1.2909944487358056
# Notice that it is different from
# print(np.std(x))
# which gives: 1.118033988749895
# Which is the MLE (i.e.: biased, dividing by n and not n-1) estimator for std:
# (np.sqrt( np.sum((x2 - x2.mean())**2) / (len(x)) ))
x2 = pd.Series(x)
tmp_sd = np.sqrt(np.sum((x2 - x2.mean()) ** 2) / (len(x) - 1))
tmp_se = tmp_sd / np.sqrt(len(x))
print(descriptive_stats(pd.DataFrame(x), stat="std_mean").iloc[0, 0])
print(tmp_se)
# 0.6454972243679029
# 0.6454972243679028
# Weighted results
x, w = [1, 2, 3, 4], [1, 2, 3, 4]
print(descriptive_stats(pd.DataFrame(x), w, stat="mean"))
# 0
# 0 3.0
print(descriptive_stats(pd.DataFrame(x), w, stat="std"))
# 0
# 0 1.195229
print(descriptive_stats(pd.DataFrame(x), w, stat="std_mean"))
# 0
# 0 0.333333
print(descriptive_stats(pd.DataFrame(x), w, stat="var_of_mean"))
# 0
# 0 0.24
print(descriptive_stats(pd.DataFrame(x), w, stat="ci_of_mean", conf_level = 0.99, round_ndigits=3))
# 0
# 0 (1.738, 4.262)
"""
if len(df.select_dtypes(np.number).columns) != len(df.columns):
# If we have non-numeric columns, and want faster results,
# then we can set numeric_only == True.
# This will skip the model_matrix computation for non-numeric variables.
if numeric_only:
# TODO: (p2) does this check takes a long time?
# if it does - then maybe add an option of numeric_only = None
# to just use df as is.
df = df.select_dtypes(include=[np.number])
else:
# TODO: add the ability to pass formula argument to model_matrix
df = model_matrix( # pyre-ignore[9]: this uses the DataFrame onlyÍ
df, add_na=add_na, return_type="one"
)["model_matrix"]
if stat == "mean":
return weighted_mean(df, weights, inf_rm=True).to_frame().transpose()
elif stat == "std":
return weighted_sd(df, weights, inf_rm=True).to_frame().transpose()
elif stat == "var_of_mean":
return var_of_weighted_mean(df, weights, inf_rm=True).to_frame().transpose()
elif stat == "ci_of_mean":
conf_level = kwargs.get("conf_level", 0.95)
round_ndigits = kwargs.get("round_ndigits", None)
return (
ci_of_weighted_mean(
df,
weights,
inf_rm=True,
conf_level=conf_level,
round_ndigits=round_ndigits,
)
.to_frame()
.transpose()
)
# TODO: (p2) check which input DescrStatsW takes, not sure we need to run the next two lines.
if weights is not None:
weights = pd.Series(weights)
# TODO: (p2) consider to remove the "weighted" argument, and just use
# whatever is passed to "weights" (if None, than make sure it's replaced with 1s)
# Fallback to statsmodels function
_check_weights_are_valid(weights)
wdf = {}
for c in df.columns.values:
df_c, w = rm_mutual_nas(df.loc[:, c], weights)
wdf[c] = [getattr(DescrStatsW(df_c, w if weighted else None), stat)]
return pd.DataFrame(wdf)
def relative_frequency_table(
df: Union[pd.DataFrame, pd.Series],
column: Optional[str] = None,
w: Optional[pd.Series] = None,
) -> pd.DataFrame:
"""Creates a relative frequency table by aggregating over a categorical column (`column`) - optionally weighted by `w`.
I.e.: produce the proportion (or weighted proportion) of rows that appear in each category, relative to the total number of rows (or sum of weights).
See: https://en.wikipedia.org/wiki/Frequency_(statistics)#Types.
Used in plotting functions.
Args:
df (pd.DataFrame): A DataFrame with categorical columns, or a pd.Series of the grouping column.
column (Optional[str]): The name of the column to be aggregated.
If None (default), then it takes the first column of df (if pd.DataFrame), or just uses as is (if pd.Series)
w (Optional[pd.Series], optional): Optional weights to use when aggregating the relative proportions.
If None than assumes weights is 1 for all rows. The defaults is None.
Returns:
pd.DataFrame: a pd.DataFrame with columns:
- `column`, the aggregation variable, and,
- 'prop', the aggregated (weighted) proportion of rows from each group in 'column'.
Examples:
::
from balance.stats_and_plots.weighted_stats import relative_frequency_table
import pandas as pd
df = pd.DataFrame({
'group': ('a', 'b', 'c', 'c'),
'v1': (1, 2, 3, 4),
})
print(relative_frequency_table(df, 'group'))
# group prop
# 0 a 0.25
# 1 b 0.25
# 2 c 0.50
print(relative_frequency_table(df, 'group', pd.Series((2, 1, 1, 1),)))
# group prop
# 0 a 0.4
# 1 b 0.2
# 2 c 0.4
# Using a pd.Series:
a_series = df['group']
print(relative_frequency_table(a_series))
# group prop
# 0 a 0.25
# 1 b 0.25
# 2 c 0.50
"""
_check_weights_are_valid(w)
if not (w is None or isinstance(w, pd.Series)):
raise TypeError("argument `w` must be a pandas Series or None")
if w is None:
w = pd.Series(np.ones(df.shape[0]))
# pyre-ignore[6]: this is a pyre bug. str inherits from hashable, and .rename works fine.
w = w.rename("Freq")
if column is None:
if isinstance(df, pd.DataFrame):
column = df.columns.values[0]
elif isinstance(df, pd.Series):
if df.name is None:
df.name = "group"
column = df.name
else:
raise TypeError("argument `df` must be a pandas DataFrame or Series")
# pyre-ignore[6]: this is a bug. pd.concat can deal with a DataFrame and a Series.
relative_frequency_table_data = pd.concat((df, w), axis=1)
relative_frequency_table_data = relative_frequency_table_data.groupby(
column, as_index=False
).sum()
relative_frequency_table_data["prop"] = relative_frequency_table_data["Freq"] / sum(
relative_frequency_table_data["Freq"]
)
return relative_frequency_table_data.loc[:, (column, "prop")]
| balance-main | balance/stats_and_plots/weighted_stats.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from typing import Any, Dict, List, Tuple, Union
import numpy as np
import pandas as pd
logger: logging.Logger = logging.getLogger(__package__)
##########################################
# Weights diagnostics - functions for analyzing weights
##########################################
def _check_weights_are_valid(
w: Union[
List,
pd.Series,
np.ndarray,
pd.DataFrame,
None,
]
) -> None:
"""Check weights.
Args:
w (Union[ List, pd.Series, np.ndarray, pd.DataFrame, None, ]): input weights.
If w is pd.DataFrame then only the first column will be checked (assuming it is a column of weights).
If input is None, then the function returns None with no errors (since None is a valid weights input for various functions).
Raises:
ValueError: if weights are not numeric.
ValueError: if weights include a negative value.
Returns:
_type_: None
"""
if w is None:
return None
if isinstance(w, pd.DataFrame):
w = w.iloc[:, 0] # if DataFrame, we check only the first column.
if not isinstance(w, pd.Series):
w = pd.Series(w)
# TODO: (p2) consider having a check for each type of w, instead of
# turning w into pd.Series (since this solution might not be very efficient)
if not np.issubdtype(w, np.number):
raise TypeError(
f"weights (w) must be a number but instead they are of type: {w.dtype}."
)
if any(w < 0):
raise ValueError("weights (w) must all be non-negative values.")
# TODO: do we also want to verify that at least one weight is larger than 0?!
return None
# TODO: if the input is pd.DataFrame than the output will be pd.Series.
# we could make the support of this more official in the future.
def design_effect(w: pd.Series) -> np.float64:
"""
Kish's design effect measure.
For details, see:
- https://en.wikipedia.org/wiki/Design_effect
- https://en.wikipedia.org/wiki/Effective_sample_size
Args:
w (pd.Series): A pandas series of weights (non negative, float/int) values.
Returns:
np.float64: An estimator saying by how much the variance of the mean is expected to increase, compared to a random sample mean,
due to application of the weights.
Examples:
::
from balance.stats_and_plots.weights_stats import design_effect
import pandas as pd
design_effect(pd.Series((0, 1, 2, 3)))
# output:
# 1.5555555555555556
design_effect(pd.Series((1, 1, 1000)))
# 2.9880418803112336
# As expected. With a single dominating weight - the Deff is almost equal to the sample size.
"""
_check_weights_are_valid(w)
return (w**2).mean() / (w.mean() ** 2)
def nonparametric_skew(w: pd.Series) -> np.float64:
# TODO (p2): consider adding other skew measures (https://en.wikipedia.org/wiki/Skewness)
# look more in the literature (are there references for using this vs another, or none at all?)
# update the doc with insights, once done:
# what is more accepted in the literature in the field and what are the advantages of each.
# Any reference to literature where this is used to analyze weights of survey?
# Add reference to some interpretation of these values?
"""
The nonparametric skew is the difference between the mean and the median, divided by the standard deviation.
See:
- https://en.wikipedia.org/wiki/Nonparametric_skew
Args:
w (pd.Series): A pandas series of weights (non negative, float/int) values.
Returns:
np.float64: A value of skew, between -1 to 1, but for weights it's often positive (i.e.: right tailed distribution).
The value returned will be 0 if the standard deviation is 0 (i.e.: all values are identical), or if the input is of length 1.
Examples:
::
from balance.stats_and_plots.weights_stats import nonparametric_skew
nonparametric_skew(pd.Series((1, 1, 1, 1))) # 0
nonparametric_skew(pd.Series((1))) # 0
nonparametric_skew(pd.Series((1, 2, 3, 4))) # 0
nonparametric_skew(pd.Series((1, 1, 1, 2))) # 0.5
nonparametric_skew(pd.Series((-1,1,1, 1))) #-0.5
"""
_check_weights_are_valid(w)
if (len(w) == 1) or (w.std() == 0):
return np.float64(0)
return (w.mean() - w.median()) / w.std()
def prop_above_and_below(
w: pd.Series,
below: Union[Tuple[float, ...], List[float], None] = (
1 / 10,
1 / 5,
1 / 3,
1 / 2,
1,
),
above: Union[Tuple[float, ...], List[float], None] = (1, 2, 3, 5, 10),
return_as_series: bool = True,
) -> Union[pd.Series, Dict[Any, Any], None]:
# TODO (p2): look more in the literature (are there references for using this vs another, or none at all?)
# update the doc with insights, once done.
"""
The proportion of weights, normalized to sample size, that are above and below some numbers (E.g. 1,2,3,5,10 and their inverse: 1, 1/2, 1/3, etc.).
This is similar to returning percentiles of the (normalized) weighted distribution. But instead of focusing on the 25th percentile, the median, etc,
We focus instead on more easily interpretable weights values.
For example, saying that some proportion of users had a weight of above 1 gives us an indication of how many users
we got that we don't "loose" their value after using the weights. Saying which proportion of users had a weight below 1/10 tells us how many users
had basically almost no contribution to the final analysis (after applying the weights).
Note that below and above can overlap, be unordered, etc. The user is responsible for the order.
Args:
w (pd.Series): A pandas series of weights (float, non negative) values.
below (Union[Tuple[float, ...], List[float], None], optional):
values to check which proportion of normalized weights are *below* them.
Using None returns None.
Defaults to (1/10, 1/5, 1/3, 1/2, 1).
above (Union[Tuple[float, ...], List[float], None], optional):
values to check which proportion of normalized weights are *above* (or equal) to them.
Using None returns None.
Defaults to (1, 2, 3, 5, 10).
return_as_series (bool, optional): If true returns one pd.Series of values.
If False will return a dict with two pd.Series (one for below and one for above).
Defaults to True.
Returns:
Union[pd.Series, Dict]:
If return_as_series is True we get pd.Series with proportions of (normalized weights)
that are below/above some numbers, the index indicates which threshold was checked
(the values in the index are rounded up to 3 points for printing purposes).
If return_as_series is False we get a dict with 'below' and 'above' with the relevant pd.Series (or None).
Examples:
::
from balance.stats_and_plots.weights_stats import prop_above_and_below
import pandas as pd
# normalized weights:
print(pd.Series((1, 2, 3, 4)) / pd.Series((1, 2, 3, 4)).mean())
# 0 0.4
# 1 0.8
# 2 1.2
# 3 1.6
# checking the function:
prop_above_and_below(pd.Series((1, 2, 3, 4)))
# dtype: float64
# prop(w < 0.1) 0.00
# prop(w < 0.2) 0.00
# prop(w < 0.333) 0.00
# prop(w < 0.5) 0.25
# prop(w < 1.0) 0.50
# prop(w >= 1) 0.50
# prop(w >= 2) 0.00
# prop(w >= 3) 0.00
# prop(w >= 5) 0.00
# prop(w >= 10) 0.00
# dtype: float64
prop_above_and_below(pd.Series((1, 2, 3, 4)), below = (0.1, 0.5), above = (2,3))
# prop(w < 0.1) 0.00
# prop(w < 0.5) 0.25
# prop(w >= 2) 0.00
# prop(w >= 3) 0.00
# dtype: float64
prop_above_and_below(pd.Series((1, 2, 3, 4)), return_as_series = False)
# {'below': prop(w < 0.1) 0.00
# prop(w < 0.2) 0.00
# prop(w < 0.333) 0.00
# prop(w < 0.5) 0.25
# prop(w < 1) 0.50
# dtype: float64, 'above': prop(w >= 1) 0.5
# prop(w >= 2) 0.0
# prop(w >= 3) 0.0
# prop(w >= 5) 0.0
# prop(w >= 10) 0.0
# dtype: float64}
"""
_check_weights_are_valid(w)
# normalize weight to sample size:
w = w / w.mean()
if below is None and above is None:
return None
# calculate props from below:
if below is not None:
prop_below = [(w < i).mean() for i in below]
prop_below_index = ["prop(w < " + str(round(i, 3)) + ")" for i in below]
prop_below_series = pd.Series(prop_below, index=prop_below_index)
else:
prop_below_series = None
# calculate props from above:
if above is not None:
prop_above = [(w >= i).mean() for i in above]
prop_above_index = ["prop(w >= " + str(round(i, 3)) + ")" for i in above]
prop_above_series = pd.Series(prop_above, index=prop_above_index)
else:
prop_above_series = None
# decide if to return one series or a dict
if return_as_series:
out = pd.concat(
[ # pyre-ignore[6]: pd.concat supports Series.
prop_below_series,
prop_above_series,
]
)
else:
out = {"below": prop_below_series, "above": prop_above_series}
return out # pyre-ignore[7]: TODO: see if we can fix this pyre
def weighted_median_breakdown_point(w: pd.Series) -> np.float64:
# TODO (p2): do we want to have weighted_quantile_breakdown_point
# so to check for quantiles other than 50%?
"""
Calculates the minimal percent of users that have at least 50% of the weights.
This gives us the breakdown point of calculating the weighted median.
This can be thought of as reflecting a similar metric to the design effect.
See also:
- https://en.wikipedia.org/wiki/Weighted_median
- https://en.wikipedia.org/wiki/Robust_statistics#Breakdown_point
Args:
w (pd.Series): A pandas series of weights (float, non negative values).
Returns:
np.float64: A minimal percent of users that contain at least 50% of the weights.
Examples:
::
w = pd.Series([1,1,1,1])
print(weighted_median_breakdown_point(w)) # 0.5
w = pd.Series([2,2,2,2])
print(weighted_median_breakdown_point(w)) # 0.5
w = pd.Series([1,1,1, 10])
print(weighted_median_breakdown_point(w)) # 0.25
w = pd.Series([1,1,1,1, 10])
print(weighted_median_breakdown_point(w)) # 0.2
"""
_check_weights_are_valid(w)
# normalize weight to sample size:
n = len(w) # n users
w = w / w.sum() # normalize to 1
# get a cumsum of sorted weights to find the median:
w_freq_cumsum = w.sort_values( # pyre-ignore[16]: it does have a cumsum method.
ascending=False
).cumsum()
numerator = (w_freq_cumsum <= 0.5).sum()
if numerator == 0:
numerator = (
1 # this happens if one observation has more than 50% of the weights
)
# find minimal proportion of samples needed to reach 50%
# the +1 trick is to deal with cases that 1 user has a weight that is larget then 50%.
return numerator / n # breakdown_point
| balance-main | balance/stats_and_plots/weights_stats.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from typing import Any, cast, Dict, List, Optional, Union
import numpy as np
import pandas as pd
import scipy
import sklearn.utils.extmath
import statsmodels.api as sm
from balance import adjustment as balance_adjustment, util as balance_util
from balance.stats_and_plots.weights_stats import design_effect
from scipy.sparse import csc_matrix
logger: logging.Logger = logging.getLogger(__package__)
def logit_truncated(
X: Union[np.ndarray, pd.DataFrame], beta: np.ndarray, truncation_value: float = 1e-5
) -> np.ndarray:
"""This is a helper function for cbps.
Given an X matrx and avector of coeeficients beta, it computes the truncated
version of the logit function.
Args:
X (Union[np.ndarray, pd.DataFrame]): Covariate matrix
beta (np.ndarray): vector of coefficients
truncation_value (float, optional): upper and lower bound for the computed probabilities. Defaults to 1e-5.
Returns:
np.ndarray: numpy array of computed probablities
"""
probs = 1.0 / (1 + np.exp(-1 * (np.matmul(X, beta))))
return np.minimum(np.maximum(probs, truncation_value), 1 - truncation_value)
def compute_pseudo_weights_from_logit_probs(
probs: np.ndarray,
design_weights: Union[np.ndarray, pd.DataFrame],
in_pop: Union[np.ndarray, pd.DataFrame],
) -> np.ndarray:
"""This is a helper function for cbps.
Given computed probs, it computes the weights: N/N_t * (in_pop - p_i)/(1 - p_i).
(Note that these weights on sample are negative for convenience of notations)
Args:
probs (np.ndarray): vector of probabilities
design_weights (Union[np.ndarray, pd.DataFrame]): vector of design weights of sample and target
in_pop (Union[np.ndarray, pd.DataFrame]): indicator vector for target
Returns:
np.ndarray: np.ndarray of computed weights
"""
N = np.sum(design_weights)
N_target = np.sum(design_weights[in_pop == 1.0])
return N / N_target * (in_pop - probs) / (1 - probs)
def bal_loss(
beta: np.ndarray,
X: np.ndarray,
design_weights: np.ndarray,
in_pop: np.ndarray,
XtXinv: np.ndarray,
) -> np.float64:
"""This is a helper function for cbps.
It computes the balance loss.
Args:
beta (np.ndarray): vector of coefficients
X (np.ndarray): Covariate matrix
design_weights (np.ndarray): vector of design weights of sample and target
in_pop (np.ndarray): indicator vector for target
XtXinv (np.ndarray): (X.T %*% X)^(-1)
Returns:
np.float64: computed balance loss
"""
probs = logit_truncated(X, beta)
N = np.sum(design_weights)
weights = (
1.0 / N * compute_pseudo_weights_from_logit_probs(probs, design_weights, in_pop)
)
Xprimew = np.matmul((X * design_weights[:, None]).T, weights)
loss = np.absolute(np.matmul(np.matmul(Xprimew.T, XtXinv), Xprimew))
return loss
def gmm_function(
beta: np.ndarray,
X: Union[np.ndarray, pd.DataFrame],
design_weights: Union[np.ndarray, pd.DataFrame],
in_pop: Union[np.ndarray, pd.DataFrame],
invV: Union[np.ndarray, None] = None,
) -> Dict[str, Union[float, np.ndarray]]:
"""This is a helper function for cbps.
It computes the gmm loss.
Args:
beta (np.ndarray): vector of coefficients
X (Union[np.ndarray, pd.DataFrame]): covariates matrix
design_weights (Union[np.ndarray, pd.DataFrame]): vector of design weights of sample and target
in_pop (Union[np.ndarray, pd.DataFrame]): indicator vector for target
invV (Union[np.ndarray, None], optional): the inverse weighting matrix for GMM. Default is None.
Returns:
Dict[str, Union[float, np.ndarray]]: Dict with two items for loss and invV:
loss (float) computed gmm loss
invV (np.ndarray) the weighting matrix for GMM
"""
probs = logit_truncated(X, beta)
N = np.sum(design_weights)
N_target = np.sum(design_weights[in_pop == 1.0])
weights = compute_pseudo_weights_from_logit_probs(probs, design_weights, in_pop)
# Generate gbar
gbar = np.concatenate(
(
1.0 / N * (np.matmul((X * design_weights[:, None]).T, (in_pop - probs))),
1.0 / N * (np.matmul((X * design_weights[:, None]).T, weights)),
)
)
if invV is None:
# Compute inverse sigma matrix to use in GMM estimate
design_weights_sq = np.sqrt(design_weights)[:, None]
X1 = design_weights_sq * X * np.sqrt((1 - probs) * probs)[:, None]
X2 = design_weights_sq * X * np.sqrt(probs / (1 - probs))[:, None]
X11 = design_weights_sq * X * np.sqrt(probs)[:, None]
X11TX11 = np.matmul(X11.T, X11 * N / N_target)
V = (
1
/ N
* np.vstack(
(
np.hstack((np.matmul(X1.T, X1), X11TX11)),
np.hstack(
(X11TX11, np.matmul(X2.T, X2 * np.power(N / N_target, 2)))
),
)
)
)
# Note - The R CBPS code is using sum(treat) for N_target instead of
# the sum of the design weights on the treated
invV = np.linalg.pinv(V)
# Compute loss
loss = np.matmul(np.matmul(gbar.T, invV), gbar)
return {"loss": loss, "invV": invV}
def gmm_loss(
beta: np.ndarray,
X: Union[np.ndarray, pd.DataFrame],
design_weights: Union[np.ndarray, pd.DataFrame],
in_pop: Union[np.ndarray, pd.DataFrame],
invV: Optional[np.ndarray] = None,
) -> Union[float, np.ndarray]:
"""This is a helper function for cbps.
It computes the gmm loss.
See gmm_function for detials.
Args:
beta (np.ndarray): vector of coefficients
X (Union[np.ndarray, pd.DataFrame]): covariates matrix
design_weights (Union[np.ndarray, pd.DataFrame]): vector of design weights of sample and target
in_pop (Union[np.ndarray, pd.DataFrame]): indicator vector for target
invV (Union[np.ndarray, None], optional): the inverse weighting matrix for GMM. Default is None.
Returns:
Union[float, np.ndarray]: loss (float) computed gmm loss
"""
return gmm_function(beta, X, design_weights, in_pop, invV)["loss"]
def alpha_function(
alpha: np.ndarray,
beta: np.ndarray,
X: Union[np.ndarray, pd.DataFrame],
design_weights: Union[np.ndarray, pd.DataFrame],
in_pop: Union[np.ndarray, pd.DataFrame],
) -> Union[float, np.ndarray]:
"""This is a helper function for cbps.
It computes the gmm loss of alpha*beta.
Args:
alpha (np.ndarray): multiplication factor
beta (np.ndarray): vector of coefficients
X (Union[np.ndarray, pd.DataFrame]): covariates matrix
design_weights (Union[np.ndarray, pd.DataFrame]): vector of design weights of sample and target
in_pop (Union[np.ndarray, pd.DataFrame]): indicator vector for target
Returns:
Union[float, np.ndarray]: loss (float) computed gmm loss
"""
return gmm_loss(alpha * beta, X, design_weights, in_pop)
def compute_deff_from_beta(
X: np.ndarray, beta: np.ndarray, design_weights: np.ndarray, in_pop: np.ndarray
) -> np.float64:
"""This is a helper function for cbps. It computes the design effect of
the estimated weights on the sample given a value of beta.
It is used for setting a constraints on max_de.
Args:
X (np.ndarray): covariates matrix
beta (np.ndarray): vector of coefficients
design_weights (np.ndarray): vector of design weights of sample and target
in_pop (np.ndarray): indicator vector for target
Returns:
np.float64: design effect
"""
probs = logit_truncated(X, beta)
weights = np.absolute(
compute_pseudo_weights_from_logit_probs(probs, design_weights, in_pop)
)
weights = design_weights[in_pop == 0.0] * weights[in_pop == 0.0]
return design_effect(weights)
def _standardize_model_matrix(
model_matrix: pd.DataFrame, model_matrix_columns_names: List[str]
) -> Dict[str, Any]:
"""This is a helper function for cbps. It standardizes the columns of the model matrix.
Args:
model_matrix (pd.DataFrame): the matrix of covariates
model_matrix_columns_names (List[str]): list of columns in the covariates matrix
Returns:
Dict[str, Any]: Dict of the shape
{
"model_matrix": model_matrix,
"model_matrix_columns_names": model_matrix_columns_names,
"model_matrix_mean": model_matrix_mean,
"model_matrix_std": model_matrix_std,
}
"""
# TODO: Verify if scikit-learn have something similar
model_matrix_std = np.asarray(np.std(model_matrix, axis=0)).reshape(
-1
) # This is needed if the input is 2 dim numpy array
if np.sum(model_matrix_std == 0) > 0:
variables_to_omit = model_matrix_std == 0
names_variables_to_omit = np.array(model_matrix_columns_names)[
variables_to_omit
]
logger.warning(
f"The following variables have only one level, and are omitted: {names_variables_to_omit}"
)
model_matrix_columns_names = list(
np.array(model_matrix_columns_names)[np.invert(variables_to_omit)]
)
model_matrix = model_matrix[:, np.invert(variables_to_omit)]
model_matrix_std = model_matrix_std[np.invert(variables_to_omit)]
model_matrix_mean = np.mean(model_matrix, axis=0)
model_matrix = (model_matrix - model_matrix_mean) / model_matrix_std
return {
"model_matrix": model_matrix,
"model_matrix_columns_names": model_matrix_columns_names,
"model_matrix_mean": model_matrix_mean,
"model_matrix_std": model_matrix_std,
}
# TODO: update docs
def _reverse_svd_and_centralization(beta, U, s, Vh, X_matrix_mean, X_matrix_std):
"""This is a helper function for cbps. It revrse the svd and the centralization to get an estimate of beta
Source: https://github.com/kosukeimai/CBPS/blob/master/R/CBPSMain.R#L353
Args:
beta (_type_): _description_
U (_type_): _description_
s (_type_): _description_
Vh (_type_): _description_
X_matrix_mean (_type_): _description_
X_matrix_std (_type_): _description_
Returns:
_type_: _description_
"""
# TODO: update SVD and reverse SVD to the functions in scikit-learn
# Invert s
s_inv = s
s_inv[s_inv > 1e-5] = 1 / s_inv[s_inv > 1e-5]
s_inv[s_inv <= 1e-5] = 0
# Compute beta
beta = np.matmul(Vh.T * s_inv, beta)
beta_new = np.delete(beta, 0) / X_matrix_std
beta_new = np.insert(
beta_new,
0,
beta[
0,
]
- np.matmul(X_matrix_mean, beta_new),
)
return beta_new
def cbps( # noqa
sample_df: pd.DataFrame,
sample_weights: pd.Series,
target_df: pd.DataFrame,
target_weights: pd.Series,
variables: Optional[List[str]] = None,
transformations: str = "default",
na_action: str = "add_indicator",
formula: Optional[Union[str, List[str]]] = None,
balance_classes: bool = True,
cbps_method: str = "over", # other option: "exact"
max_de: Optional[float] = None,
opt_method: str = "COBYLA",
opt_opts: Optional[Dict] = None,
weight_trimming_mean_ratio: Union[None, float, int] = 20,
weight_trimming_percentile: Optional[float] = None,
random_seed: int = 2020,
*args,
**kwargs,
) -> Dict[str, Union[pd.Series, Dict]]:
"""Fit cbps (covariate balancing propensity score model) for the sample using the target.
Final weights are normalized to target size.
We use a two-step GMM estimator (as in the default R package), unlike the suggeted continuous-updating
estimator in the paper. The reason is that it runs much faster than the continuous one.
Paper: Imai, K., & Ratkovic, M. (2014). Covariate balancing propensity score.
Journal of the Royal Statistical Society: Series B: Statistical Methodology, 243-263.
https://rss.onlinelibrary.wiley.com/doi/abs/10.1111/rssb.12027
R code source: https://github.com/kosukeimai/CBPS
two-step GMM: https://en.wikipedia.org/wiki/Generalized_method_of_moments
Args:
sample_df (pd.DataFrame): a dataframe representing the sample
sample_weights (pd.Series): design weights for sample
target_df (pd.DataFrame): a dataframe representing the target
target_weights (pd.Series): design weights for target
variables (Optional[List[str]], optional): list of variables to include in the model.
If None all joint variables of sample_df and target_df are used. Defaults to None.
transformations (str, optional): what transformations to apply to data before fitting the model.
Default is "default" (see apply_transformations function). Defaults to "default".
na_action (str, optional): what to do with NAs. (see add_na_indicator function).
Defaults to "add_indicator".
formula (Optional[Union[str, List[str]]], optional): The formula according to which build the model.
In case of list of formula, the model matrix will be built in steps and
concatenated together.. Defaults to None.
balance_classes (bool, optional): whether to balance the sample and target size for running the model.
True is preferable for imbalanced cases. Defaults to True.
cbps_method (str, optional): method used for cbps. "over" fits an over-identified model that combines
the propensity score and covariate balancing conditions; "exact" fits a model that only c
ontains the covariate balancing conditions. Defaults to "over".
max_de (Optional[float], optional): upper bound for the design effect of the computed weights.
Default is None.
opt_method (str, optional): type of optimization solver. See :func:`scipy.optimize.minimize`
for other options. Defaults to "COBYLA".
opt_opts (Optional[Dict], optional): A dictionary of solver options. Default is None. See :func:`scipy.optimize.minimize`
for other options. Defaults to None.
weight_trimming_mean_ratio (Union[None, float, int], optional): indicating the ratio from above according to which
the weights are trimmed by mean(weights) * ratio. Defaults to 20.
weight_trimming_percentile (Optional[float], optional): if weight_trimming_percentile is not none, winsorization is applied.
Default is None, i.e. trimming is applied.
random_seed (int, optional): a random seed. Defaults to 2020.
Raises:
Exception: _description_
Exception: _description_
Exception: _description_
Exception: _description_
Returns:
Dict[str, Union[pd.Series, Dict]]: A dictionary includes:
"weight" --- The weights for the sample.
"model" -- dictionary with details about the fitted model:
X_matrix_columns, deviance, beta_optimal, balance_optimize_result,
gmm_optimize_result_glm_init, gmm_optimize_result_bal_init
It has the following shape:
"model": {
"method": "cbps",
"X_matrix_columns": X_matrix_columns_names,
"deviance": deviance,
"original_sum_weights": original_sum_weights, # This can be used to reconstruct the propensity probablities
"beta_optimal": beta_opt,
"beta_init_glm": beta_0, # The initial estimator by glm
"gmm_init": gmm_init, # The rescaled initial estimator
# The following are the results of the optimizations
"rescale_initial_result": rescale_initial_result,
"balance_optimize_result": balance_optimize_result,
"gmm_optimize_result_glm_init": gmm_optimize_result_glm_init
if cbps_method == "over"
else None,
"gmm_optimize_result_bal_init": gmm_optimize_result_bal_init
if cbps_method == "over"
else None,
},
"""
logger.info("Starting cbps function")
np.random.seed(random_seed) # setting random seed for cases of variations in glmnet
balance_util._check_weighting_methods_input(sample_df, sample_weights, "sample")
balance_util._check_weighting_methods_input(target_df, target_weights, "target")
# Choose joint variables from sample and target
variables = balance_util.choose_variables(sample_df, target_df, variables=variables)
logger.debug(f"Joint variables for sample and target: {variables}")
sample_df = sample_df.loc[:, variables]
target_df = target_df.loc[:, variables]
if na_action == "drop":
(sample_df, sample_weights) = balance_util.drop_na_rows(
sample_df, sample_weights, "sample"
)
(target_df, target_weights) = balance_util.drop_na_rows(
target_df, target_weights, "target"
)
# keeping index of sample df to use for final weights
sample_index = sample_df.index
# Applying transformations
# Important! Variables that don't need transformations
# should be transformed with the *identity function*,
# otherwise will be dropped from the model
sample_df, target_df = balance_adjustment.apply_transformations(
(sample_df, target_df), transformations=transformations
)
variables = list(sample_df.columns)
logger.debug(f"Final variables in the model: {variables}")
# Build X matrix
model_matrix_output = balance_util.model_matrix(
sample_df,
target_df,
variables,
add_na=(na_action == "add_indicator"),
return_type="one",
return_var_type="sparse",
# pyre-fixme[6]: for 7th parameter `formula` expected `Optional[List[str]]` but got `Union[None, List[str], str]`.
formula=formula,
one_hot_encoding=False,
)
# TODO: Currently using a dense version of the X matrix. We might change to using the sparse version if need.
X_matrix = cast(
Union[pd.DataFrame, np.ndarray, csc_matrix],
(model_matrix_output["model_matrix"]),
).toarray()
X_matrix_columns_names = model_matrix_output["model_matrix_columns_names"]
logger.info(
f"The formula used to build the model matrix: {model_matrix_output['formula']}"
)
# Standardize the X_matrix for SVD
model_matrix_standardized = _standardize_model_matrix(
X_matrix,
# pyre-fixme[6]: for 2nd positional only parameter expected `List[str]` but got `Union[None, List[str], ndarray, DataFrame, csc_matrix]`.
X_matrix_columns_names,
)
X_matrix = model_matrix_standardized["model_matrix"]
X_matrix_columns_names = model_matrix_standardized["model_matrix_columns_names"]
logger.info(f"The number of columns in the model matrix: {X_matrix.shape[1]}")
logger.info(f"The number of rows in the model matrix: {X_matrix.shape[0]}")
# Adding intercept since model_matrix removes it
X_matrix = np.c_[np.ones(X_matrix.shape[0]), X_matrix]
X_matrix_columns_names.insert(0, "Intercept")
# SVD for X_matrix
U, s, Vh = scipy.linalg.svd(X_matrix, full_matrices=False)
# Make the sign of the SVD deterministic
U, Vh = sklearn.utils.extmath.svd_flip(U, Vh, u_based_decision=False)
# TODO: add stop: if (k < ncol(X)) stop("X is not full rank")
sample_n = sample_df.shape[0]
target_n = target_df.shape[0]
total_n = sample_n + target_n
# Create "treatment" (in_sample) variable
in_sample = np.concatenate((np.ones(sample_n), np.zeros(target_n)))
in_pop = np.concatenate((np.zeros(sample_n), np.ones(target_n)))
if len(np.unique(in_sample.reshape(in_sample.shape[0]))) == 1:
_number_unique = np.unique(in_sample.reshape(in_sample.shape[0]))
raise Exception(
f"Sample indicator only has value {_number_unique}. This can happen when your sample or target are empty from unknown reason"
)
# balance classes
if balance_classes:
design_weights = (
total_n
/ 2
* np.concatenate(
(
sample_weights / np.sum(sample_weights),
target_weights / np.sum(target_weights),
)
)
)
XtXinv = np.linalg.pinv(
# pyre-fixme[16] Undefined attribute [16]: `float` has no attribute `__getitem__`.
np.matmul((U * design_weights[:, None]).T, U * design_weights[:, None])
)
else:
design_weights = np.concatenate((sample_weights, target_weights))
design_weights = design_weights / np.mean(design_weights)
XtXinv = np.linalg.pinv(np.matmul(U.T, U))
# Define constraints for optimization to limit max_de
constraints = []
if max_de is not None:
constraints += [
# max de effect
{
"type": "ineq",
"fun": lambda x: (
max_de - compute_deff_from_beta(U, x, design_weights, in_pop)
),
}
]
# Optimization using Generalized Methods of Moments:
# Step 0 - initial estimation for beta
logger.info("Finding initial estimator for GMM optimization")
glm_mod = sm.GLM(
in_pop, U, family=sm.families.Binomial(), freq_weights=design_weights
)
beta_0 = glm_mod.fit().params
# TODO: add some safty for when this fails?
# Step 1 - rescale initial estimation for beta by minimizing the gmm loss
rescale_initial_result = scipy.optimize.minimize(
alpha_function,
x0=[1],
args=(
beta_0,
U,
design_weights,
in_pop,
),
bounds=[(0.8, 1.1)], # These are the bounds used in the R CBPS package
)
if rescale_initial_result["success"] is np.bool_(False):
logger.warning(
f"Convergence of alpha_function has failed due to '{rescale_initial_result['message']}'"
)
gmm_init = beta_0 * rescale_initial_result["x"][0]
invV = gmm_function(gmm_init, U, design_weights, in_pop, invV=None)["invV"]
# Step 2 - find initial estimation for beta by minimizing balance loss
logger.info(
"Finding initial estimator for GMM optimization that minimizes the balance loss"
)
balance_optimize_result = scipy.optimize.minimize(
fun=bal_loss,
x0=gmm_init,
args=(
U,
design_weights,
in_pop,
XtXinv,
),
method=opt_method,
options=opt_opts,
constraints=constraints,
)
if balance_optimize_result["success"] is np.bool_(False):
logger.warning(
f"Convergence of bal_loss function has failed due to '{balance_optimize_result['message']}'"
)
beta_balance = balance_optimize_result["x"]
gmm_optimize_result_glm_init = None
if cbps_method == "exact":
if (
balance_optimize_result["success"] is np.bool_(False)
and "Did not converge to a solution satisfying the constraints"
in balance_optimize_result["message"]
):
raise Exception("There is no solution satisfying the constraints.")
beta_opt = beta_balance
# Step 3 - minimize gmm_loss from two starting points: beta_balance and gmm_init,
# and choose the solution that minimize the gmm_loss.
elif cbps_method == "over":
logger.info("Running GMM optimization")
gmm_optimize_result_glm_init = scipy.optimize.minimize(
fun=gmm_loss,
x0=gmm_init,
args=(
U,
design_weights,
in_pop,
invV,
),
method=opt_method,
options=opt_opts,
constraints=constraints,
)
if gmm_optimize_result_glm_init["success"] is np.bool_(False):
logger.warning(
f"Convergence of gmm_loss function with gmm_init start point has failed due to '{gmm_optimize_result_glm_init['message']}'"
)
gmm_optimize_result_bal_init = scipy.optimize.minimize(
fun=gmm_loss,
x0=beta_balance,
args=(
U,
design_weights,
in_pop,
invV,
),
method=opt_method,
options=opt_opts,
constraints=constraints,
)
if gmm_optimize_result_bal_init["success"] is np.bool_(False):
logger.warning(
f"Convergence of gmm_loss function with beta_balance start point has failed due to '{gmm_optimize_result_bal_init['message']}'"
)
# If the constraints cannot be satisfied, exit the function
if (
gmm_optimize_result_glm_init["success"] is np.bool_(False)
and "Did not converge to a solution satisfying the constraints"
in gmm_optimize_result_glm_init["message"]
and gmm_optimize_result_bal_init["success"] is np.bool_(False)
and "Did not converge to a solution satisfying the constraints"
in gmm_optimize_result_bal_init["message"]
):
raise Exception("There is no solution satisfying the constraints.")
# Choose beta that gives a smaller loss in GMM and that satisfy the constraints
if (
gmm_optimize_result_bal_init["fun"] < gmm_optimize_result_glm_init["fun"]
and "Did not converge to a solution satisfying the constraints"
not in gmm_optimize_result_bal_init["message"]
):
beta_opt = gmm_optimize_result_bal_init["x"]
else:
beta_opt = gmm_optimize_result_glm_init["x"]
else:
raise Exception(f"cbps_method '{cbps_method}' is not a valid option")
# Compute final probs and weights with beta_opt
probs = logit_truncated(U, beta_opt)
logger.debug(f"Minimum probs for sample: {np.min(probs[in_sample == 1.0])}")
logger.debug(f"Maximum probs for sample: {np.max(probs[in_sample == 1.0])}")
weights = np.absolute(
compute_pseudo_weights_from_logit_probs(probs, design_weights, in_pop)
)
logger.debug(f"Minimum weight for sample: {np.min(weights[in_sample == 1.0])}")
logger.debug(f"Maximum weight for sample: {np.max(weights[in_sample == 1.0])}")
weights = design_weights[in_sample == 1.0] * weights[in_sample == 1.0]
# Compute deviance (Minus twice the log-likelihood of the CBPS fit)
deviance = -2 * np.sum(
in_pop * design_weights * np.log(probs)
+ (1 - in_pop) * design_weights * np.log(1 - probs)
)
# trim weights
weights = balance_adjustment.trim_weights(
weights, weight_trimming_mean_ratio, weight_trimming_percentile
)
# normalize to target size
original_sum_weights = np.sum(weights)
logger.debug(f"original sum of weights for sample: {original_sum_weights}")
weights = weights / original_sum_weights * np.sum(target_weights)
# set index to sample_df
weights = pd.DataFrame({"weight": weights}).set_index(sample_index)["weight"]
if np.unique(weights).shape[0] == 1 or weights.describe()["std"] < 1e-4:
# All weights are the same
logger.warning(
"All weights are identical (or almost identical). The estimates will not be adjusted"
)
# Revrse SVD and centralization
beta_opt = _reverse_svd_and_centralization(
beta_opt,
U,
s,
Vh,
model_matrix_standardized["model_matrix_mean"],
model_matrix_standardized["model_matrix_std"],
)
out = {
"weight": weights,
"model": {
"method": "cbps",
"X_matrix_columns": X_matrix_columns_names,
"deviance": deviance,
"original_sum_weights": original_sum_weights, # This can be used to reconstruct the propensity probablities
"beta_optimal": beta_opt,
"beta_init_glm": beta_0, # The initial estimator by glm
"gmm_init": gmm_init, # The rescaled initial estimator
# The following are the results of the optimizations
"rescale_initial_result": rescale_initial_result,
"balance_optimize_result": balance_optimize_result,
"gmm_optimize_result_glm_init": gmm_optimize_result_glm_init
if cbps_method == "over"
else None,
# pyre-fixme[61]: `gmm_optimize_result_bal_init` is undefined, or not
# always defined.
"gmm_optimize_result_bal_init": gmm_optimize_result_bal_init
if cbps_method == "over"
else None,
},
}
logger.info("Done cbps function")
return out
| balance-main | balance/weighting_methods/cbps.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from typing import Dict, Union
import pandas as pd
logger: logging.Logger = logging.getLogger(__package__)
def adjust_null(
sample_df: pd.DataFrame,
sample_weights: pd.Series,
target_df: pd.DataFrame,
target_weights: pd.Series,
*args,
**kwargs,
) -> Dict[str, Union[Dict[str, str], pd.Series]]:
"""Doesn't apply any adjustment to the data. Returns the design weights as they are.
This may be useful when one needs the output of Sample.adjust() (i.e.: an adjusted object),
but wishes to not run any model for it.
Args:
sample_df (pd.DataFrame): a dataframe representing the sample
sample_weights (pd.Series): design weights for sample
target_df (pd.DataFrame): a dataframe representing the target
target_weights (pd.Series): design weights for target
Returns:
Dict[str, Union[Dict[str, str], pd.Series]]: Dict of weights (original sample weights) and model (with method = null_adjustment)
"""
return {
"weight": sample_weights,
"model": {
"method": "null_adjustment",
},
}
| balance-main | balance/weighting_methods/adjust_null.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from typing import Dict, List, Optional, Union
import pandas as pd
from balance import adjustment as balance_adjustment, util as balance_util
logger: logging.Logger = logging.getLogger(__package__)
# TODO: Add tests for all arguments of function
# TODO: Add argument for na_action
def poststratify(
sample_df: pd.DataFrame,
sample_weights: pd.Series,
target_df: pd.DataFrame,
target_weights: pd.Series,
variables: Optional[List[str]] = None,
transformations: str = "default",
transformations_drop: bool = True,
*args,
**kwargs,
) -> Dict[str, Union[pd.Series, Dict[str, str]]]:
"""Perform cell-based post-stratification. The output weights take into account
the design weights and the post-stratification weights.
Reference: https://docs.wfp.org/api/documents/WFP-0000121326/download/
Args:
sample_df (pd.DataFrame): a dataframe representing the sample
sample_weights (pd.Series): design weights for sample
target_df (pd.DataFrame): a dataframe representing the target
target_weights (pd.Series): design weights for target
variables (Optional[List[str]], optional): list of variables to include in the model.
If None all joint variables of sample_df and target_df are used
transformations (str, optional): what transformations to apply to data before fitting the model.
Default is "default" (see apply_transformations function)
transformations_drop (bool, optional): whether the function should drop non-transformed variables.
Default is True.
Raises:
ValueError: _description_
ValueError: _description_
Returns:
Dict[str, Union[pd.Series, Dict[str, str]]]:
weight (pd.Series): final weights (sum up to target's sum of weights)
model (dict): method of adjustment
Dict shape:
{
"weight": w,
"model": {"method": "poststratify"},
}
"""
balance_util._check_weighting_methods_input(sample_df, sample_weights, "sample")
balance_util._check_weighting_methods_input(target_df, target_weights, "target")
if ("weight" in sample_df.columns.values) or ("weight" in target_df.columns.values):
raise ValueError(
"weight can't be a name of a column in sample or target when applying poststratify"
)
variables = balance_util.choose_variables(sample_df, target_df, variables=variables)
logger.debug(f"Join variables for sample and target: {variables}")
sample_df = sample_df.loc[:, variables]
target_df = target_df.loc[:, variables]
sample_df, target_df = balance_adjustment.apply_transformations(
(sample_df, target_df),
transformations=transformations,
drop=transformations_drop,
)
variables = list(sample_df.columns)
logger.debug(f"Final variables in the model after transformations: {variables}")
target_df = target_df.assign(weight=target_weights)
target_cell_props = target_df.groupby(list(variables))["weight"].sum()
sample_df = sample_df.assign(design_weight=sample_weights)
sample_cell_props = sample_df.groupby(list(variables))["design_weight"].sum()
combined = pd.merge(
target_cell_props,
sample_cell_props,
right_index=True,
left_index=True,
how="outer",
)
# check that all combinations of cells in sample_df are also in target_df
if any(combined["weight"].isna()):
raise ValueError("all combinations of cells in sample_df must be in target_df")
combined["weight"] = combined["weight"] / combined["design_weight"]
sample_df = sample_df.join(combined["weight"], on=variables)
w = sample_df.weight * sample_df.design_weight
return {
"weight": w,
"model": {"method": "poststratify"},
}
| balance-main | balance/weighting_methods/poststratify.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
| balance-main | balance/weighting_methods/__init__.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import math
from fractions import Fraction
from functools import reduce
from typing import Callable, Dict, List, Union
import numpy as np
import pandas as pd
from balance import adjustment as balance_adjustment, util as balance_util
from ipfn import ipfn
logger = logging.getLogger(__package__)
# TODO: Add options for only marginal distributions input
def rake(
sample_df: pd.DataFrame,
sample_weights: pd.Series,
target_df: pd.DataFrame,
target_weights: pd.Series,
variables: Union[List[str], None] = None,
transformations: Union[Dict[str, Callable], str] = "default",
na_action: str = "add_indicator",
max_iteration: int = 1000,
convergence_rate: float = 0.0005,
rate_tolerance: float = 1e-8,
*args,
**kwargs,
) -> Dict:
"""
Perform raking (using the iterative proportional fitting algorithm).
See: https://en.wikipedia.org/wiki/Iterative_proportional_fitting
Returns weights normalised to sum of target weights
Arguments:
sample_df --- (pandas dataframe) a dataframe representing the sample.
sample_weights --- (pandas series) design weights for sample.
target_df --- (pandas dataframe) a dataframe representing the target.
target_weights --- (pandas series) design weights for target.
variables --- (list of strings) list of variables to include in the model.
If None all joint variables of sample_df and target_df are used.
transformations --- (dict) what transformations to apply to data before fitting the model.
Default is "default" (see apply_transformations function).
na_action --- (string) what to do with NAs. Default is "add_indicator", which adds NaN as a
group (called "__NaN__") for each weighting variable (post-transformation);
"drop" removes rows with any missing values on any variable from both sample
and target.
max_iteration --- (int) maximum number of iterations for iterative proportional fitting algorithm
convergence_rate --- (float) convergence criteria; the maximum difference in proportions between
sample and target marginal distribution on any covariate in order
for algorithm to converge.
rate_tolerance --- (float) convergence criteria; if convergence rate does not move more
than this amount than the algorithm is also considered to
have converged.
Returns:
A dictionary including:
"weight" --- The weights for the sample.
"model" --- parameters of the model: iterations (dataframe with iteration numbers and
convergence rate information at all steps), converged (Flag with the output
status: 0 for failure and 1 for success).
"""
assert (
"weight" not in sample_df.columns.values
), "weight shouldn't be a name for covariate in the sample data"
assert (
"weight" not in target_df.columns.values
), "weight shouldn't be a name for covariate in the target data"
# TODO: move the input checks into separate funnction for rake, ipw, poststratify
assert isinstance(sample_df, pd.DataFrame), "sample_df must be a pandas DataFrame"
assert isinstance(target_df, pd.DataFrame), "target_df must be a pandas DataFrame"
assert isinstance(
sample_weights, pd.Series
), "sample_weights must be a pandas Series"
assert isinstance(
target_weights, pd.Series
), "target_weights must be a pandas Series"
assert sample_df.shape[0] == sample_weights.shape[0], (
"sample_weights must be the same length as sample_df"
f"{sample_df.shape[0]}, {sample_weights.shape[0]}"
)
assert target_df.shape[0] == target_weights.shape[0], (
"target_weights must be the same length as target_df"
f"{target_df.shape[0]}, {target_weights.shape[0]}"
)
variables = balance_util.choose_variables(sample_df, target_df, variables=variables)
logger.debug(f"Join variables for sample and target: {variables}")
sample_df = sample_df.loc[:, variables]
target_df = target_df.loc[:, variables]
assert len(variables) > 1, (
"Must weight on at least two variables for raking. "
f"Currently have variables={variables} only"
)
sample_df, target_df = balance_adjustment.apply_transformations(
(sample_df, target_df), transformations
)
# TODO: separate into a function that handles NA (for rake, ipw, poststratify)
if na_action == "drop":
(sample_df, sample_weights) = balance_util.drop_na_rows(
sample_df, sample_weights, "sample"
)
(target_df, target_weights) = balance_util.drop_na_rows(
target_df, target_weights, "target"
)
elif na_action == "add_indicator":
target_df = target_df.fillna("__NaN__")
sample_df = sample_df.fillna("__NaN__")
else:
raise ValueError("`na_action` must be 'add_indicator' or 'drop'")
# Cast all data types as string to be explicit about each unique value
# being its own group and to handle that `fillna()` above creates
# series of type Object, which won't work for the ipfn script
levels_dict = {}
for variable in variables:
target_df[variable] = target_df[variable].astype(str)
sample_df[variable] = sample_df[variable].astype(str)
sample_var_set = set(sample_df[variable].unique())
target_var_set = set(target_df[variable].unique())
sample_over_set = sample_var_set - target_var_set
target_over_set = target_var_set - sample_var_set
if len(sample_over_set):
raise ValueError(
"All variable levels in sample must be present in target. "
f"'{variable}' in target is missing these levels: {sample_over_set}."
)
if len(target_over_set):
logger.warning(
f"'{variable}' has more levels in target than in sample. "
f"'{variable}' in sample is missing these levels: {target_over_set}. "
"These levels are treated as if they do not exist for that variable."
)
levels_dict[variable] = list(sample_var_set.intersection(target_var_set))
logger.info(
f"Final covariates and levels that will be used in raking: {levels_dict}."
)
target_df = target_df.assign(weight=target_weights)
sample_df = sample_df.assign(weight=sample_weights)
sample_sum_weights = sample_df["weight"].sum()
target_sum_weights = target_df["weight"].sum()
# Alphabetize variables to ensure consistency across covariate order
# (ipfn algorithm is iterative and variable order can matter on the margins)
alphabetized_variables = list(variables)
alphabetized_variables.sort()
logger.debug(
f"Alphabetized variable order is as follows: {alphabetized_variables}."
)
# margins from population
target_margins = [
(
(
target_df.groupby(variable)["weight"].sum()
/ (sum(target_df.groupby(variable)["weight"].sum()))
* sample_sum_weights
)
)
for variable in alphabetized_variables
]
# sample cells (joint distribution of covariates)
sample_cells = (
sample_df.groupby(alphabetized_variables)["weight"].sum().reset_index()
)
logger.debug(
"Raking algorithm running following settings: "
f" convergence_rate: {convergence_rate}; max_iteration: {max_iteration}; rate_tolerance: {rate_tolerance}"
)
# returns dataframe with joint distribution of covariates and total weight
# for that specific set of covariates
ipfn_obj = ipfn.ipfn(
original=sample_cells,
aggregates=target_margins,
dimensions=[[var] for var in alphabetized_variables],
weight_col="weight",
convergence_rate=convergence_rate,
max_iteration=max_iteration,
verbose=2,
rate_tolerance=rate_tolerance,
)
fit, converged, iterations = ipfn_obj.iteration()
logger.debug(
f"Raking algorithm terminated with following convergence: {converged}; "
f"and iteration meta data: {iterations}."
)
if not converged:
logger.warning("Maximum iterations reached, convergence was not achieved")
raked = pd.merge(
sample_df.reset_index(),
fit.rename(columns={"weight": "rake_weight"}),
how="left",
on=list(variables),
)
# Merge back to original sample weights
raked_rescaled = pd.merge(
raked,
(
sample_df.groupby(list(variables))["weight"]
.sum()
.reset_index()
.rename(columns={"weight": "total_survey_weight"})
),
how="left",
on=list(variables),
).set_index(
"index"
) # important if dropping rows due to NA
# use above merge to give each individual sample its proportion of the
# cell's total weight
raked_rescaled["rake_weight"] = (
raked_rescaled["rake_weight"] / raked_rescaled["total_survey_weight"]
)
# rescale weights to sum to target_sum_weights (sum of initial target weights)
w = (
raked_rescaled["rake_weight"] / raked_rescaled["rake_weight"].sum()
) * target_sum_weights
return {
"weight": w,
"model": {
"method": "rake",
"iterations": iterations,
"converged": converged,
"perf": {"prop_dev_explained": np.array([np.nan])},
# TODO: fix functions that use the perf and remove it from here
},
}
def _lcm(a: int, b: int) -> int:
"""
Calculates the least common multiple (LCM) of two integers.
The least common multiple (LCM) of two or more numbers is the smallest positive integer that is divisible by each of the given numbers.
In other words, it is the smallest multiple that the numbers have in common.
The LCM is useful when you need to find a common denominator for fractions or synchronize repeating events with different intervals.
For example, let's find the LCM of 4 and 6:
The multiples of 4 are: 4, 8, 12, 16, 20, ...
The multiples of 6 are: 6, 12, 18, 24, 30, ...
The smallest multiple that both numbers have in common is 12, so the LCM of 4 and 6 is 12.
The calculation is based on the property that the product of two numbers is equal to the product of their LCM and GCD: a * b = LCM(a, b) * GCD(a, b).
(proof: https://math.stackexchange.com/a/589299/1406)
Args:
a: The first integer.
b: The second integer.
Returns:
The least common multiple of the two integers.
"""
# NOTE: this function uses math.gcd which calculates the greatest common divisor (GCD) of two integers.
# The greatest common divisor (GCD) of two or more integers is the largest positive integer that divides each of the given integers without leaving a remainder.
# In other words, it is the largest common factor of the given integers.
# For example, the GCD of 12 and 18 is 6, since 6 is the largest integer that divides both 12 and 18 without leaving a remainder.
# Similarly, the GCD of 24, 36, and 48 is 12, since 12 is the largest integer that divides all three of these numbers without leaving a remainder.
return abs(a * b) // math.gcd(a, b)
def _proportional_array_from_dict(
input_dict: Dict[str, float], max_length: int = 10000
) -> List[str]:
"""
Generates a proportional array based on the input dictionary.
Args:
input_dict (Dict[str, float]): A dictionary where keys are strings and values are their proportions (float).
max_length (int): check if the length of the output exceeds the max_length. If it does, it will be scaled down to that length. Default is 10k.
Returns:
A list of strings where each key is repeated according to its proportion.
Examples:
::
_proportional_array_from_dict({"a":0.2, "b":0.8})
# ['a', 'b', 'b', 'b', 'b']
_proportional_array_from_dict({"a":0.5, "b":0.5})
# ['a', 'b']
_proportional_array_from_dict({"a":1/3, "b":1/3, "c": 1/3})
# ['a', 'b', 'c']
_proportional_array_from_dict({"a": 3/8, "b": 5/8})
# ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b']
_proportional_array_from_dict({"a":3/5, "b":1/5, "c": 2/10})
# ['a', 'a', 'a', 'b', 'c']
"""
# Filter out items with zero value
filtered_dict = {k: v for k, v in input_dict.items() if v > 0}
# Normalize the values if they don't sum to 1
sum_values = sum(filtered_dict.values())
if sum_values != 1:
filtered_dict = {k: v / sum_values for k, v in filtered_dict.items()}
# Convert the proportions to fractions
fraction_dict = {
k: Fraction(v).limit_denominator() for k, v in filtered_dict.items()
}
# Find the least common denominator (LCD) of the fractions
lcd = 1
for fraction in fraction_dict.values():
lcd *= fraction.denominator // math.gcd(lcd, fraction.denominator)
# Calculate the scaling factor based on max_length
scaling_factor = min(1, max_length / lcd)
result = []
for key, fraction in fraction_dict.items():
# Calculate the count for each key based on its proportion and scaling_factor
k_count = round((fraction * lcd).numerator * scaling_factor)
# Extend the result array with the key repeated according to its count
result.extend([key] * k_count)
return result
def _find_lcm_of_array_lengths(arrays: Dict[str, List[str]]) -> int:
"""
Finds the least common multiple (LCM) of the lengths of arrays in the input dictionary.
Args:
arrays: A dictionary where keys are strings and values are lists of strings.
Returns:
The LCM of the lengths of the arrays in the input dictionary.
Example:
::
arrays = {
"v1": ["a", "b", "b", "c"],
"v2": ["aa", "bb"]
}
_find_lcm_of_array_lengths(arrays)
# 4
arrays = {
"v1": ["a", "b", "b", "c"],
"v2": ["aa", "bb"],
"v3": ["a1", "a2", "a3"]
}
_find_lcm_of_array_lengths(arrays)
# 12
"""
array_lengths = [len(arr) for arr in arrays.values()]
lcm_length = reduce(lambda x, y: _lcm(x, y), array_lengths)
return lcm_length
def _realize_dicts_of_proportions(
dict_of_dicts: Dict[str, Dict[str, float]]
) -> Dict[str, List[str]]:
"""
Generates proportional arrays of equal length for each input dictionary.
This can be used to get an input dict of proportions of values, and produce a dict with arrays that realizes these proportions.
It can be used as input to the Sample object so it could be used for running raking.
Args:
dict_of_dicts: A dictionary of dictionaries, where each key is a string and
each value is a dictionary with keys as strings and values as their proportions (float).
Returns:
A dictionary with the same keys as the input and equal length arrays as values.
Examples:
::
dict_of_dicts = {
"v1": {"a": 0.2, "b": 0.6, "c": 0.2},
"v2": {"aa": 0.5, "bb": 0.5}
}
realize_dicts_of_proportions(dict_of_dicts)
# {'v1': ['a', 'b', 'b', 'b', 'c', 'a', 'b', 'b', 'b', 'c'], 'v2': ['aa', 'bb', 'aa', 'bb', 'aa', 'bb', 'aa', 'bb', 'aa', 'bb']}
dict_of_dicts = {
"v1": {"a": 0.2, "b": 0.6, "c": 0.2},
"v2": {"aa": 0.5, "bb": 0.5},
"v3": {"A": 0.2, "B": 0.8},
}
realize_dicts_of_proportions(dict_of_dicts)
# {'v1': ['a', 'b', 'b', 'b', 'c', 'a', 'b', 'b', 'b', 'c'],
# 'v2': ['aa', 'bb', 'aa', 'bb', 'aa', 'bb', 'aa', 'bb', 'aa', 'bb'],
# 'v3': ['A', 'B', 'B', 'B', 'B', 'A', 'B', 'B', 'B', 'B']}
# The above example could have been made shorter. But that's a limitation of the function.
dict_of_dicts = {
"v1": {"a": 0.2, "b": 0.6, "c": 0.2},
"v2": {"aa": 0.5, "bb": 0.5},
"v3": {"A": 0.2, "B": 0.8},
"v4": {"A": 0.1, "B": 0.9},
}
realize_dicts_of_proportions(dict_of_dicts)
# {'v1': ['a', 'b', 'b', 'b', 'c', 'a', 'b', 'b', 'b', 'c'],
# 'v2': ['aa', 'bb', 'aa', 'bb', 'aa', 'bb', 'aa', 'bb', 'aa', 'bb'],
# 'v3': ['A', 'B', 'B', 'B', 'B', 'A', 'B', 'B', 'B', 'B'],
# 'v4': ['A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B']}
"""
# Generate proportional arrays for each dictionary
arrays = {k: _proportional_array_from_dict(v) for k, v in dict_of_dicts.items()}
# Find the LCM over the lengths of all the arrays
lcm_length = _find_lcm_of_array_lengths(arrays)
# Extend each array to have the same LCM length while maintaining proportions
result = {}
for k, arr in arrays.items():
factor = lcm_length // len(arr)
extended_arr = arr * factor
result[k] = extended_arr
return result
def prepare_marginal_dist_for_raking(
dict_of_dicts: Dict[str, Dict[str, float]]
) -> pd.DataFrame:
"""
Realizes a nested dictionary of proportions into a DataFrame.
Args:
dict_of_dicts: A nested dictionary where the outer keys are column names
and the inner dictionaries have keys as category labels
and values as their proportions (float).
Returns:
A DataFrame with columns specified by the outer keys of the input dictionary
and rows containing the category labels according to their proportions.
An additional "id" column is added with integer values as row identifiers.
Example:
::
print(prepare_marginal_dist_for_raking({
"A": {"a": 0.5, "b": 0.5},
"B": {"x": 0.2, "y": 0.8}
}))
# Returns a DataFrame with columns A, B, and id
# A B id
# 0 a x 0
# 1 b y 1
# 2 a y 2
# 3 b y 3
# 4 a y 4
# 5 b x 5
# 6 a y 6
# 7 b y 7
# 8 a y 8
# 9 b y 9
"""
target_dict_from_marginals = _realize_dicts_of_proportions(dict_of_dicts)
target_df_from_marginals = pd.DataFrame.from_dict(target_dict_from_marginals)
# Add an id column:
target_df_from_marginals["id"] = range(target_df_from_marginals.shape[0])
return target_df_from_marginals
| balance-main | balance/weighting_methods/rake.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from contextlib import contextmanager
from typing import Any, Callable, cast, Dict, Generator, List, Optional, Tuple, Union
import glmnet_python # noqa # Required so that cvglmnet import works
import numpy as np
import pandas as pd
import scipy
from balance import adjustment as balance_adjustment, util as balance_util
from balance.stats_and_plots.weighted_comparisons_stats import asmd
from balance.stats_and_plots.weights_stats import design_effect
from cvglmnet import cvglmnet # pyre-ignore[21]: this module exists
from cvglmnetPredict import cvglmnetPredict # pyre-ignore[21]: this module exists
from scipy.sparse.csc import csc_matrix
logger: logging.Logger = logging.getLogger(__package__)
# Allows us to control exactly where monkey patching is applied (e.g.: for better code readability and exceptions tracking).
@contextmanager
def _patch_nan_in_amin_amax(*args, **kwds) -> Generator:
"""This allows us to use nanmin and nanmax instead of amin and amax (thus removing nan from their computation)
This is needed in cases that the cvglmnet yields some nan values for the cross validation folds.
Returns:
Generator: replaces amin and amax, and once done, turns them back to their original version.
"""
# swap amin and amax with nanmin and nanmax
# so that they won't return nan when their input has some nan values
tmp_amin, tmp_amax = scipy.amin, scipy.amax # pyre-ignore[16]
# Wrapping amin and amax with logger calls so to alert the user in case nan were present.
# This comes with the strong assumption that this will occur within the cross validation step!
def new_amin(a, *args, **kwds) -> Callable:
nan_count = scipy.count_nonzero(scipy.isnan(a)) # pyre-ignore[16]
if nan_count > 0:
logger.warning(
"The scipy.amin function was replaced with scipy.nanmin."
f"While running, it removed {nan_count} `nan` values from an array of size {a.size}"
f"(~{round(100 * nan_count / a.size, 1)}% of the values)."
)
return scipy.nanmin(a, *args, **kwds) # pyre-ignore[16]
def new_amax(a, *args, **kwds) -> Callable:
nan_count = scipy.count_nonzero(scipy.isnan(a)) # pyre-ignore[16]
if nan_count > 0:
logger.warning(
"The scipy.amax function was replaced with scipy.nanmax. "
f"While running, it removed {nan_count} `nan` values from an array of size {a.size}"
f"(~{round(100 * nan_count / a.size, 1)}% of the values)."
)
return scipy.nanmax(a, *args, **kwds) # pyre-ignore[16]
scipy.amin = new_amin # scipy.nanmin
scipy.amax = new_amax # scipy.nanmax
try:
yield
finally:
# undo the function swap
scipy.amin, scipy.amax = tmp_amin, tmp_amax
@contextmanager
def _patch_scipy_random(*args, **kwds) -> Generator:
"""Monkey-patch scipy.random(), used by glmnet_python
but removed in scipy 1.9.0"""
tmp_scipy_random_func = (
# pyre-ignore[16]
scipy.random
if hasattr(scipy, "random")
else None
)
scipy.random = np.random
try:
yield
finally:
# undo the function swap
scipy.random = tmp_scipy_random_func
def cv_glmnet_performance(
fit, feature_names: Optional[list] = None, s: Union[str, float, None] = "lambda_1se"
) -> Dict[str, Any]:
"""Extract elements from cvglmnet to describe the fitness quality.
Args:
fit (_type_): output of cvglmnet
feature_names (Optional[list], optional): The coeficieents of which features should be included.
None = all features are included. Defaults to None.
s (Union[str, float, None], optional): lambda avlue for cvglmnet. Defaults to "lambda_1se".
Raises:
Exception: _description_
Returns:
Dict[str, Any]: Dict of the shape:
{
"prop_dev_explained": fit["glmnet_fit"]["dev"][optimal_lambda_index],
"mean_cv_error": fit["cvm"][optimal_lambda_index],
"coefs": coefs,
}
"""
if isinstance(s, str):
optimal_lambda = fit[s]
else:
optimal_lambda = s
optimal_lambda_index = np.where(fit["lambdau"] == optimal_lambda)[0]
if len(optimal_lambda_index) != 1:
raise Exception(
f"No lambda found for s={s}. You must specify a "
'numeric value which exists in the model or "lambda_min", or '
'"lambda_1se"'
)
coefs = cvglmnetPredict(
fit,
newx=np.empty([0]),
ptype="coefficients",
s=optimal_lambda,
)
coefs = coefs.reshape(coefs.shape[0])
if feature_names is not None:
coefs = pd.Series(data=coefs, index=["intercept"] + feature_names)
else:
coefs = pd.Series(data=coefs)
return {
"prop_dev_explained": fit["glmnet_fit"]["dev"][optimal_lambda_index],
"mean_cv_error": fit["cvm"][optimal_lambda_index],
"coefs": coefs,
}
# TODO: consider add option to normalize weights to sample size
def weights_from_link(
link: Any,
balance_classes: bool,
sample_weights: pd.Series,
target_weights: pd.Series,
weight_trimming_mean_ratio: Union[None, float, int] = None,
weight_trimming_percentile: Optional[float] = None,
keep_sum_of_weights: bool = True,
) -> pd.Series:
"""Transform output of cvglmnetPredict(..., type='link') into weights, by
exponentiating them, and optionally balancing the classes and trimming
the weights, then normalize the weights to have sum equal to the sum of the target weights.
Args:
link (Any): output of cvglmnetPredict(..., type='link')
balance_classes (bool): whether balance_classes used in glmnet
sample_weights (pd.Series): vector of sample weights
target_weights (pd.Series): vector of sample weights
weight_trimming_mean_ratio (Union[None, float, int], optional): to be used in :func:`trim_weights`. Defaults to None.
weight_trimming_percentile (Optional[float], optional): to be used in :func:`trim_weights`. Defaults to None.
keep_sum_of_weights (bool, optional): to be used in :func:`trim_weights`. Defaults to True.
Returns:
pd.Series: A vecotr of normalized weights (for sum of target weights)
"""
link = link.reshape((link.shape[0],))
if balance_classes:
odds = np.sum(sample_weights) / np.sum(target_weights)
link = link + np.log(odds)
weights = sample_weights / np.exp(link)
weights = balance_adjustment.trim_weights(
weights,
weight_trimming_mean_ratio,
weight_trimming_percentile,
keep_sum_of_weights=keep_sum_of_weights,
)
# Normalize weights such that the sum will be the sum of the weights of target
weights = weights * np.sum(target_weights) / np.sum(weights)
return weights
# TODO: Update choose_regularization function to be based on mse (instead of grid search)
def choose_regularization(
fit,
sample_df: pd.DataFrame,
target_df: pd.DataFrame,
sample_weights: pd.Series,
target_weights: pd.Series,
X_matrix_sample,
balance_classes: bool,
max_de: float = 1.5,
trim_options: Tuple[
int, int, int, float, float, float, float, float, float, float
] = (20, 10, 5, 2.5, 1.25, 0.5, 0.25, 0.125, 0.05, 0.01),
n_asmd_candidates: int = 10,
) -> Dict[str, Any]:
"""Searches through the regularisation parameters of the model and weight
trimming levels to find the combination with the highest covariate
ASMD reduction (in sample_df and target_df, NOT in the model matrix used for modeling
the response) subject to the design effect being lower than max_de (deafults to 1.5).
The function preforms a grid search over the n_asmd_candidates (deafults to 10) models
with highest DE lower than max_de (assuming higher DE means more bias reduction).
Args:
fit (_type_): output of cvglmnet
sample_df (pd.DataFrame): a dataframe representing the sample
target_df (pd.DataFrame): a dataframe representing the target
sample_weights (pd.Series): design weights for sample
target_weights (pd.Series): design weights for target
X_matrix_sample (_type_): the matrix that was used to consturct the model
balance_classes (bool): whether balance_classes used in glmnet
max_de (float, optional): upper bound for the design effect of the computed weights.
Used for choosing the model regularization and trimming.
If set to None, then it uses 'lambda_1se'. Defaults to 1.5.
trim_options (Tuple[ int, int, int, float, float, float, float, float, float, float ], optional):
options for weight_trimming_mean_ratio. Defaults to (20, 10, 5, 2.5, 1.25, 0.5, 0.25, 0.125, 0.05, 0.01).
n_asmd_candidates (int, optional): number of candidates for grid search.. Defaults to 10.
Returns:
Dict[str, Any]: Dict of the value of the chosen lambda, the value of trimming, model description.
Shape is
{
"best": {"s": best.s.values, "trim": best.trim.values[0]},
"perf": all_perf,
}
"""
logger.info("Starting choosing regularisation parameters")
# get all links
links = cvglmnetPredict(fit, X_matrix_sample, ptype="link", s=fit["lambdau"])
asmd_before = asmd(
sample_df=sample_df,
target_df=target_df,
sample_weights=sample_weights,
target_weights=target_weights,
)
# Grid search over regularisation parameter and weight trimming
# First calculates design effects for all combinations, because this is cheap
all_perf = []
for wr in trim_options:
for i in range(links.shape[1]):
s = fit["lambdau"][i]
link = links[:, i]
weights = weights_from_link(
link,
balance_classes,
sample_weights,
target_weights,
weight_trimming_mean_ratio=wr,
)
deff = design_effect(weights)
all_perf.append(
{
"s": s,
"s_index": i,
"trim": wr,
"design_effect": deff,
}
)
all_perf = pd.DataFrame(all_perf)
best = (
# pyre-fixme[16]: `Optional` has no attribute `tail`.
all_perf[all_perf.design_effect < max_de]
# pyre-fixme[6]: For 1st param expected `Union[typing_extensions.Literal[0],
# typing_extensions.Literal['index']]` but got
# `typing_extensions.Literal['design_effect']`.
.sort_values("design_effect").tail(n_asmd_candidates)
)
logger.debug(f"Regularisation with design effect below {max_de}: \n {best}")
# Calculate ASMDS for best 10 candidates (assuming that higher DE means
# more bias reduction)
all_perf = []
for _, r in best.iterrows():
wr = r.trim
s_index = int(r.s_index)
s = fit["lambdau"][s_index]
link = links[:, s_index]
weights = weights_from_link(
link,
balance_classes,
sample_weights,
target_weights,
weight_trimming_mean_ratio=wr,
)
adjusted_df = sample_df[sample_df.index.isin(weights.index)]
asmd_after = asmd(
# pyre-fixme[6]: For 1st param expected `DataFrame` but got `Series`.
sample_df=adjusted_df,
target_df=target_df,
sample_weights=weights,
target_weights=target_weights,
)
# TODO: use asmd_improvement function for that
asmd_improvement = (
asmd_before.loc["mean(asmd)"] - asmd_after.loc["mean(asmd)"]
) / asmd_before.loc["mean(asmd)"]
deff = design_effect(weights)
all_perf.append(
{
"s": s,
# pyre-fixme[61]: `i` is undefined, or not always defined.
"s_index": i,
"trim": wr,
"design_effect": deff,
"asmd_improvement": asmd_improvement,
"asmd": asmd_after.loc["mean(asmd)"],
}
)
all_perf = pd.DataFrame(all_perf)
best = (
all_perf[all_perf.design_effect < max_de]
# pyre-fixme[6]: For 1st param expected `Union[typing_extensions.Literal[0],
# typing_extensions.Literal['index']]` but got
# `typing_extensions.Literal['asmd_improvement']`.
.sort_values("asmd_improvement").tail(1)
)
logger.info(f"Best regularisation: \n {best}")
solution = {
"best": {"s": best.s.values, "trim": best.trim.values[0]},
"perf": all_perf,
}
return solution
# TODO: add memoaization (maybe in the adjust stage?!)
def ipw(
sample_df: pd.DataFrame,
sample_weights: pd.Series,
target_df: pd.DataFrame,
target_weights: pd.Series,
variables: Optional[List[str]] = None,
model: str = "glmnet",
weight_trimming_mean_ratio: Optional[Union[int, float]] = 20,
weight_trimming_percentile: Optional[float] = None,
balance_classes: bool = True,
transformations: str = "default",
na_action: str = "add_indicator",
max_de: Optional[float] = None,
formula: Union[str, List[str], None] = None,
penalty_factor: Optional[List[float]] = None,
one_hot_encoding: bool = False,
# TODO: This is set to be false in order to keep reproducibility of works that uses balance.
# The best practice is for this to be true.
random_seed: int = 2020,
*args,
**kwargs,
) -> Dict[str, Any]:
"""Fit an ipw (inverse propensity score weighting) for the sample using the target.
Args:
sample_df (pd.DataFrame): a dataframe representing the sample
sample_weights (pd.Series): design weights for sample
target_df (pd.DataFrame): a dataframe representing the target
target_weights (pd.Series): design weights for target
variables (Optional[List[str]], optional): list of variables to include in the model.
If None all joint variables of sample_df and target_df are used. Defaults to None.
model (str, optional): the model used for modeling the propensity scores.
"glmnet" is logistic model. Defaults to "glmnet".
weight_trimming_mean_ratio (Optional[Union[int, float]], optional): indicating the ratio from above according to which
the weights are trimmed by mean(weights) * ratio.
Defaults to 20.
weight_trimming_percentile (Optional[float], optional): if weight_trimming_percentile is not none, winsorization is applied.
if None then trimming is applied. Defaults to None.
balance_classes (bool, optional): whether to balance the sample and target size for running the model.
True is preferable for imbalanced cases.
It is done to make the computation of the glmnet more efficient.
It shouldn't have an effect on the final weights as this is factored
into the computation of the weights. TODO: add ref. Defaults to True.
transformations (str, optional): what transformations to apply to data before fitting the model.
See apply_transformations function. Defaults to "default".
na_action (str, optional): what to do with NAs.
See add_na_indicator function. Defaults to "add_indicator".
max_de (Optional[float], optional): upper bound for the design effect of the computed weights.
Used for choosing the model regularization and trimming.
If set to None, then it uses 'lambda_1se'. Defaults to 1.5.
formula (Union[str, List[str], None], optional): The formula according to which build the model.
In case of list of formula, the model matrix will be built in steps and
concatenated together. Defaults to None.
penalty_factor (Optional[List[float]], optional): the penalty used in the glmnet function in ipw. The penalty
should have the same length as the formula list (and applies to each element of formula).
Smaller penalty on some formula will lead to elements in that formula to get more adjusted, i.e. to have a higher chance to get into the model (and not zero out). A penalty of 0 will make sure the element is included in the model.
If not provided, assume the same penalty (1) for all variables. Defaults to None.
one_hot_encoding (bool, optional): whether to encode all factor variables in the model matrix with
almost_one_hot_encoding. This is recomended in case of using
LASSO on the data (Default: False).
one_hot_encoding_greater_3 creates one-hot-encoding for all
categorical variables with more than 2 categories (i.e. the
number of columns will be equal to the number of categories),
and only 1 column for variables with 2 levels (treatment contrast). Defaults to False.
random_seed (int, optional): Random seed to use. Defaults to 2020.
Raises:
Exception: f"Sample indicator only has value {_n_unique}. This can happen when your sample or target are empty from unknown reason"
NotImplementedError: if model is not "glmnet"
Returns:
Dict[str, Any]: A dictionary includes:
"weight" --- The weights for the sample.
"model" --- parameters of the model:fit, performance, X_matrix_columns, lambda,
weight_trimming_mean_ratio
Shape of the Dict:
{
"weight": weights,
"model": {
"method": "ipw",
"X_matrix_columns": X_matrix_columns_names,
"fit": fit,
"perf": performance,
"lambda": best_s,
"weight_trimming_mean_ratio": weight_trimming_mean_ratio,
},
}
"""
logger.info("Starting ipw function")
np.random.seed(
random_seed
) # setting random seed for cases of variations in cvglmnet
balance_util._check_weighting_methods_input(sample_df, sample_weights, "sample")
balance_util._check_weighting_methods_input(target_df, target_weights, "target")
variables = balance_util.choose_variables(sample_df, target_df, variables=variables)
logger.debug(f"Join variables for sample and target: {variables}")
sample_df = sample_df.loc[:, variables]
target_df = target_df.loc[:, variables]
if na_action == "drop":
(sample_df, sample_weights) = balance_util.drop_na_rows(
sample_df, sample_weights, "sample"
)
(target_df, target_weights) = balance_util.drop_na_rows(
target_df, target_weights, "target"
)
sample_n = sample_df.shape[0]
target_n = target_df.shape[0]
# Applying transformations
# Important! Variables that don't need transformations
# should be transformed with the *identity function*,
# otherwise will be dropped from the model
sample_df, target_df = balance_adjustment.apply_transformations(
(sample_df, target_df), transformations=transformations
)
variables = list(sample_df.columns)
logger.debug(f"Final variables in the model: {variables}")
logger.info("Building model matrix")
model_matrix_output = balance_util.model_matrix(
sample_df,
target_df,
variables,
add_na=(na_action == "add_indicator"),
return_type="one",
return_var_type="sparse",
# pyre-fixme[6]: for 7th parameter `formula` expected `Optional[List[str]]` but got `Union[None, List[str], str]`.
# TODO: fix pyre issue
formula=formula,
penalty_factor=penalty_factor,
one_hot_encoding=one_hot_encoding,
)
X_matrix = cast(
Union[pd.DataFrame, np.ndarray, csc_matrix],
model_matrix_output["model_matrix"],
)
X_matrix_columns_names = cast(
List[str], model_matrix_output["model_matrix_columns_names"]
)
penalty_factor = cast(Optional[List[float]], model_matrix_output["penalty_factor"])
# in cvglmnet: "penalty factors are internally rescaled to sum to nvars."
# (https://glmnet-python.readthedocs.io/en/latest/glmnet_vignette.html)
logger.info(
f"The formula used to build the model matrix: {model_matrix_output['formula']}"
)
logger.info(f"The number of columns in the model matrix: {X_matrix.shape[1]}")
logger.info(f"The number of rows in the model matrix: {X_matrix.shape[0]}")
in_sample = np.concatenate((np.ones(sample_n), np.zeros(target_n)))
_n_unique = np.unique(in_sample.reshape(in_sample.shape[0]))
if len(_n_unique) == 1:
raise Exception(
f"Sample indicator only has value {_n_unique}. This can happen when your "
"sample or target are empty from unknown reason"
)
if balance_classes:
odds = np.sum(sample_weights) / np.sum(target_weights)
else:
odds = 1
logger.debug(f"odds for balancing classes: {odds}")
y0 = np.concatenate((np.zeros(sample_n), target_weights * odds))
y1 = np.concatenate((sample_weights, np.zeros(target_n)))
y = np.column_stack((y0, y1))
# From glmnet documentation: https://glmnet-python.readthedocs.io/en/latest/glmnet_vignette.html
# "For binomial logistic regression, the response variable y should be either
# a factor with two levels, or a two-column matrix of counts or proportions."
logger.debug(f"X_matrix shape: {X_matrix.shape}")
logger.debug(f"y input shape: {y.shape}")
logger.debug(
f"penalty_factor frequency table {pd.crosstab(index=penalty_factor, columns='count')}"
f"Note that these are normalized by cvglmnet"
)
if model == "glmnet":
logger.info("Fitting logistic model")
foldid = np.resize(range(10), y.shape[0])
np.random.shuffle(
foldid
) # shuffels the values of foldid - note that we set the seed in the beginning of the function, so this order is fixed
logger.debug(
f"foldid frequency table {pd.crosstab(index=foldid, columns='count')}"
)
logger.debug(f"first 10 elements of foldid: {foldid[0:9]}")
with _patch_nan_in_amin_amax():
# we use _patch_nan_in_amin_amax here since sometimes
# cvglmnet could have one of the cross validated samples that
# produce nan. In which case, the lambda search returns nan
# instead of a value from the cross-validated options that successfully computed a lambda
# The current monkey-patch solves this problem and makes the function fail less.
with np.errstate(
divide="ignore"
): # ignoring np warning "divide by zero encountered in log"
with _patch_scipy_random():
fit = cvglmnet(
x=X_matrix,
y=y,
family="binomial",
ptype="deviance",
alpha=1,
penalty_factor=penalty_factor,
nlambda=250,
lambda_min=np.array([1e-6]),
nfolds=10,
foldid=foldid,
maxit=5000,
*args,
**kwargs,
)
logger.debug("Done with cvglmnet")
else:
raise NotImplementedError()
logger.debug(f"fit['lambda_1se']: {fit['lambda_1se']}")
X_matrix_sample = X_matrix[
:sample_n,
].toarray()
logger.info(f"max_de: {max_de}")
if max_de is not None:
regularisation_perf = choose_regularization(
fit,
sample_df,
target_df,
sample_weights,
target_weights,
X_matrix_sample,
balance_classes,
max_de,
)
best_s = regularisation_perf["best"]["s"]
weight_trimming_mean_ratio = regularisation_perf["best"]["trim"]
weight_trimming_percentile = None
else:
best_s = fit["lambda_1se"]
regularisation_perf = None
link = cvglmnetPredict(fit, X_matrix_sample, ptype="link", s=best_s)
logger.debug("Predicting")
weights = weights_from_link(
link,
balance_classes,
sample_weights,
target_weights,
weight_trimming_mean_ratio,
weight_trimming_percentile,
)
logger.info(f"Chosen lambda for cv: {best_s}")
performance = cv_glmnet_performance(
fit,
feature_names=list(X_matrix_columns_names),
s=best_s,
)
dev = performance["prop_dev_explained"]
logger.info(f"Proportion null deviance explained {dev}")
if np.unique(weights).shape[0] == 1: # All weights are the same
logger.warning("All weights are identical. The estimates will not be adjusted")
coefs = performance["coefs"][1:] # exclude intercept
if all(abs(coefs) < 1e-14):
# The value was determined by the unit-test test_adjustment/test_ipw_bad_adjustment_warnings
logger.warning(
(
"All propensity model coefficients are zero, your covariates do "
"not predict inclusion in the sample. The estimates will not be "
"adjusted"
)
)
if dev < 0.10:
logger.warning(
"The propensity model has low fraction null deviance explained "
f"({dev}). Results may not be accurate"
)
out = {
"weight": weights,
"model": {
"method": "ipw",
"X_matrix_columns": X_matrix_columns_names,
"fit": fit,
"perf": performance,
"lambda": best_s,
"weight_trimming_mean_ratio": weight_trimming_mean_ratio,
},
}
if max_de is not None:
out["model"]["regularisation_perf"] = regularisation_perf
logger.debug("Done ipw function")
return out
| balance-main | balance/weighting_methods/ipw.py |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import sys
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = "balance"
copyright = "Copyright © 2022 Meta Platforms, Inc."
author = "Meta Platforms"
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(".."))
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = [
"sphinx.ext.autodoc", # HTML generation from Py docstrings
"sphinx.ext.autosummary", # Generate Py docs recursively
"sphinx.ext.napoleon", # Support Google style docstrings
"sphinx.ext.doctest",
"sphinx.ext.todo",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
"sphinx.ext.ifconfig",
"sphinx.ext.viewcode",
]
autosummary_generate = True # Turn on sphinx.ext.autosummary
templates_path = ["_templates"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = "basic"
html_static_path = ["_static"]
| balance-main | sphinx/conf.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import pickle
from fig_1 import *
def evaluate_function_in_polytope():
# Generate projection matrix
np.random.seed(3)
B0 = np.random.randn(2, 100) # A REMBO projection
B = B0 / np.sqrt((B0 ** 2).sum(axis=0)) # A hypersphere projection
# Generate grid in low-d space
b = 60. # Something big to be sure we capture the whole range
density = 1000
grid_x = np.linspace(-b, b, density)
grid_y = np.linspace(-b, b, density)
grid2_x, grid2_y = np.meshgrid(grid_x, grid_y)
X = np.array([grid2_x.flatten(), grid2_y.flatten()]).transpose()
# Project up
Y = (np.linalg.pinv(B) @ X.transpose()).transpose()
z = ((Y<-1).any(axis=1) | (Y>1).any(axis=1)) # Points outside box bounds
Y[z, :] = 0. # Set them to 0 for now; we'll drop them later
fs = branin_centered(Y[:, :2])
# Drop points that violate polytope constraints in (1)
fs[z] = np.nan
fs = fs.reshape(grid2_x.shape)
# Same thing with B0 instead of B.
Y = (np.linalg.pinv(B0) @ X.transpose()).transpose()
z = ((Y<-1).any(axis=1) | (Y>1).any(axis=1)) # Points outside box bounds
Y[z, :] = 0. # Set them to 0 for now; we'll drop them later
fs_B0 = branin_centered(Y[:, :2])
fs_B0[z] = np.nan # Drop points outside the box bounds
fs_B0 = fs_B0.reshape(grid2_x.shape)
with open('data/figS4_sim_output.pckl', 'wb') as fout:
pickle.dump((grid_x, grid_y, fs, fs_B0), fout)
def make_fig_S4():
with open('data/figS4_sim_output.pckl', 'rb') as fin:
grid_x, grid_y, fs, fs_B0 = pickle.load(fin)
fig = plt.figure(figsize=(5.5, 2))
plt.set_cmap('RdBu_r')
ax = fig.add_subplot(121)
CS1 = ax.contourf(grid_x, grid_y, np.log(fs_B0), levels=np.linspace(-1, 6, 30))
ax.grid(False)
ax.set_xlabel(r'$x_1$', fontsize=9)
ax.set_ylabel(r'$x_2$', fontsize=9)
ax.set_xlim([-45, 45])
ax.set_ylim([-35, 35])
ax = fig.add_subplot(122)
CS1 = ax.contourf(grid_x, grid_y, np.log(fs), levels=np.linspace(-1, 6, 30))
ax.grid(False)
ax.set_xlabel(r'$x_1$', fontsize=9)
ax.set_ylabel(r'$x_2$', fontsize=9)
ax.set_xlim([-62, 62])
ax.set_ylim([-50, 50])
plt.subplots_adjust(right=0.99, top=0.99, left=0.1, bottom=0.17, wspace=0.45)
plt.savefig('pdfs/new_embedding.pdf', pad_inches=0)
if __name__ == '__main__':
#evaluate_function_in_polytope() # Takes 20s to run, creates data/figS4_sim_output.pckl
make_fig_S4()
| alebo-main | figs/fig_S4.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import numpy as np
from fig_1 import *
def hesbo_branin(X, mode):
# In 2-D, HESBO has 3 possible embeddings:
# Full rank, span x1 and x2
# x1=x2
# x1=-x2
Y = X.copy()
if mode == 1:
pass # All is well here!
elif mode == 2:
Y[:, 0] = Y[:, 1]
elif mode == 3:
Y[:, 0] = -Y[:, 1]
return branin_centered(Y)
def make_fig_S1():
# Evaluate the branin function on the grid under the three possible embeddings
grid_xhes, grid_yhes, fs_hesbo1 = eval_f_on_grid(hesbo_branin, [-1, 1], [-1, 1], {'mode': 1}, 2, density=1000)
grid_xhes, grid_yhes, fs_hesbo2 = eval_f_on_grid(hesbo_branin, [-1, 1], [-1, 1], {'mode': 3}, 2, density=1000)
grid_xhes, grid_yhes, fs_hesbo3 = eval_f_on_grid(hesbo_branin, [-1, 1], [-1, 1], {'mode': 2}, 2, density=1000)
fig = plt.figure(figsize=(5.5, 1.8), facecolor='w', edgecolor='w')
plt.set_cmap('RdBu_r')
for i, fs in enumerate([fs_hesbo1, fs_hesbo2, fs_hesbo3]):
ax = fig.add_subplot(1, 3, i + 1)
CS1 = ax.contourf(grid_xhes, grid_yhes, np.log(fs), levels=np.linspace(-1, 6, 30))
ax.grid(False)
ax.set_xlabel(r'$x_1$', fontsize=9)
ax.set_xlim([-1, 1])
ax.set_xticks([-1, -0.5, 0, 0.5, 1])
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
if i == 0:
ax.set_ylabel(r'$x_2$', fontsize=9)
ax.set_ylim([-1, 1])
else:
ax.set_yticklabels([])
plt.subplots_adjust(right=0.98, top=0.975, left=0.1, bottom=0.195)
plt.savefig('pdfs/hesbo_embeddings.pdf', pad_inches=0)
if __name__ == '__main__':
make_fig_S1()
| alebo-main | figs/fig_S1.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from matplotlib import rc
import matplotlib
rc('font', family='serif', style='normal', variant='normal', weight='normal', stretch='normal', size=8)
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['xtick.labelsize'] = 7
matplotlib.rcParams['ytick.labelsize'] = 7
matplotlib.rcParams['axes.titlesize'] = 9
plot_method_names = [
'ALEBO (ours)',
'REMBO',
'HeSBO, $d_e$=$d$',
'HeSBO, $d_e$=$2d$',
'REMBO-$\phi k_{\Psi}$',
'REMBO-$\gamma k_{\Psi}$',
'EBO',
'Add-GP-UCB',
'SMAC',
'CMA-ES',
'TuRBO',
'Sobol',
'CoordinateLineBO',
'RandomLineBO',
'DescentLineBO',
]
plot_colors={
'ALEBO (ours)': plt.cm.tab20(0),
'REMBO': plt.cm.tab20(1),
'HeSBO, $d_e$=$d$': plt.cm.tab20(2),
'HeSBO, $d_e$=$2d$': plt.cm.tab20(3),
'REMBO-$\phi k_{\Psi}$': plt.cm.tab20(4),
'REMBO-$\gamma k_{\Psi}$': plt.cm.tab20(5),
'EBO': plt.cm.tab20(6),
'Add-GP-UCB': plt.cm.tab20(7),
'SMAC': plt.cm.tab20(8),
'CMA-ES': plt.cm.tab20(9),
'TuRBO': plt.cm.tab20(10),
'Sobol': plt.cm.tab20(14),
'CoordinateLineBO': plt.cm.tab20(12),
'RandomLineBO': plt.cm.tab20(16),
'DescentLineBO': plt.cm.tab20(18),
}
| alebo-main | figs/plot_config.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import numpy as np
import pickle
from plot_config import *
def make_fig_S5():
with open('data/fig4_sim_output.pckl', 'rb') as fin:
res = pickle.load(fin)
nsamp = 1000
fig = plt.figure(figsize=(5.5, 2))
for i, d in enumerate([2, 6, 10]):
ax = fig.add_subplot(1, 3, i + 1)
x = [d_use for d_use in range(21) if d_use >= d]
y1 = np.array([res['rembo'][(100, d, d_use)] for d_use in x])
y2 = np.array([res['hesbo'][(100, d, d_use)] for d_use in x])
y3 = np.array([res['unitsphere'][(100, d, d_use)] for d_use in x])
y1err = 2 * np.sqrt(y1 * (1 - y1) / nsamp)
y2err = 2 * np.sqrt(y2 * (1 - y2) / nsamp)
y3err = 2 * np.sqrt(y3 * (1 - y3) / nsamp)
ax.errorbar(x, y1, yerr=y1err, color=plt.cm.tab10(0), marker='')
ax.errorbar(x, y2, yerr=y2err, color=plt.cm.tab10(1), marker='')
ax.errorbar(x, y3, yerr=y3err, color=plt.cm.tab10(2), marker='')
ax.set_title(r'$d={d}$'.format(d=d))
if i == 0:
ax.set_ylabel('Probability embedding\ncontains optimizer', fontsize=9)
ax.legend(['REMBO', 'HeSBO', r'Hypersphere'], loc='lower right', fontsize=7)
ax.set_xlabel(r'$d_e$', fontsize=9)
ax.set_xlim([0, 21])
ax.set_ylim([-0.02, 1.02])
ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
if i > 0:
ax.set_yticklabels([])
ax.grid(True, alpha=0.2)
plt.subplots_adjust(right=0.99, bottom=0.17, left=0.10, top=0.89, wspace=0.1)
plt.savefig('pdfs/lp_solns_ext.pdf', pad_inches=0)
if __name__ == '__main__':
# Assumes fig_4 has been run
make_fig_S5()
| alebo-main | figs/fig_S5.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import pickle
import time
import torch
import numpy as np
import cvxpy as cp # 1.0.25
from plot_config import *
def gen_A_rembo(d: int, D: int) -> np.ndarray:
A = torch.randn(D, d, dtype=torch.double)
return A.numpy()
def gen_A_hesbo(d: int, D:int) -> np.ndarray:
A = torch.zeros((D, d), dtype=torch.double)
h = torch.randint(d, size=(D,))
s = 2 * torch.randint(2, size=(D,), dtype=torch.double) - 1
for i in range(D):
A[i, h[i]] = s[i]
return A.numpy()
def gen_A_unitsphere(d: int, D: int) -> np.ndarray:
A = np.random.randn(D, d) # A REMBO projection _up_
A = A / np.sqrt((A ** 2).sum(axis=1))[:, None]
return A
def A_contains_xstar(xstar, A, perm):
d = len(xstar)
D = A.shape[0]
Acon = np.zeros((d, D))
Acon[:d, :d] = np.diag(np.ones(d))
# Shuffle columns, to place true embedding on columns perm
Acon = Acon[:, perm]
Q = A @ np.linalg.pinv(A) - np.eye(D)
A_eq = np.vstack((Acon, Q))
b_eq = np.hstack((xstar, np.zeros(D)))
c = np.zeros(D)
x = cp.Variable(D)
prob = cp.Problem(
cp.Minimize(c.T * x),
[
A_eq @ x == b_eq,
x >= -1,
x <= 1,
],
)
prob.solve(solver=cp.ECOS)
if prob.status == cp.OPTIMAL:
has_opt = True
elif prob.status == cp.INFEASIBLE:
has_opt = False
else:
raise ValueError(prob.status)
return has_opt, prob
def p_A_contains_optimizer(d, D, d_use, gen_A_fn, nsamp):
num_feas = 0.
for _ in range(nsamp):
# Sample location of optimizer uniformly on [-1, 1]^d
xstar = np.random.rand(d) * 2 - 1
# Sample features of embedding (first d) uniformly at random
perm = list(range(D))
np.random.shuffle(perm)
# Generate projection matrix
A = gen_A_fn(d_use, D)
has_opt, _ = A_contains_xstar(xstar, A, perm)
num_feas += float(has_opt)
return num_feas / nsamp
def run_simulation1():
t1 = time.time()
nsamp = 1000
res = {'rembo': {}, 'hesbo': {}, 'unitsphere': {}}
D = 100
for d in [2, 6, 10]:
for d_use in range(1, 21):
if d_use < d:
continue
res['rembo'][(D, d, d_use)] = p_A_contains_optimizer(
d=d, D=D, d_use=d_use, gen_A_fn=gen_A_rembo, nsamp=nsamp
)
res['hesbo'][(D, d, d_use)] = p_A_contains_optimizer(
d=d, D=D, d_use=d_use, gen_A_fn=gen_A_hesbo, nsamp=nsamp
)
res['unitsphere'][(D, d, d_use)] = p_A_contains_optimizer(
d=d, D=D, d_use=d_use, gen_A_fn=gen_A_unitsphere, nsamp=nsamp
)
print(time.time() - t1)
with open('data/fig4_sim_output.pckl', 'wb') as fout:
pickle.dump(res, fout)
def make_fig_4():
with open('data/fig4_sim_output.pckl', 'rb') as fin:
res = pickle.load(fin)
nsamp = 1000
fig = plt.figure(figsize=(2.63, 1.45))
for i, d in enumerate([2, 6]):
ax = fig.add_subplot(1, 2, i + 1)
x = [d_use for d_use in range(21) if d_use >= d]
y1 = np.array([res['rembo'][(100, d, d_use)] for d_use in x])
y2 = np.array([res['hesbo'][(100, d, d_use)] for d_use in x])
y3 = np.array([res['unitsphere'][(100, d, d_use)] for d_use in x])
y1err = 2 * np.sqrt(y1 * (1 - y1) / nsamp)
y2err = 2 * np.sqrt(y2 * (1 - y2) / nsamp)
y3err = 2 * np.sqrt(y3 * (1 - y3) / nsamp)
ax.errorbar(x, y1, yerr=y1err, color=plt.cm.tab10(0), marker='')
ax.errorbar(x, y2, yerr=y2err, color=plt.cm.tab10(1), marker='')
ax.errorbar(x, y3, yerr=y3err, color=plt.cm.tab10(2), marker='')
ax.set_title(r'$d={d}$'.format(d=d))
if i == 0:
ax.set_ylabel(r'$P_{\textrm{opt}}$', fontsize=9)
ax.legend(['REMBO', 'HeSBO', r'Hypersphere'], loc='lower right', fontsize=5)
ax.set_xlabel(r'$d_e$', fontsize=9)
ax.set_xlim([0, 21])
ax.set_ylim([-0.02, 1.02])
ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
if i > 0:
ax.set_yticklabels([])
ax.grid(True, alpha=0.2)
plt.subplots_adjust(right=0.99, bottom=0.23, left=0.17, top=0.87, wspace=0.1)
plt.savefig('pdfs/lp_solns.pdf', pad_inches=0)
if __name__ == '__main__':
#run_simulation1() # Will take about 30mins, produces data/fig4_sim_output.pckl
make_fig_4()
| alebo-main | figs/fig_4.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import json
import numpy as np
from ax.storage.json_store.decoder import object_from_json
from plot_config_nr import *
def make_fig_5():
# Load in the benchmark results
res = {}
for fname in ['hartmann6_1000', 'branin_gramacy_100']:
with open(f'../benchmarks/results/{fname}_aggregated_results.json', 'r') as fin:
res.update(object_from_json(json.load(fin)))
# A map from method idx in plot_method_names to the name used in res
method_idx_to_res_name = {
0: 'ALEBO',
1: 'REMBO',
2: 'HeSBO, d=d',
3: 'HeSBO, d=2d',
4: 'rrembos_standard_kPsi',
5: 'rrembos_reverse_kPsi',
6: 'ebo',
7: 'addgpucb',
8: 'smac',
9: 'cmaes',
10: 'turbo',
11: 'Sobol',
12: 'coordinatelinebo',
13: 'randomlinebo',
14: 'descentlinebo',
}
# Make the figure
fig = plt.figure(figsize=(5.5, 3.7))
####### Branin, D=100
ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(234)
res_h = res['Branin, D=100']
for idx, m in enumerate(plot_method_names):
res_name = method_idx_to_res_name[idx]
if res_name not in res_h.objective_at_true_best:
continue # Not run on this problem
Y = res_h.objective_at_true_best[res_name]
f = Y.mean(axis=0)
x = np.arange(1, 51)
color = plot_colors[m]
ax1.plot(x, f, color=color, label=m)
parts = ax2.violinplot(positions=[idx], dataset=Y[:, 49], showmeans=True)
for pc in parts['bodies']:
pc.set_facecolor(color)
pc.set_edgecolor(color)
for field in ['cmeans', 'cmaxes', 'cmins', 'cbars']:
parts[field].set_color(color)
ax1.set_xlim([0, 51])
ax1.set_ylabel('Best value found', fontsize=7)
ax1.set_xlabel('Function evaluations', fontsize=7)
ax1.axhline(y=0.397887, c='gray', ls='--')
ax1.grid(alpha=0.2, zorder=-10)
ax1.set_ylim([0, 7])
ax2.set_xticks(range(12))
ax2.set_xticklabels([])
ax2.set_ylabel('Final value', fontsize=7)
ax2.grid(alpha=0.2, zorder=-10)
ax2.set_xticklabels([plot_method_names[i] for i in range(12)], fontsize=6)
ax2.xaxis.set_tick_params(rotation=90)
# Make the legend
custom_lines = []
names = []
for i in range(12):
names.append(plot_method_names[i])
custom_lines.append(
Line2D([0], [0], color=plot_colors[plot_method_names[i]], lw=2)
)
order = range(12)
names = [names[o] for o in order]
custom_lines = [custom_lines[o] for o in order]
ax1.legend(custom_lines, names, ncol=6, fontsize=5.5, bbox_to_anchor=(3.52, -2.26))
ax1.set_title('Branin, $d$=2, $D$=100', fontsize=8)
####### Hartmann6, D=1000
ax1 = fig.add_subplot(232)
ax2 = fig.add_subplot(235)
res_h = res['Hartmann6, D=1000']
for idx, m in enumerate(plot_method_names):
res_name = method_idx_to_res_name[idx]
if res_name not in res_h.objective_at_true_best:
continue # Not run on this problem
Y = res_h.objective_at_true_best[res_name]
f = Y.mean(axis=0)
x = np.arange(1, 201)
color = plot_colors[m]
ax1.plot(x, f, color=color, label=m)
parts = ax2.violinplot(positions=[idx], dataset=Y[:, 199], showmeans=True)
for pc in parts['bodies']:
pc.set_facecolor(color)
pc.set_edgecolor(color)
for field in ['cmeans', 'cmaxes', 'cmins', 'cbars']:
parts[field].set_color(color)
ax1.set_xlim([0, 201])
#ax1.set_ylabel('Best value found', fontsize=9)
ax1.set_xlabel('Function evaluations', fontsize=7)
ax1.axhline(y=-3.32237, c='gray', ls='--')
ax1.grid(alpha=0.2, zorder=-10)
ax1.set_ylim([-3.5, -0.5])
ax2.set_xticks(range(12))
ax2.set_xticklabels([])
#ax2.set_ylabel('Final value', fontsize=9)
ax2.grid(alpha=0.2, zorder=-10)
ax2.set_xticklabels([plot_method_names[i] for i in range(12)], fontsize=6)
ax2.xaxis.set_tick_params(rotation=90)
ax1.set_title('Hartmann6, $d$=6, $D$=1000', fontsize=8)
####### Gramacy, D=100
ax1 = fig.add_subplot(233)
ax2 = fig.add_subplot(236)
res_h = res['Gramacy, D=100']
for idx, m in enumerate(plot_method_names):
res_name = method_idx_to_res_name[idx]
if res_name not in res_h.objective_at_true_best:
continue # Not run on this problem
Y = res_h.objective_at_true_best[res_name]
f = Y.mean(axis=0)
x = np.arange(1, 51)
color = plot_colors[m]
ax1.plot(x, f, color=color, label=m)
parts = ax2.violinplot(positions=[idx], dataset=Y[:, 49], showmeans=True)
for pc in parts['bodies']:
pc.set_facecolor(color)
pc.set_edgecolor(color)
for field in ['cmeans', 'cmaxes', 'cmins', 'cbars']:
parts[field].set_color(color)
ax1.set_xlim([0, 51])
#ax1.set_ylabel('Best value found', fontsize=9)
ax1.set_xlabel('Function evaluations', fontsize=7)
ax1.set_ylim([0.58, 1])
ax1.axhline(y=0.5998, c='gray', ls='--')
ax1.grid(alpha=0.2, zorder=-10)
ax2.set_xticks(range(12))
ax2.set_xticklabels([plot_method_names[i] for i in range(12)], fontsize=6)
ax2.xaxis.set_tick_params(rotation=90)
#ax2.set_ylabel('Final value', fontsize=9)
ax2.grid(alpha=0.2, zorder=-10)
ax1.set_title('Gramacy, $d$=2, $D$=100', fontsize=8)
plt.subplots_adjust(right=0.995, bottom=0.3, left=0.07, top=0.94, wspace=0.25, hspace=0.45)
plt.savefig('pdfs/benchmark_results_t.pdf', pad_inches=0)
if __name__ == '__main__':
make_fig_5()
| alebo-main | figs/fig_5.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import json
import numpy as np
from ax.storage.json_store.decoder import object_from_json
def table_S1_data():
with open('../benchmarks/results/all_aggregated_results.json', 'r') as fin:
res = object_from_json(json.load(fin))
for D in [100, 1000]:
pname = f'Hartmann6, D={D}'
print('-----', pname)
for m, ts in res[pname].gen_times.items():
# Get average total time for fit and gen
t = np.mean(ts)
t += np.mean(res[pname].fit_times[m])
# Divide by 200 to be time per iteration
t /= 200.
print(f'{m}: {t}')
if __name__ == '__main__':
table_S1_data()
| alebo-main | figs/table_S1.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import numpy as np
from ax.utils.measurement.synthetic_functions import branin, hartmann6
from plot_config import *
def branin_centered(X):
# Evaluate branin problem, scaled to X \in [-1, 1]^2
# Map from [-1, 1]^2 to [[-5, 10], [0, 15]]
assert X.min() >= -1
assert X.max() <= 1
Xu = (X + 1) / 2.
Xu *= 15
Xu[:, 0] -= 5
return branin(Xu)
def hartmann6_centered(X):
# Evaluate hartmann6 problem, scaled to X \in [-1, 1]^2
# Map from [-1, 1]^6 to [0, 1]^6
assert X.min() >= -1
assert X.max() <= 1
Xu = (X + 1) / 2.
return hartmann6(Xu)
def rembo_branin(X, A):
# Map from low-d to high-D
Y = (A @ X.transpose()).transpose()
# Clip to [-1, 1]
Y = np.clip(Y, a_min=-1, a_max=1)
# Evaluate Branin on first two components
return branin_centered(Y[:, :2])
def rembo_hartmann6(X, A):
# Map from low-d to high-D
Y = (A @ X.transpose()).transpose()
# Clip to [-1, 1]
Y = np.clip(Y, a_min=-1, a_max=1)
# Evaluate Hartmann6 on first six components
return hartmann6_centered(Y[:, :6])
def eval_f_on_grid(f, bounds_x, bounds_y, f_kwargs, d, density=100):
# prepare the grid on which to evaluate the problem
grid_x = np.linspace(bounds_x[0], bounds_x[1], density)
grid_y = np.linspace(bounds_y[0], bounds_y[1], density)
grid2_x, grid2_y = np.meshgrid(grid_x, grid_y)
X = np.array([grid2_x.flatten(), grid2_y.flatten()]).transpose()
if d > 2:
# Add in the other components, just at 0
X = np.hstack((X, np.zeros((X.shape[0], d - 2))))
fs = f(X, **f_kwargs).reshape(grid2_x.shape)
return grid_x, grid_y, fs
def make_fig_1():
## Branin
# Evaluate the usual Branin problem, but scaled to [-1, 1]^2
grid_x1, grid_y1, fs_branin = eval_f_on_grid(branin_centered, [-1, 1], [-1, 1], {}, 2)
# Generate a REMBO projection matrix
D = 100
np.random.seed(1)
A_b = np.random.randn(D, 2)
# Evaluate the function across the low-d space
bounds = [-np.sqrt(2), np.sqrt(2)]
grid_x2, grid_y2, fs_rembo = eval_f_on_grid(rembo_branin, bounds, bounds, {'A': A_b}, 2)
## Hartmann6
# Evaluate the usual Hartmann6 problem, but scaled to [-1, 1]^6
grid_x1h, grid_y1h, fs_hartmann6 = eval_f_on_grid(hartmann6_centered, [-1, 1], [-1, 1], {}, 6)
# Generate a REMBO projection matrix
D = 100
A_h = np.random.randn(D, 6)
# Evaluate the function across the low-d space
bounds = [-np.sqrt(6), np.sqrt(6)]
grid_x2h, grid_y2h, fs_rembo_h = eval_f_on_grid(rembo_hartmann6, bounds, bounds, {'A': A_h}, 6)
# Make the figure
fig = plt.figure(figsize=(5.5, 1.2), facecolor='w', edgecolor='w')
plt.set_cmap('RdBu_r')
### Branin
ax = fig.add_subplot(141)
CS1 = ax.contourf(grid_x1, grid_y1, np.log(fs_branin), levels=np.linspace(-1, 6, 30))
ax.grid(False)
#ax.set_xlabel(r'$x_1$', fontsize=9)
ax.set_xlim([-1, 1])
#ax.set_xticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticks([])
#ax.set_ylabel(r'$x_2$', fontsize=9)
ax.set_ylim([-1, 1])
ax.set_yticks([])
#ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_title(r'Branin function, $d$=2')
ax = fig.add_subplot(142)
CS1 = ax.contourf(grid_x2, grid_y2, np.log(fs_rembo), levels=np.linspace(-1, 6, 30))
ax.grid(False)
#ax.set_xlabel(r'$x_1$', fontsize=9)
ax.set_xlim([-np.sqrt(2), np.sqrt(2)])
ax.set_xticks([])
#ax.set_xticks([-1.4, -1, -0.5, 0, 0.5, 1, 1.4])
#ax.set_ylabel(r'$x_2$', fontsize=9)
ax.set_ylim([-np.sqrt(2), np.sqrt(2)])
ax.set_yticks([])
#ax.set_yticks([-1.4, -1, -0.5, 0, 0.5, 1, 1.4])
ax.set_title('REMBO embedding,\n$D$=100, $d_e$=2')
### Hartmann6
ax = fig.add_subplot(143)
CS1f = ax.contourf(grid_x1h, grid_y1h, fs_hartmann6, levels=np.linspace(-1.2, 0., 20))
ax.grid(False)
#ax.set_xlabel(r'$x_1$', fontsize=9)
ax.set_xlim([-1, 1])
ax.set_xticks([])
#ax.set_xticks([-1, -0.5, 0, 0.5, 1])
#ax.set_ylabel(r'$x_2$', fontsize=9)
ax.set_ylim([-1, 1])
ax.set_yticks([])
#ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_title(r'Hartmann6 function, $d$=6')
ax = fig.add_subplot(144)
CS1f = ax.contourf(grid_x2h, grid_y2h, fs_rembo_h, levels=np.linspace(-1.2, 0., 20))
ax.grid(False)
#ax.set_xlabel(r'$x_1$', fontsize=9)
ax.set_xlim([-np.sqrt(6), np.sqrt(6)])
ax.set_xticks([])
#ax.set_xticks([-2, -1, 0, 1, 2,])
#ax.set_ylabel(r'$x_2$', fontsize=9)
ax.set_ylim([-np.sqrt(6), np.sqrt(6)])
ax.set_yticks([])
#ax.set_yticks([-2, -1, 0, 1, 2,])
ax.set_title('REMBO embedding,\n$D$=100, $d_e$=6')
fig.subplots_adjust(wspace=0.13, top=0.74, bottom=0.05, right=0.99, left=0.01)
plt.savefig('pdfs/rembo_illustrations_w.pdf', pad_inches=0)
if __name__ == '__main__':
make_fig_1()
| alebo-main | figs/fig_1.py |
import json
import numpy as np
from ax.storage.json_store.decoder import object_from_json
from plot_config import *
def make_nasbench_figure():
with open('../benchmarks/results/nasbench_aggregated_results.json', 'r') as fin:
res = object_from_json(json.load(fin))
# A map from method idx in plot_method_names to the name used in res
method_idx_to_res_name = {
1: 'REMBO',
3: 'HeSBO',
9: 'cmaes',
10: 'turbo',
11: 'Sobol',
0: 'ALEBO',
}
plot_method_names[3] = 'HeSBO'
plot_colors['HeSBO'] = plt.cm.tab20(3)
fig = plt.figure(figsize=(2.96, 2.0))
ax1 = fig.add_subplot(111)
method_idx = 1
method_names_used = []
for i, m in method_idx_to_res_name.items():
f = np.nanmean(res[m], axis=0)
sem = np.nanstd(res[m], axis=0) / np.sqrt(res[m].shape[0])
x = np.arange(1, 51)
mname = plot_method_names[i]
color = plot_colors[mname]
ax1.plot(x, f, color=color, label=mname)
ax1.errorbar(x, f, yerr=2 * sem, color=color, alpha=0.5, ls='')
ax1.set_xlim([0, 51])
ax1.set_ylabel('Best feasible test accuracy', fontsize=9)
ax1.set_xlabel('Function evaluations', fontsize=9)
#ax1.legend(bbox_to_anchor=(1.0, 1.24), ncol=4, fontsize=6, columnspacing=1.65)
ax1.legend(ncol=2, loc='lower right', fontsize=7)
ax1.set_ylim([0.92, 0.936])
ax1.set_yticks([0.92, 0.925, 0.93, 0.935])
ax1.set_yticklabels(['92.0\%', '92.5\%', '93.0\%', '93.5\%'])
ax1.grid(alpha=0.2, zorder=-10)
plt.subplots_adjust(right=0.98, bottom=0.17, left=0.19, top=0.98)
plt.savefig(f'pdfs/nas.pdf', pad_inches=0)
#plt.show()
if __name__ == '__main__':
make_nasbench_figure()
| alebo-main | figs/fig_6.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import json
import numpy as np
from ax.storage.json_store.decoder import object_from_json
from plot_config import *
def extract_sensitivity_results():
res = {}
for fname in [
'branin_gramacy_100',
'sensitivity',
]:
with open(f'../benchmarks/results/{fname}_aggregated_results.json', 'r') as fin:
res.update(object_from_json(json.load(fin)))
# Results for D=100
ys1 = {}
for d in [2, 3, 4, 5, 6, 7, 8]:
if d == 4:
ys1[d] = res['Branin, D=100'].objective_at_true_best['ALEBO']
else:
ys1[d] = res['Branin, D=100_sensitivity'].objective_at_true_best[f'ALEBO, d={d}']
# Results for d_e=4
ys2 = {}
for D in [50, 100, 200, 500, 1000]:
if D == 100:
ys2[D] = res['Branin, D=100'].objective_at_true_best['ALEBO']
else:
ys2[D] = res[f'Branin, D={D}_sensitivity'].objective_at_true_best['ALEBO']
return ys1, ys2
def make_fig_S8():
ys1, ys2 = extract_sensitivity_results()
fig = plt.figure(figsize=(5.5, 2.2))
ax = fig.add_subplot(121)
x = np.arange(1, 51)
for d_e in [2, 3, 4, 6, 8]:
ax.plot(x, ys1[d_e].mean(axis=0), label=f'$d_e={d_e}$')
ax.set_ylim([0, 7])
ax.set_yticks([0, 2, 4, 6])
ax.legend(fontsize=7)
ax.set_title(r'Branin, $D=100$')
ax.set_ylabel('Best value found', fontsize=9)
ax.set_xlabel('Function evaluations', fontsize=9)
ax.axhline(y=0.397887, c='gray', ls='--')
ax.grid(alpha=0.2, zorder=-10)
ax.set_xlim([0, 51])
ax = fig.add_subplot(122)
for D in [50, 100, 200, 500, 1000]:
ax.plot(x, ys2[D].mean(axis=0), label=f'$D={D}$')
ax.set_title(r'Branin, $d_e=4$')
ax.set_ylim([0, 7])
ax.legend(fontsize=7)
ax.set_xlabel('Function evaluations', fontsize=9)
ax.axhline(y=0.397887, c='gray', ls='--')
ax.grid(alpha=0.2, zorder=-10)
ax.set_yticks([0, 2, 4, 6])
ax.set_xlim([0, 51])
ax.set_yticklabels([])
plt.subplots_adjust(right=0.995, bottom=0.16, left=0.06, top=0.91, wspace=0.05)
plt.savefig('pdfs/branin_by_d_D_traces.pdf', pad_inches=0)
if __name__ == '__main__':
make_fig_S8()
| alebo-main | figs/fig_S8.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import numpy as np
from plot_config import *
def make_fig_2():
# Run the simulation
np.random.seed(1)
Ds = [20, 100, 1000]
ds = list(range(1, 6))
nsamp = 1000
p_interior = {}
for D in Ds:
for d in ds:
p_interior[(D, d)] = 0.
for _ in range(nsamp):
# Generate a REMBO projection
A = np.random.randn(D, d)
# Sample a point in [-sqrt(d), sqrt(d)]^d
x = (np.random.rand(d) * 2 - 1) * np.sqrt(d)
# Project up
z = A @ x
# Check if satisfies box bounds
if z.min() >= -1 and z.max() <= 1:
p_interior[(D, d)] += 1
p_interior[(D, d)] /= nsamp
# Make the figure
fig = plt.figure(figsize=(2., 1.55))
ax = fig.add_subplot(111)
ax.grid(alpha=0.5)
for i, D in enumerate(Ds):
ax.plot(ds, [p_interior[(D, d)] for d in ds], 'x-', c=plt.cm.tab10(i))
ax.legend([r'$D=20$', r'$D=100$', r'$D=1000$'], fontsize=7)
ax.set_xlabel(r'Embedding dimension $d_e$', fontsize=9)
ax.set_ylabel('Probability projection\nsatisfies box bounds', fontsize=9)
plt.subplots_adjust(right=0.99, bottom=0.22, left=0.3, top=0.94)
plt.savefig('pdfs/rembo_p_interior.pdf', pad_inches=0)
if __name__ == '__main__':
make_fig_2()
| alebo-main | figs/fig_2.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import time
import numpy as np
import torch
import pickle
from ax.models.torch.alebo import ALEBO
from ax.models.random.alebo_initializer import ALEBOInitializer
from ax.models.torch.botorch import BotorchModel
from botorch.test_functions.synthetic import Hartmann
from botorch.models.gpytorch import BatchedMultiOutputGPyTorchModel
from torch import Tensor
from gpytorch.means.constant_mean import ConstantMean
from gpytorch.models.exact_gp import ExactGP
from gpytorch.likelihoods.gaussian_likelihood import FixedNoiseGaussianLikelihood
from gpytorch.kernels.rbf_kernel import RBFKernel
from gpytorch.kernels.scale_kernel import ScaleKernel
from gpytorch.mlls.exact_marginal_log_likelihood import ExactMarginalLogLikelihood
from botorch.fit import fit_gpytorch_model
from gpytorch.distributions.multivariate_normal import MultivariateNormal
from plot_config import *
def highDhartmann6(X):
# X \in [-1, 1]^D
h = Hartmann()
Xd = (X[:, :6] + 1) / 2.
return h.evaluate_true(Xd)
def gen_train_test_sets(B, ntrain, ntest, seed_train=1000, seed_test=2000):
# Generate training points
m1 = ALEBOInitializer(B=B.numpy(), seed=seed_train)
train_X = torch.tensor(m1.gen(n=ntrain, bounds=[])[0], dtype=torch.double)
train_Y = highDhartmann6(train_X)
# Standardize train Y
mu = train_Y.mean()
sigma = train_Y.std()
train_Y = (train_Y - mu) / sigma
train_Y = train_Y.unsqueeze(1)
train_Yvar = 1e-7 * torch.ones(train_Y.shape)
# Generate test points
m2 = ALEBOInitializer(B=B.numpy(), seed=seed_test)
test_X = torch.tensor(m2.gen(n=ntest, bounds=[])[0], dtype=torch.double)
test_Y = highDhartmann6(test_X)
return train_X, train_Y, train_Yvar, test_X, test_Y, mu, sigma
def fit_and_predict_alebo(B, train_X, train_Y, train_Yvar, test_X, mu, sigma):
m = ALEBO(B=B)
m.fit([train_X], [train_Y], [train_Yvar], [], [], [], [], [])
f, var = m.predict(test_X)
# Return predictions, un-standardized
return f.squeeze() * sigma + mu, var.squeeze() * sigma ** 2
def fit_and_predict_map(B, train_X, train_Y, train_Yvar, test_X, mu, sigma):
m = ALEBO(B=B, laplace_nsamp=1) # laplace_nsamp=1 uses MAP estimate
m.fit([train_X], [train_Y], [train_Yvar], [], [], [], [], [])
f, var = m.predict(test_X)
# Return predictions, un-standardized
return f.squeeze() * sigma + mu, var.squeeze() * sigma ** 2
class ARDRBFGP(BatchedMultiOutputGPyTorchModel, ExactGP):
"""A GP with fixed observation noise and an ARD RBF kernel."""
def __init__(self, train_X: Tensor, train_Y: Tensor, train_Yvar: Tensor) -> None:
self._validate_tensor_args(X=train_X, Y=train_Y, Yvar=train_Yvar)
self._set_dimensions(train_X=train_X, train_Y=train_Y)
train_X, train_Y, train_Yvar = self._transform_tensor_args(
X=train_X, Y=train_Y, Yvar=train_Yvar
)
likelihood = FixedNoiseGaussianLikelihood(
noise=train_Yvar, batch_shape=self._aug_batch_shape
)
ExactGP.__init__(
self, train_inputs=train_X, train_targets=train_Y, likelihood=likelihood
)
self.mean_module = ConstantMean(batch_shape=self._aug_batch_shape)
self.covar_module = ScaleKernel(
base_kernel=RBFKernel(
ard_num_dims=train_X.shape[-1],
batch_shape=self._aug_batch_shape,
),
batch_shape=self._aug_batch_shape,
)
self.to(train_X)
def forward(self, x: Tensor) -> MultivariateNormal:
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return MultivariateNormal(mean_x, covar_x)
def get_and_fit_ARDRBF(
Xs, Ys, Yvars, task_features=None, fidelity_features=None, refit_model=None, state_dict=None,
fidelity_model_id=None, metric_names=None,
):
m = ARDRBFGP(train_X=Xs[0], train_Y=Ys[0], train_Yvar=Yvars[0])
mll = ExactMarginalLogLikelihood(m.likelihood, m)
mll = fit_gpytorch_model(mll)
return m
def fit_and_predict_ARDRBF(B, train_X, train_Y, train_Yvar, test_X, mu, sigma):
# Project training data down to the embedding
BX = train_X @ B.t()
m = BotorchModel(model_constructor=get_and_fit_ARDRBF)
# Fit ARD RBF model on data in embedding
m.fit([BX], [train_Y], [train_Yvar], [], [], [], [], [])
# Predict on test points in embedding
f, var = m.predict(test_X @ B.t())
# Return predictions, un-standardized
return f.squeeze() * sigma + mu, var.squeeze() * sigma ** 2
def run_simulation():
D = 100
d = 6
ntrain = 100
ntest = 50
# Get projection
torch.manual_seed(1000)
B0 = torch.randn(d, D, dtype=torch.double)
B = B0 / torch.sqrt((B0 ** 2).sum(dim=0))
# Get fixed train/test data
train_X, train_Y, train_Yvar, test_X, test_Y, mu, sigma = gen_train_test_sets(B, ntrain, ntest)
# Predict with each model
f1, var1 = fit_and_predict_alebo(B, train_X, train_Y, train_Yvar, test_X, mu, sigma)
f2, var2 = fit_and_predict_map(B, train_X, train_Y, train_Yvar, test_X, mu, sigma)
f3, var3 = fit_and_predict_ARDRBF(B, train_X, train_Y, train_Yvar, test_X, mu, sigma)
# Save outcome
with open('data/fig3_sim_output.pckl', 'wb') as fout:
pickle.dump((test_Y, f1, var1, f2, var2, f3, var3), fout)
def make_fig_3():
# Load in simulation results
with open('data/fig3_sim_output.pckl', 'rb') as fin:
(test_Y, f1, var1, f2, var2, f3, var3) = pickle.load(fin)
fig = plt.figure(figsize=(2.63, 1.45))
ax = fig.add_subplot(121)
ax.errorbar(
x=test_Y.numpy(), y=f3.numpy(), yerr = 2 * np.sqrt(var3.numpy()),
c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3
)
x0 = -2.5
x1 = 0.5
ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2)
ax.set_xlim([x0, x1])
ax.set_ylim([x0, x1])
ax.set_yticks([0, -1, -2])
ax.set_xlabel('True value', fontsize=9)
ax.set_ylabel('Model prediction', fontsize=9)
ax.set_title('ARD RBF', fontsize=9)
ax.grid(True, alpha=0.2)
ax = fig.add_subplot(122)
ax.errorbar(
x=test_Y.numpy(), y=f1.numpy(), yerr = 2 * np.sqrt(var1.numpy()),
c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3
)
x0 = -3
x1 = 1
ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2)
ax.set_xlim([x0, x1])
ax.set_ylim([x0, x1])
ax.set_title('Mahalanobis', fontsize=9)
ax.set_xticks([-3, -2, -1, 0, 1])
ax.set_xlabel('True value', fontsize=9)
ax.grid(True, alpha=0.2)
plt.subplots_adjust(right=0.99, bottom=0.24, left=0.16, top=0.87, wspace=0.3)
plt.savefig('pdfs/ard_mahalanobis.pdf', pad_inches=0)
if __name__ == '__main__':
#run_simulation() # This will take ~20s, produces data/fig3_sim_output.pckl
make_fig_3()
| alebo-main | figs/fig_3.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
from fig_S8 import *
def make_fig_S9():
ys1, ys2 = extract_sensitivity_results()
d_es = [2, 3, 4, 5, 6, 7, 8]
mus_de = []
sems_de = []
for d_e in d_es:
Y = ys1[d_e][:, 49]
mus_de.append(Y.mean())
sems_de.append(Y.std() / np.sqrt(len(Y)))
Ds = [50, 100, 200, 500, 1000]
mus_D = []
sems_D = []
for D in Ds:
Y = ys2[D][:, 49]
mus_D.append(Y.mean())
sems_D.append(Y.std() / np.sqrt(len(Y)))
fig = plt.figure(figsize=(5.5, 1.8))
ax = fig.add_subplot(121)
ax.errorbar(d_es, mus_de, yerr=2*np.array(sems_de))
ax.set_ylim([0.3, 2.85])
ax.set_yticks([0.5, 1.0, 1.5, 2.0, 2.5])
ax.set_xlabel(r'Embedding dimension $d_e$', fontsize=9)
ax.set_title(r'Branin, $D=100$')
ax.set_ylabel('Best value found', fontsize=9)
ax.grid(alpha=0.2)
ax = fig.add_subplot(122)
ax.errorbar(Ds, mus_D, yerr=2*np.array(sems_D))
ax.set_ylim([0.3, 2.85])
ax.set_yticks([0.5, 1.0, 1.5, 2.0, 2.5])
ax.set_yticklabels([])
ax.set_xlabel(r'Ambient dimension $D$', fontsize=9)
ax.set_title('Branin, $d_e=4$')
ax.grid(alpha=0.2)
ax.set_xticks([50, 200, 500, 1000])
plt.subplots_adjust(right=0.93, bottom=0.19, left=0.12, top=0.89, wspace=0.1)
plt.savefig('pdfs/branin_by_D_d.pdf', pad_inches=0)
if __name__ == '__main__':
make_fig_S9()
| alebo-main | figs/fig_S9.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import json
import numpy as np
from ax.storage.json_store.decoder import object_from_json
from plot_config import *
def extract_ablation_results():
with open(f'../benchmarks/results/ablation_aggregated_results.json', 'r') as fin:
res = object_from_json(json.load(fin))
# Results
ys = {
'ALEBO': res['Branin, D=100_ablation'].objective_at_true_best['ALEBO, base'],
'Ablation: Matern kernel': res['Branin, D=100_ablation'].objective_at_true_best['ALEBO, kernel ablation'],
'Ablation: Normal projection': res['Branin, D=100_ablation'].objective_at_true_best['ALEBO, projection ablation'],
}
return ys
def make_fig_S_ablation():
ys = extract_ablation_results()
fig = plt.figure(figsize=(4, 2.5))
ax = fig.add_subplot(111)
x = np.arange(1, 51)
for k, y in ys.items():
f = y.mean(axis=0)
sem = y.std(axis=0) / np.sqrt(y.shape[0])
ax.errorbar(x, f, yerr=2 * sem, label=k)
ax.set_ylim([0, 7])
ax.set_yticks([0, 2, 4, 6])
ax.legend(fontsize=7, loc='lower left')
ax.set_title(r'Branin, $D=100$')
ax.set_ylabel('Best value found', fontsize=9)
ax.set_xlabel('Function evaluations', fontsize=9)
ax.axhline(y=0.397887, c='gray', ls='--')
ax.grid(alpha=0.2, zorder=-10)
ax.set_xlim([0, 51])
plt.subplots_adjust(right=0.995, bottom=0.16, left=0.1, top=0.91, wspace=0.05)
plt.savefig('pdfs/branin_ablation_traces.pdf', pad_inches=0)
if __name__ == '__main__':
make_fig_S_ablation()
| alebo-main | figs/fig_S10.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import numpy as np
import pickle
from plot_config import *
def make_fig_S2():
# Load in simulation results
with open('data/fig3_sim_output.pckl', 'rb') as fin:
(test_Y, f1, var1, f2, var2, f3, var3) = pickle.load(fin)
fig = plt.figure(figsize=(5.5, 2))
ax = fig.add_subplot(131)
ax.errorbar(
x=test_Y.numpy(), y=f3.numpy(), yerr = 2 * np.sqrt(var3.numpy()),
c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3
)
x0 = -2.5
x1 = 0.5
ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2)
ax.set_xlim([x0, x1])
ax.set_ylim([x0, x1])
ax.set_xlabel('True value', fontsize=9)
ax.set_ylabel('Model prediction', fontsize=9)
ax.set_title('ARD RBF', fontsize=9)
ax = fig.add_subplot(132)
ax.errorbar(
x=test_Y.numpy(), y=f2.numpy(), yerr = 2 * np.sqrt(var2.numpy()),
c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3
)
x0 = -2.5
x1 = 0.5
ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2)
ax.set_xlim([x0, x1])
ax.set_ylim([x0, x1])
ax.set_xlabel('True value', fontsize=9)
ax.set_title('Mahalanobis\npoint estimate', fontsize=9)
ax = fig.add_subplot(133)
ax.errorbar(
x=test_Y.numpy(), y=f1.numpy(), yerr = 2 * np.sqrt(var1.numpy()),
c='gray', lw=1, ls='', marker='.', mfc='k', mec='k', ms=3
)
x0 = -3.
x1 = 1
ax.plot([x0, x1], [x0, x1], '-', zorder=-5, alpha=0.5, c='steelblue', lw=2)
ax.set_xlim([x0, x1])
ax.set_ylim([x0, x1])
ax.set_title('Mahalanobis\nposterior sampled', fontsize=9)
ax.set_xticks([-3, -2, -1, 0, 1])
ax.set_xlabel('True value', fontsize=9)
plt.subplots_adjust(right=0.99, bottom=0.17, left=0.1, top=0.84, wspace=0.3)
plt.savefig('pdfs/model_predictions.pdf', pad_inches=0)
if __name__ == '__main__':
# Assumes fig_3 has already been run
make_fig_S2()
| alebo-main | figs/fig_S2.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
from fig_4 import *
def run_simulation():
t1 = time.time()
nsamp = 1000
res = {'unitsphere': {}}
for D in [50, 100, 200]:
for d in range(2, 19, 2):
for d_use in range(2, 21, 2):
if d_use < d:
continue
res['unitsphere'][(D, d, d_use)] = p_A_contains_optimizer(
d=d, D=D, d_use=d_use, gen_A_fn=gen_A_unitsphere, nsamp=nsamp
)
with open('data/figS6_sim_output.pckl', 'wb') as fout:
pickle.dump(res, fout)
print(time.time() - t1)
def make_fig_S6():
with open('data/figS6_sim_output.pckl', 'rb') as fin:
res = pickle.load(fin)
fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=4,figsize=(5.5, 2),
gridspec_kw={"width_ratios":[1, 1, 1, 0.15]})
axes = [ax1, ax2, ax3]
for i, D in enumerate([50, 100, 200]):
ds = []
duses = []
ps = []
for d in range(2, 19, 2):
for d_use in range(2, 21, 2):
if d_use < d:
continue
ds.append(d)
duses.append(d_use)
ps.append(res['unitsphere'][(D, d, d_use)])
cntr = axes[i].tricontourf(duses, ds, ps, levels=np.linspace(0, 1.001, 21), cmap='viridis')
axes[i].set_title(f'$D={D}$')
if i == 0:
axes[i].set_yticks([2, 6, 10, 14, 18])
axes[i].set_ylabel(r'True subspace dimension $d$', fontsize=9)
else:
axes[i].set_yticks([2, 6, 10, 14, 18])
axes[i].set_yticklabels([])
axes[i].grid(alpha=0.2, zorder=-2)
axes[i].set_xlabel(r'Embedding $d_e$')
axes[i].set_xticks([2, 6, 10, 14, 18])
ax4.patch.set_visible(False)
ax4.set_yticks([])
ax4.set_xticks([])
fig.colorbar(cntr, ax=ax4, ticks=[0, 0.25, 0.5, 0.75, 1.], fraction=1)
plt.subplots_adjust(right=0.97, bottom=0.2, left=0.07, top=0.89, wspace=0.1)
plt.savefig('pdfs/lp_solns_D.pdf', pad_inches=0)
if __name__ == '__main__':
#run_simulation() # This takes about 3hrs and produces data/figS6_sim_output.pckl
make_fig_S6()
| alebo-main | figs/fig_S6.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import json
import numpy as np
from ax.storage.json_store.decoder import object_from_json
from plot_config import *
def make_fig_S7():
# Load in the benchmark results
res = {}
for fname in [
'hartmann6_1000',
'branin_gramacy_100',
'hartmann6_100',
'hartmann6_random_subspace_1000',
]:
with open(f'../benchmarks/results/{fname}_aggregated_results.json', 'r') as fin:
res.update(object_from_json(json.load(fin)))
# A map from method idx in plot_method_names to the name used in res
method_idx_to_res_name = {
0: 'ALEBO',
1: 'REMBO',
2: 'HeSBO, d=d',
3: 'HeSBO, d=2d',
4: 'rrembos_standard_kPsi',
5: 'rrembos_reverse_kPsi',
6: 'ebo',
7: 'addgpucb',
8: 'smac',
9: 'cmaes',
10: 'turbo',
11: 'Sobol',
12: 'coordinatelinebo',
13: 'randomlinebo',
14: 'descentlinebo',
}
# Make the figure
fig = plt.figure(figsize=(5.5, 7.5))
####### Branin, D=100
ax1 = fig.add_subplot(511)
res_h = res['Branin, D=100']
for idx, m in enumerate(plot_method_names):
res_name = method_idx_to_res_name[idx]
if res_name not in res_h.objective_at_true_best:
continue # Not run on this problem
Y = np.log(res_h.objective_at_true_best[res_name] - 0.397887)
f = Y.mean(axis=0)
sem = Y.std(axis=0) / np.sqrt(Y.shape[0])
x = np.arange(1, 51)
color = plot_colors[m]
ax1.plot(x, f, color=color, label=m)
ax1.errorbar(x[4::5], f[4::5], yerr=2 * sem[4::5], color=color, alpha=0.5, ls='')
ax1.set_xlim([0, 51])
ax1.set_ylim([-6, 2])
ax1.set_ylabel('Log regret', fontsize=9)
ax1.grid(alpha=0.2, zorder=-10)
ax1.set_title(r'Branin, $d$=2, $D$=100')
####### Hartmann6, D=1000
ax2 = fig.add_subplot(512)
res_h = res['Hartmann6, D=1000']
for idx, m in enumerate(plot_method_names):
res_name = method_idx_to_res_name[idx]
if res_name not in res_h.objective_at_true_best:
continue # Not run on this problem
Y = np.log(res_h.objective_at_true_best[res_name] - (-3.32237))
f = Y.mean(axis=0)
sem = Y.std(axis=0) / np.sqrt(Y.shape[0])
x = np.arange(1, 201)
color = plot_colors[m]
ax2.plot(x, f, color=color, label=m)
ax2.errorbar(x[9::10], f[9::10], yerr=2 * sem[9::10], color=color, alpha=0.5, ls='')
ax2.set_xlim([0, 201])
ax2.set_ylim([-2.5, 1.7])
ax2.set_ylabel('Log regret', fontsize=9)
ax2.grid(alpha=0.2, zorder=-10)
ax2.set_title(r'Hartmann6, $d$=6, $D$=1000')
####### Gramacy, D=100
ax3 = fig.add_subplot(513)
res_h = res['Gramacy, D=100']
for idx, m in enumerate(plot_method_names):
res_name = method_idx_to_res_name[idx]
if res_name not in res_h.objective_at_true_best:
continue # Not run on this problem
Y = np.log(res_h.objective_at_true_best[res_name] - 0.5998)
f = Y.mean(axis=0)
sem = Y.std(axis=0) / np.sqrt(Y.shape[0])
x = np.arange(1, 51)
color = plot_colors[m]
ax3.plot(x, f, color=color, label=m)
ax3.errorbar(x[4::5], f[4::5], yerr=2 * sem[4::5], color=color, alpha=0.5, ls='')
ax3.set_xlim([0, 51])
ax3.set_ylabel('Log regret', fontsize=9)
ax3.grid(alpha=0.2, zorder=-10)
ax3.set_title(r'Gramacy, $d$=2, $D=100$')
####### Hartmann6, D=100
ax4 = fig.add_subplot(514)
res_h = res['Hartmann6, D=100']
for idx, m in enumerate(plot_method_names):
res_name = method_idx_to_res_name[idx]
if res_name not in res_h.objective_at_true_best:
continue # Not run on this problem
Y = np.log(res_h.objective_at_true_best[res_name] - (-3.32237))
f = Y.mean(axis=0)
sem = Y.std(axis=0) / np.sqrt(Y.shape[0])
x = np.arange(1, 201)
color = plot_colors[m]
ax4.plot(x, f, color=color, label=m)
ax4.errorbar(x[9::10], f[9::10], yerr=2 * sem[9::10], color=color, alpha=0.5, ls='')
ax4.set_xlim([0, 201])
ax4.set_ylim([-4, 1.7])
ax4.set_ylabel('Log regret', fontsize=9)
ax4.grid(alpha=0.2, zorder=-10)
ax4.set_title(r'Hartmann6, $d$=6, $D$=100')
# Add the legend
ax4.legend(bbox_to_anchor=(1.44, 5.405), fontsize=8)
####### Hartmann6 random subspace, D=1000
ax5 = fig.add_subplot(515)
res_h = res['Hartmann6 random subspace, D=1000']
for idx, m in enumerate(plot_method_names):
res_name = method_idx_to_res_name[idx]
if res_name not in res_h.objective_at_true_best:
continue # Not run on this problem
Y = np.log(res_h.objective_at_true_best[res_name] - (-3.32237))
f = Y.mean(axis=0)
sem = Y.std(axis=0) / np.sqrt(Y.shape[0])
x = np.arange(1, 201)
color = plot_colors[m]
ax5.plot(x, f, color=color, label=m)
ax5.errorbar(x[9::10], f[9::10], yerr=2 * sem[9::10], color=color, alpha=0.5, ls='')
ax5.set_xlim([0, 201])
ax5.set_ylim([-2.1, 1.7])
ax5.set_xlabel('Function evaluations', fontsize=9)
ax5.set_ylabel('Log regret', fontsize=9)
ax5.grid(alpha=0.2, zorder=-10)
ax5.set_title(r'Hartmann6, $d$=6 random subspace, $D$=1000')
plt.subplots_adjust(right=0.72, bottom=0.06, left=0.08, top=0.97, hspace=0.45)
plt.savefig('pdfs/log_regrets.pdf', pad_inches=0)
if __name__ == '__main__':
make_fig_S7()
| alebo-main | figs/fig_S7.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
from math import pi
from fig_3 import *
def compute_ll(f, var, test_Y):
return -0.5 * (torch.log(2 * pi * var) + ((test_Y - f) ** 2) / var).sum().item()
def run_simulation():
D = 100
d = 6
# Get projection
torch.manual_seed(10)
B0 = torch.randn(d, D, dtype=torch.double)
B = B0 / torch.sqrt((B0 ** 2).sum(dim=0))
# Get test data
_, _, _, test_X, test_Y, _, _ = gen_train_test_sets(B, ntrain=10, ntest=1000, seed_test=1000)
ns = np.array([40, 50, 75, 100, 125, 150, 175, 200])
nrep = 20
ll_alebo = np.zeros((nrep, len(ns)))
ll_ard = np.zeros((nrep, len(ns)))
for i in range(nrep):
for j, n in enumerate(ns):
# Generate training data
train_X, train_Y, train_Yvar, _, _, mu, sigma = gen_train_test_sets(
B, ntrain=n, ntest=10, seed_train=(i + 1) * len(ns) + j
)
# Predict with each model
f1, var1 = fit_and_predict_alebo(B, train_X, train_Y, train_Yvar, test_X, mu, sigma)
f3, var3 = fit_and_predict_ARDRBF(B, train_X, train_Y, train_Yvar, test_X, mu, sigma)
ll_alebo[i, j] = compute_ll(f1, var1, test_Y)
ll_ard[i, j] = compute_ll(f3, var3, test_Y)
# Save outcome
with open('data/figS3_sim_output.pckl', 'wb') as fout:
pickle.dump((ns, ll_alebo, ll_ard), fout)
def make_fig_S3():
with open('data/figS3_sim_output.pckl', 'rb') as fin:
(ns, ll_alebo, ll_ard) = pickle.load(fin)
ntest = 1000.
nrep = 20
fig = plt.figure(figsize=(3, 2))
ax = fig.add_subplot(111)
ax.errorbar(ns, ll_alebo.mean(axis=0) / ntest, yerr=2 * ll_alebo.std(axis=0)/ ntest / np.sqrt(nrep))
ax.errorbar(ns, ll_ard.mean(axis=0) / ntest, yerr=2 * ll_ard.std(axis=0)/ ntest / np.sqrt(nrep))
ax.grid(alpha=0.2)
ax.set_ylabel('Average test-set\nlog likelihood', fontsize=9)
ax.set_xlabel('Training set size', fontsize=9)
ax.legend(['Mahalanobis, sampled', 'ARD RBF'], fontsize=7, loc='lower right')
plt.subplots_adjust(right=0.995, bottom=0.19, left=0.21, top=0.98, wspace=0.3)
plt.savefig('pdfs/log_likelihood.pdf', pad_inches=0)
if __name__ == '__main__':
run_simulation() # Produces data/figS3_sim_output.pckl
make_fig_S3()
| alebo-main | figs/fig_S3.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Run NASBench benchmarks
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import json
import numpy as np
# This loads the nasbench dataset, which takes ~30s
from nasbench_evaluation import (
get_nasbench_ax_client,
evaluate_parameters,
NASBenchRunner,
)
from ax.modelbridge.registry import Models
from ax.modelbridge.generation_strategy import GenerationStep, GenerationStrategy
from ax.modelbridge.strategies.alebo import ALEBOStrategy
from ax.modelbridge.strategies.rembo import HeSBOStrategy, REMBOStrategy
from ax.storage.json_store.encoder import object_to_json
from ax.core.data import Data
import turbo
import cma
def run_nasbench_benchmarks_ax(rep):
"""
Runs the Ax methods on the nasbench benchmark
(Sobol, ALEBO, HeSBO, REMBO)
"""
gs_list = [
GenerationStrategy(name="Sobol", steps=[GenerationStep(model=Models.SOBOL, num_trials=-1)]),
ALEBOStrategy(D=36, d=12, init_size=10),
HeSBOStrategy(D=36, d=12, init_per_proj=10),
REMBOStrategy(D=36, d=12, init_per_proj=4),
]
for gs in gs_list:
try:
axc = get_nasbench_ax_client(gs)
for i in range(50):
param_dict_i, trial_index = axc.get_next_trial()
raw_data = evaluate_parameters(param_dict_i)
axc.complete_trial(trial_index=trial_index, raw_data=raw_data)
with open(f'results/nasbench_{gs.name}_rep_{rep}.json', 'w') as fout:
json.dump(object_to_json(axc.experiment), fout)
except Exception:
pass
return
def run_nasbench_benchmarks_turbo(rep):
r = NASBenchRunner(max_eval=50)
turbo1 = turbo.Turbo1(
f=r.f,
lb=np.zeros(36),
ub=np.ones(36),
n_init=10,
max_evals=50,
batch_size=1,
)
turbo1.optimize()
with open(f'results/nasbench_turbo_rep_{rep}.json', "w") as fout:
json.dump((r.fs, r.feas), fout)
def run_nasbench_benchmarks_cmaes(rep):
r = NASBenchRunner(max_eval=50)
try:
cma.fmin(
objective_function=r.f,
x0=[0.5] * 36,
sigma0=0.25,
options={
'bounds': [[0.0] * 36, [1.0] * 36],
'maxfevals': 50,
},
)
except ValueError:
pass # CMA-ES doesn't always terminate at exactly maxfevals
with open(f'results/nasbench_cmaes_rep_{rep}.json', "w") as fout:
json.dump((r.fs, r.feas), fout)
if __name__ == '__main__':
for rep in range(100):
run_nasbench_benchmarks_cmaes(rep)
run_nasbench_benchmarks_turbo(rep)
run_nasbench_benchmarks_notbatch(rep)
| alebo-main | benchmarks/run_nasbench.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
from typing import Any, Callable, Dict, List, MutableMapping, Optional, Tuple, Union
from ax.models.torch.botorch_defaults import get_and_fit_model
from ax.modelbridge.strategies.alebo import ALEBOStrategy, get_ALEBOInitializer
import torch
from torch import Tensor
from ax.core.data import Data
from ax.core.experiment import Experiment
from ax.core.search_space import SearchSpace
from ax.modelbridge.factory import DEFAULT_TORCH_DEVICE
from ax.modelbridge.generation_strategy import GenerationStep, GenerationStrategy
from ax.modelbridge.random import RandomModelBridge
from ax.modelbridge.torch import TorchModelBridge
from ax.modelbridge.transforms.centered_unit_x import CenteredUnitX
from ax.modelbridge.transforms.standardize_y import StandardizeY
from botorch.models.gpytorch import GPyTorchModel
from ax.models.torch.alebo import ALEBO
class ALEBO_kernel_ablation(ALEBO):
def get_and_fit_model(
self,
Xs: List[Tensor],
Ys: List[Tensor],
Yvars: List[Tensor],
state_dicts: Optional[List[MutableMapping[str, Tensor]]] = None,
) -> GPyTorchModel:
return get_and_fit_model(
Xs=Xs,
Ys=Ys,
Yvars=Yvars,
task_features=[],
fidelity_features=[],
metric_names=[],
state_dict=None,
)
def get_ALEBO_kernel_ablation(
experiment: Experiment,
search_space: SearchSpace,
data: Data,
B: torch.Tensor,
**model_kwargs: Any,
) -> TorchModelBridge:
if search_space is None:
search_space = experiment.search_space
return TorchModelBridge(
experiment=experiment,
search_space=search_space,
data=data,
model=ALEBO_kernel_ablation(B=B, **model_kwargs),
transforms=[CenteredUnitX, StandardizeY],
torch_dtype=B.dtype,
torch_device=B.device,
)
class ALEBOStrategy_kernel_ablation(GenerationStrategy):
def __init__(
self,
D: int,
d: int,
init_size: int,
name: str = "ALEBO",
dtype: torch.dtype = torch.double,
device: torch.device = DEFAULT_TORCH_DEVICE,
random_kwargs: Optional[Dict[str, Any]] = None,
gp_kwargs: Optional[Dict[str, Any]] = None,
gp_gen_kwargs: Optional[Dict[str, Any]] = None,
) -> None:
self.D = D
self.d = d
self.init_size = init_size
self.dtype = dtype
self.device = device
self.random_kwargs = random_kwargs if random_kwargs is not None else {}
self.gp_kwargs = gp_kwargs if gp_kwargs is not None else {}
self.gp_gen_kwargs = gp_gen_kwargs
B = self.gen_projection(d=d, D=D, device=device, dtype=dtype)
self.gp_kwargs.update({"B": B})
self.random_kwargs.update({"B": B.cpu().numpy()})
steps = [
GenerationStep(
model=get_ALEBOInitializer,
num_arms=init_size,
model_kwargs=self.random_kwargs,
),
GenerationStep(
model=get_ALEBO_kernel_ablation,
num_arms=-1,
model_kwargs=self.gp_kwargs,
model_gen_kwargs=gp_gen_kwargs,
),
]
super().__init__(steps=steps, name=name)
def clone_reset(self) -> "ALEBOStrategy":
"""Copy without state."""
return self.__class__(
D=self.D,
d=self.d,
init_size=self.init_size,
name=self.name,
dtype=self.dtype,
device=self.device,
random_kwargs=self.random_kwargs,
gp_kwargs=self.gp_kwargs,
gp_gen_kwargs=self.gp_gen_kwargs,
)
def gen_projection(
self, d: int, D: int, dtype: torch.dtype, device: torch.device
) -> torch.Tensor:
"""Generate the projection matrix B as a (d x D) tensor
"""
B0 = torch.randn(d, D, dtype=dtype, device=device)
B = B0 / torch.sqrt((B0 ** 2).sum(dim=0))
return B
class ALEBOStrategy_projection_ablation(ALEBOStrategy):
def gen_projection(
self, d: int, D: int, dtype: torch.dtype, device: torch.device
) -> torch.Tensor:
B0 = torch.randn(d, D, dtype=dtype, device=device)
return B0
| alebo-main | benchmarks/ablation_models.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Run benchmarks for CMAES.
Requires installing cma from pip. The experiments here used version 2.7.0.
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import json
from benchmark_problems import (
branin_100,
hartmann6_100,
hartmann6_1000,
hartmann6_random_subspace_1000,
)
from ax.benchmark.benchmark import benchmark_minimize_callable
from ax.storage.json_store.encoder import object_to_json
import cma # cma==2.7.0
def run_hartmann6_benchmarks(D, rep, random_subspace=False):
if D == 100:
problem = hartmann6_100
elif D == 1000 and not random_subspace:
problem = hartmann6_1000
elif D == 1000 and random_subspace:
problem = hartmann6_random_subspace_1000
experiment, f = benchmark_minimize_callable(
problem=problem,
num_trials=200,
method_name='cmaes',
replication_index=rep,
)
try:
cma.fmin(
objective_function=f,
x0=[0.5] * D,
sigma0=0.25,
options={'bounds': [[0] * D, [1] * D], 'maxfevals': 200},
)
except ValueError:
pass # CMA-ES doesn't always terminate at exactly maxfevals
rs_str = 'random_subspace_' if random_subspace else ''
with open(f'results/hartmann6_{rs_str}{D}_cmaes_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
def run_branin_benchmarks(rep):
experiment, f = benchmark_minimize_callable(
problem=branin_100,
num_trials=50,
method_name='cmaes',
replication_index=rep,
)
try:
cma.fmin(
objective_function=f,
x0=[2.5] * 50 + [7.5] * 50,
sigma0=3.75,
options={
'bounds': [[-5] * 50 + [0] * 50, [10] * 50 + [15] * 50],
'maxfevals': 50,
},
)
except ValueError:
pass # CMA-ES doesn't always terminate at exactly maxfevals
with open(f'results/branin_100_cmaes_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
if __name__ == '__main__':
# Run all of the CMAES experiments.
# These can be distributed.
for i in range(50):
# Hartmann6, D=100: Each rep takes ~5 s
run_hartmann6_benchmarks(D=100, rep=i)
# Hartmann6, D=1000: Each rep takes ~10 s
run_hartmann6_benchmarks(D=1000, rep=i)
# Branin, D=100: Each rep takes ~1 s
run_branin_benchmarks(rep=i)
# Hartmann6 random subspace, D=1000
run_hartmann6_benchmarks(D=1000, rep=i, random_subspace=True)
| alebo-main | benchmarks/run_cmaes_benchmarks.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Run benchmarks for SMAC.
Requires installing smac from pip. The experiments here used version 2.7.0.
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import json
import numpy as np
from benchmark_problems import (
branin_100,
hartmann6_100,
hartmann6_1000,
hartmann6_random_subspace_1000,
)
from ax.benchmark.benchmark import benchmark_minimize_callable
from ax.storage.json_store.encoder import object_to_json
from smac.facade.smac_hpo_facade import SMAC4HPO
from smac.scenario.scenario import Scenario
from smac.configspace import ConfigurationSpace
from smac.runhistory.runhistory import RunKey
from smac.initial_design.random_configuration_design import RandomConfigurations
from smac.tae.execute_func import ExecuteTAFuncArray
from ConfigSpace.hyperparameters import UniformFloatHyperparameter
def fmin_smac_nopynisher(func, x0, bounds, maxfun, rng):
"""
Minimize a function using SMAC, but without pynisher, which doesn't work
well with benchmark_minimize_callable.
This function is based on SMAC's fmin_smac.
"""
cs = ConfigurationSpace()
tmplt = 'x{0:0' + str(len(str(len(bounds)))) + 'd}'
for idx, (lower_bound, upper_bound) in enumerate(bounds):
parameter = UniformFloatHyperparameter(
name=tmplt.format(idx + 1),
lower=lower_bound,
upper=upper_bound,
default_value=x0[idx],
)
cs.add_hyperparameter(parameter)
scenario_dict = {
"run_obj": "quality",
"cs": cs,
"deterministic": "true",
"initial_incumbent": "DEFAULT",
"runcount_limit": maxfun,
}
scenario = Scenario(scenario_dict)
def call_ta(config):
x = np.array([val for _, val in sorted(config.get_dictionary().items())],
dtype=np.float)
return func(x)
smac = SMAC4HPO(
scenario=scenario,
tae_runner=ExecuteTAFuncArray,
tae_runner_kwargs={'ta': call_ta, 'use_pynisher': False},
rng=rng,
initial_design=RandomConfigurations,
)
smac.optimize()
return
def run_hartmann6_benchmarks(D, rep, random_subspace=False):
if D == 100:
problem = hartmann6_100
elif D == 1000 and not random_subspace:
problem = hartmann6_1000
elif D == 1000 and random_subspace:
problem = hartmann6_random_subspace_1000
experiment, f = benchmark_minimize_callable(
problem=problem,
num_trials=200,
method_name='smac',
replication_index=rep,
)
fmin_smac_nopynisher(
func=f,
x0=[0.5] * D,
bounds=[[0, 1]] * D,
maxfun=200,
rng=rep + 1,
)
rs_str = 'random_subspace_' if random_subspace else ''
with open(f'results/hartmann6_{rs_str}{D}_smac_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
def run_branin_benchmarks(rep):
experiment, f = benchmark_minimize_callable(
problem=branin_100,
num_trials=50,
method_name='smac',
replication_index=rep,
)
fmin_smac_nopynisher(
func=f,
x0=[2.5] * 50 + [7.5] * 50,
bounds=[[-5, 10]] * 50 + [[0, 15]] * 50,
maxfun=50,
rng=rep + 1,
)
with open(f'results/branin_100_smac_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
if __name__ == '__main__':
# Run all of the SMAC experiments.
# These can be distributed.
for i in range(50):
# Hartmann6, D=100: Each rep takes ~1.5 hours
run_hartmann6_benchmarks(D=100, rep=i)
# Branin, D=100: Each rep takes ~20 mins
run_branin_benchmarks(rep=i)
# Hartmann6, D=1000: Each rep takes ~36 hours
for i in range(10):
run_hartmann6_benchmarks(D=1000, rep=i)
# Hartmann6 random subspace, D=1000
run_hartmann6_benchmarks(D=1000, rep=i, random_subspace=True)
| alebo-main | benchmarks/run_smac_benchmarks.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Run benchmarks for TuRBO.
Requires installing turbo from https://github.com/uber-research/TuRBO.
The experiments here used version 0.0.1 (commit 8461f9c).
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import json
import numpy as np
from benchmark_problems import (
branin_100,
hartmann6_100,
hartmann6_1000,
hartmann6_random_subspace_1000,
)
from ax.benchmark.benchmark import benchmark_minimize_callable
from ax.storage.json_store.encoder import object_to_json
import turbo
def run_hartmann6_benchmarks(D, rep, random_subspace=False):
if D == 100:
problem = hartmann6_100
elif D == 1000 and not random_subspace:
problem = hartmann6_1000
elif D == 1000 and random_subspace:
problem = hartmann6_random_subspace_1000
experiment, f = benchmark_minimize_callable(
problem=problem,
num_trials=200,
method_name='turbo',
replication_index=rep,
)
turbo1 = turbo.Turbo1(
f=f,
lb=np.zeros(D),
ub=np.ones(D),
n_init=10,
max_evals=200,
)
turbo1.optimize()
rs_str = 'random_subspace_' if random_subspace else ''
with open(f'results/hartmann6_{rs_str}{D}_turbo_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
def run_branin_benchmarks(rep):
experiment, f = benchmark_minimize_callable(
problem=branin_100,
num_trials=50,
method_name='turbo',
replication_index=rep,
)
turbo1 = turbo.Turbo1(
f=f,
lb=np.hstack((-5 * np.ones(50), np.zeros(50))),
ub=np.hstack((10 * np.ones(50), 15 * np.ones(50))),
n_init=10,
max_evals=50,
)
turbo1.optimize()
with open(f'results/branin_100_turbo_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
if __name__ == '__main__':
# Run all of the TuRBO experiments.
# These can be distributed.
for i in range(50):
# Hartmann6, D=100: Each rep takes ~15 mins
run_hartmann6_benchmarks(D=100, rep=i)
# Hartmann6, D=1000: Each rep takes ~30 mins
run_hartmann6_benchmarks(D=1000, rep=i)
# Branin, D=100: Each rep takes ~5 mins
run_branin_benchmarks(rep=i)
# Hartmann6 random subspace, D=1000
run_hartmann6_benchmarks(D=1000, rep=i, random_subspace=True)
| alebo-main | benchmarks/run_turbo_benchmarks.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Compile all of the benchmark results from the different methods (potentially
run in a distributed fashion) into a single BenchmarkResult object.
All of the benchmark runs should be completed before running this.
"""
import gc
import json
import numpy as np
from benchmark_problems import (
branin_100,
branin_by_D,
gramacy_100,
hartmann6_100,
hartmann6_1000,
hartmann6_random_subspace_1000,
)
from ax.benchmark.benchmark_result import aggregate_problem_results
from ax.storage.json_store.encoder import object_to_json
from ax.storage.json_store.decoder import object_from_json
def merge_benchmark_results(res1, res2):
"""
Merges two benchmark results dictionaries in-place (res2 into res1)
"""
for problem_name in res2:
for method_name in res2[problem_name]:
for exp in res2[problem_name][method_name]:
res1 = add_exp(
res=res1,
exp=exp,
problem_name=problem_name,
method_name=method_name,
)
return res1
def add_exp(res, exp, problem_name, method_name):
"""
Add benchmark experiment exp to results dict res, under the specified
problem_name and method_name.
"""
if problem_name not in res:
res[problem_name] = {}
if method_name not in res[problem_name]:
res[problem_name][method_name] = []
res[problem_name][method_name].append(exp)
return res
def compile_hartmann6(D, random_subspace=False):
if D == 100:
problem = hartmann6_100
other_methods = ['addgpucb', 'cmaes', 'ebo', 'smac', 'turbo']
rls = ['rrembos_standard_kPsi', 'rrembos_reverse_kPsi', 'coordinatelinebo', 'descentlinebo', 'randomlinebo']
rs_str = ''
elif D == 1000 and not random_subspace:
problem = hartmann6_1000
other_methods = ['cmaes', 'smac', 'turbo']
rls = ['rrembos_standard_kPsi']
rs_str = ''
elif D == 1000 and random_subspace:
problem = hartmann6_random_subspace_1000
other_methods = ['cmaes', 'smac', 'turbo']
rls = []
rs_str = 'random_subspace_'
all_results = {}
for rep in range(50):
with open(f'results/hartmann6_{rs_str}{D}_alebo_rembo_hesbo_sobol_rep_{rep}.json', 'r') as fin:
res_i = object_from_json(json.load(fin))
all_results = merge_benchmark_results(all_results, res_i)
for method_name in other_methods:
if D==1000 and method_name == 'smac' and rep > 9:
# SMAC D=1000 only run for 10 reps
continue
with open(f'results/hartmann6_{rs_str}{D}_{method_name}_rep_{rep}.json', 'r') as fin:
exp_i = object_from_json(json.load(fin))
all_results = add_exp(res=all_results, exp=exp_i, problem_name=problem.name, method_name=method_name)
res = aggregate_problem_results(runs=all_results[problem.name], problem=problem)
# Add in RRembo and LineBOresults
for method in rls:
with open(f'results/hartmann6_{D}_{method}.json', 'r') as fin:
A = json.load(fin)
res.objective_at_true_best[method] = np.minimum.accumulate(np.array(A), axis=1)
# Save
with open(f'results/hartmann6_{rs_str}{D}_aggregated_results.json', "w") as fout:
json.dump(object_to_json({problem.name: res}), fout)
def compile_branin_gramacy_100():
all_results = {}
for rep in range(50):
with open(f'results/branin_gramacy_100_alebo_rembo_hesbo_sobol_rep_{rep}.json', 'r') as fin:
res_i = object_from_json(json.load(fin))
all_results = merge_benchmark_results(all_results, res_i)
for method_name in ['addgpucb', 'cmaes', 'ebo', 'smac', 'turbo']:
with open(f'results/branin_100_{method_name}_rep_{rep}.json', 'r') as fin:
exp_i = object_from_json(json.load(fin))
all_results = add_exp(
res=all_results,
exp=exp_i,
problem_name='Branin, D=100',
method_name=method_name,
)
res = {
p.name: aggregate_problem_results(runs=all_results[p.name], problem=p)
for p in [branin_100, gramacy_100]
}
# Add in RRembo results
for proj in ['standard', 'reverse']:
method = f'rrembos_{proj}_kPsi'
with open(f'results/branin_100_{method}.json', 'r') as fin:
A = json.load(fin)
res['Branin, D=100'].objective_at_true_best[method] = np.minimum.accumulate(np.array(A), axis=1)
# Save
with open(f'results/branin_gramacy_100_aggregated_results.json', "w") as fout:
json.dump(object_to_json(res), fout)
def compile_sensitivity_benchmarks():
all_results = {}
for rep in range(50):
## Sensitivity to D
with open(f'results/sensitivity_D_rep_{rep}.json', 'r') as fin:
results_dict = json.load(fin)
for D, obj in results_dict.items():
res_i = object_from_json(obj)
all_results = merge_benchmark_results(all_results, res_i)
## Sensitivity to d_e
with open(f'results/sensitivity_d_e_rep_{rep}.json', 'r') as fin:
res_i = object_from_json(json.load(fin))
all_results = merge_benchmark_results(all_results, res_i)
all_problems = (
[hartmann6_100, hartmann6_1000, branin_100, gramacy_100]
+ list(branin_by_D.values())
)
problems = [branin_100] + list(branin_by_D.values())
res = {
p.name+'_sensitivity': aggregate_problem_results(runs=all_results[p.name], problem=p)
for p in problems
}
# Save
with open(f'results/sensitivity_aggregated_results.json', "w") as fout:
json.dump(object_to_json(res), fout)
def compile_ablation_benchmarks():
all_results = {}
for rep in range(100):
with open(f'results/ablation_rep_{rep}.json', 'r') as fin:
res_i = object_from_json(json.load(fin))
all_results = merge_benchmark_results(all_results, res_i)
problems = [branin_100]
res = {
p.name+'_ablation': aggregate_problem_results(runs=all_results[p.name], problem=p)
for p in problems
}
# Save
with open(f'results/ablation_aggregated_results.json', "w") as fout:
json.dump(object_to_json(res), fout)
def compile_nasbench():
all_res = {}
# TuRBO and CMAES
for method in ['turbo', 'cmaes']:
all_res[method] = []
for rep in range(100):
with open(f'results/nasbench_{method}_rep_{rep}.json', 'r') as fin:
fs, feas = json.load(fin)
# Set infeasible points to nan
fs = np.array(fs)
fs[~np.array(feas)] = np.nan
all_res[method].append(fs)
# Ax methods
for method in ['Sobol', 'ALEBO', 'HeSBO', 'REMBO']:
all_res[method] = []
for rep in range(100):
with open(f'results/nasbench_{method}_rep_{rep}.json', 'r') as fin:
exp = object_from_json(json.load(fin))
# Pull out results and set infeasible points to nan
df = exp.fetch_data().df.sort_values(by='arm_name')
df_obj = df[df['metric_name'] == 'final_test_accuracy'].copy().reset_index(drop=True)
df_con = df[df['metric_name'] == 'final_training_time'].copy().reset_index(drop=True)
infeas = df_con['mean'] > 1800
df_obj.loc[infeas, 'mean'] = np.nan
all_res[method].append(df_obj['mean'].values)
for method, arr in all_res.items():
all_res[method] = np.fmax.accumulate(np.vstack(all_res[method]), axis=1)
with open(f'results/nasbench_aggregated_results.json', "w") as fout:
json.dump(object_to_json(all_res), fout)
if __name__ == '__main__':
compile_nasbench()
gc.collect()
compile_hartmann6(D=100)
gc.collect()
compile_hartmann6(D=1000)
gc.collect()
compile_branin_gramacy_100()
gc.collect()
compile_sensitivity_benchmarks()
gc.collect()
compile_hartmann6(D=1000, random_subspace=True)
gc.collect()
compile_ablation_benchmarks()
| alebo-main | benchmarks/compile_benchmark_results.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
import json
import numpy as np
from scipy.stats import special_ortho_group
from typing import List, Optional
from ax.benchmark.benchmark_problem import BenchmarkProblem
from ax.core.objective import Objective
from ax.core.optimization_config import OptimizationConfig
from ax.core.outcome_constraint import ComparisonOp, OutcomeConstraint
from ax.core.parameter import ParameterType, RangeParameter
from ax.core.search_space import SearchSpace
from ax.metrics.branin import BraninMetric
from ax.metrics.hartmann6 import Hartmann6Metric
from ax.metrics.noisy_function import NoisyFunctionMetric
from ax.storage.metric_registry import register_metric
from ax.utils.measurement.synthetic_functions import hartmann6
### Hartmann6 problem, D=100 and D=1000
# Relevant parameters were chosen randomly using
# x = np.arange(100)
# np.random.seed(10)
# np.random.shuffle(x)
# print(x[:6]) # [19 14 43 37 66 3]
hartmann6_100 = BenchmarkProblem(
name="Hartmann6, D=100",
optimal_value=-3.32237,
optimization_config=OptimizationConfig(
objective=Objective(
metric=Hartmann6Metric(
name="objective",
param_names=["x19", "x14", "x43", "x37", "x66", "x3"],
noise_sd=0.0,
),
minimize=True,
)
),
search_space=SearchSpace(
parameters=[
RangeParameter(
name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=0.0, upper=1.0
)
for i in range(100)
]
),
)
hartmann6_1000 = BenchmarkProblem(
name="Hartmann6, D=1000",
optimal_value=-3.32237,
optimization_config=OptimizationConfig(
objective=Objective(
metric=Hartmann6Metric(
name="objective",
param_names=["x190", "x140", "x430", "x370", "x660", "x30"],
noise_sd=0.0,
),
minimize=True,
)
),
search_space=SearchSpace(
parameters=[
RangeParameter(
name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=0.0, upper=1.0
)
for i in range(1000)
]
),
)
### Branin problem, D=100 and sensitivity analysis
# Original x1 and x2 have different bounds, so we create blocks of 50 for each
# with each of the bounds and set the relevant parameters in those blocks.
branin_100 = BenchmarkProblem(
name="Branin, D=100",
optimal_value=0.397887,
optimization_config=OptimizationConfig(
objective=Objective(
metric=BraninMetric(
name="objective", param_names=["x19", "x64"], noise_sd=0.0
),
minimize=True,
)
),
search_space=SearchSpace(
parameters=[ # pyre-ignore
RangeParameter(
name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=-5.0, upper=10.0
)
for i in range(50)
]
+ [
RangeParameter(
name=f"x{i + 50}",
parameter_type=ParameterType.FLOAT,
lower=0.0,
upper=15.0,
)
for i in range(50)
]
),
)
# Additional dimensionalities for the sensitivity analysis to D.
# Random embedding methods are invariant to the ordering of relevant/irrelevant
# parameters, and also to the bounds on the irrelevant parameters. So since
# these problems are being used only for ALEBO, we can simplify their
# definition and take x0 and x1 as the relevant.
base_branin_parameters = [
RangeParameter(
name="x0", parameter_type=ParameterType.FLOAT, lower=-5.0, upper=10.0
),
RangeParameter(
name="x1", parameter_type=ParameterType.FLOAT, lower=0.0, upper=15.0
),
]
branin_by_D = {
D: BenchmarkProblem(
name="Branin, D=" + str(D),
optimal_value=0.397887,
optimization_config=OptimizationConfig(
objective=Objective(
metric=BraninMetric(
name="objective", param_names=["x0", "x1"], noise_sd=0.0
),
minimize=True,
)
),
search_space=SearchSpace(
parameters=base_branin_parameters # pyre-ignore
+ [
RangeParameter(
name=f"x{i}",
parameter_type=ParameterType.FLOAT,
lower=0.0,
upper=1.0,
)
for i in range(2, D)
]
),
)
for D in [50, 200, 500, 1000]
}
### Gramacy problem, D=100
class GramacyObjective(NoisyFunctionMetric):
def f(self, x: np.ndarray) -> float:
return x.sum()
class GramacyConstraint1(NoisyFunctionMetric):
def f(self, x: np.ndarray) -> float:
return 1.5 - x[0] - 2 * x[1] - 0.5 * np.sin(2 * np.pi * (x[0] ** 2 - 2 * x[1]))
class GramacyConstraint2(NoisyFunctionMetric):
def f(self, x: np.ndarray) -> float:
return x[0] ** 2 + x[1] ** 2 - 1.5
# Register these metrics so they can be serialized to json
register_metric(metric_cls=GramacyObjective, val=101)
register_metric(metric_cls=GramacyConstraint1, val=102)
register_metric(metric_cls=GramacyConstraint2, val=103)
gramacy_100 = BenchmarkProblem(
name="Gramacy, D=100",
optimal_value=0.5998,
optimization_config=OptimizationConfig(
objective=Objective(
metric=GramacyObjective(
name="objective", param_names=["x19", "x64"], noise_sd=0.0
),
minimize=True,
),
outcome_constraints=[
OutcomeConstraint(
metric=GramacyConstraint1(
name="constraint1", param_names=["x19", "x64"], noise_sd=0.0
),
op=ComparisonOp.LEQ,
bound=0.0,
relative=False,
),
OutcomeConstraint(
metric=GramacyConstraint2(
name="constraint2", param_names=["x19", "x64"], noise_sd=0.0
),
op=ComparisonOp.LEQ,
bound=0.0,
relative=False,
),
],
),
search_space=SearchSpace(
parameters=[
RangeParameter(
name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=0.0, upper=1.0
)
for i in range(100)
]
),
)
### Hartmann6 D=1000 with random subspace
class Hartmann6RandomSubspace1000Metric(NoisyFunctionMetric):
def __init__(
self,
name: str,
param_names: List[str],
noise_sd: float = 0.0,
lower_is_better: Optional[bool] = None,
) -> None:
super().__init__(
name=name,
param_names=param_names,
noise_sd=noise_sd,
lower_is_better=lower_is_better,
)
# Set the random basis
try:
with open('data/random_subspace_1000x6.json', 'r') as fin:
self.random_basis = np.array(json.load(fin))
except IOError:
np.random.seed(1000)
self.random_basis = special_ortho_group.rvs(1000)[:6, :]
with open('data/random_subspace_1000x6.json', 'w') as fout:
json.dump(self.random_basis.tolist(), fout)
def f(self, x: np.ndarray) -> float:
# Project down to the true subspace
z = self.random_basis @ x
# x \in [-1, 1], so adjust z to be closer to [0, 1], and evaluate
return hartmann6((z + 1) / 2.)
register_metric(metric_cls=Hartmann6RandomSubspace1000Metric, val=104)
hartmann6_random_subspace_1000 = BenchmarkProblem(
name="Hartmann6 random subspace, D=1000",
optimal_value=-3.32237,
optimization_config=OptimizationConfig(
objective=Objective(
metric=Hartmann6RandomSubspace1000Metric(
name="objective",
param_names=[f"x{i}" for i in range(1000)],
noise_sd=0.0,
),
minimize=True,
)
),
search_space=SearchSpace(
parameters=[
RangeParameter(
name=f"x{i}", parameter_type=ParameterType.FLOAT, lower=-1.0, upper=1.0
)
for i in range(1000)
]
),
)
| alebo-main | benchmarks/benchmark_problems.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Run benchmarks for Add-GP-UCB.
Requires installing dragonfly-opt from pip. The experiments here used version
0.1.4.
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
from argparse import Namespace
import json
from benchmark_problems import (
branin_100,
hartmann6_100,
hartmann6_1000,
)
from ax.benchmark.benchmark import benchmark_minimize_callable
from ax.storage.json_store.encoder import object_to_json
from dragonfly import minimise_function # dragonfly-opt==0.1.4
def run_hartmann6_benchmarks(D, rep):
if D == 100:
problem = hartmann6_100
elif D == 1000:
problem = hartmann6_1000
experiment, f = benchmark_minimize_callable(
problem=problem,
num_trials=200,
method_name='add_gp_ucb',
replication_index=rep,
)
options = Namespace(acq="add_ucb")
res = minimise_function(f, domain=[[0, 1]] * D, max_capital=199, options=options)
with open(f'results/hartmann6_{D}_addgpucb_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
def run_branin_benchmarks(rep):
experiment, f = benchmark_minimize_callable(
problem=branin_100,
num_trials=50,
method_name='add_gp_ucb',
replication_index=rep,
)
options = Namespace(acq="add_ucb")
res = minimise_function(
f,
domain=[[-5, 10]] * 50 + [[0, 15]] * 50,
max_capital=49,
options=options,
)
with open(f'results/branin_100_addgpucb_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
if __name__ == '__main__':
# Run all of the Add-GP-UCB benchmarks using Dragonfly.
# These can be distributed.
for i in range(50):
run_hartmann6_benchmarks(D=100, rep=i)
## Hartmann6, D=1000: Too slow, not run
#run_hartmann6_benchmarks(D=1000, rep=i)
# Branin, D=100: Each rep takes ~3 hours
run_branin_benchmarks(rep=i)
| alebo-main | benchmarks/run_addgpucb_benchmarks.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Run benchmarks for LineBO on the Hartmann6 100 problem.
These benchmarks are run using the benchmarking suite contained in the LineBO
codebase. The code here loads in those results and extracts just the function
evaluations, which are then stored in json. There are several steps that must
be done before this script can be run.
1) Clone and install the LineBO software from https://github.com/jkirschner42/LineBO
2) copy data/hartmann6_100.yaml from here into the LineBO/config/ directory.
This problem configuration is based on LineBO/config/hartmann6_sub14.yaml.
3) Run the experiments by executing:
febo create hartmann6_100 --config config/hartmann6_100.yaml
febo run hartmann6_100
4) Copy LineBO/runs/hartmann6_100/data/evaluations.hdf5 into results/
"""
import numpy as np
import h5py
import json
f = h5py.File('results/evaluations.hdf5', 'r')
methods = ['RandomLineBO', 'CoordinateLineBO', 'DescentLineBO', 'Random', 'CMA-ES']
ys = {}
for i, m in enumerate(methods):
ys[m] = np.zeros((50, 200))
for rep in range(50):
ys[m][rep, :] = f[str(i)][str(rep)]['y_exact'] * -3.32237
with open('results/hartmann6_100_randomlinebo.json', 'w') as fout:
json.dump(ys['RandomLineBO'].tolist(), fout)
with open('results/hartmann6_100_coordinatelinebo.json', 'w') as fout:
json.dump(ys['CoordinateLineBO'].tolist(), fout)
with open('results/hartmann6_100_descentlinebo.json', 'w') as fout:
json.dump(ys['DescentLineBO'].tolist(), fout)
| alebo-main | benchmarks/run_linebo_benchmarks.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Run benchmarks for: ALEBO, REMBO, HeSBO, and Sobol.
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import json
from benchmark_problems import (
branin_100,
branin_by_D,
gramacy_100,
hartmann6_100,
hartmann6_1000,
hartmann6_random_subspace_1000,
)
from ablation_models import (
ALEBOStrategy_projection_ablation,
ALEBOStrategy_kernel_ablation,
)
from ax.benchmark.benchmark import full_benchmark_run
from ax.benchmark.benchmark_result import aggregate_problem_results
from ax.modelbridge.registry import Models
from ax.modelbridge.generation_strategy import GenerationStep, GenerationStrategy
from ax.modelbridge.strategies.alebo import ALEBOStrategy
from ax.modelbridge.strategies.rembo import HeSBOStrategy, REMBOStrategy
from ax.storage.json_store.encoder import object_to_json
def run_hartmann6_benchmarks(D, rep, random_subspace=False):
if D == 100:
problem = hartmann6_100
elif D == 1000 and not random_subspace:
problem = hartmann6_1000
elif D == 1000 and random_subspace:
problem = hartmann6_random_subspace_1000
strategy0 = GenerationStrategy(
name="Sobol",
steps=[
GenerationStep(
model=Models.SOBOL, num_arms=-1, model_kwargs={'seed': rep + 1}
)
],
)
strategy1 = ALEBOStrategy(D=D, d=12, init_size=10)
strategy2 = REMBOStrategy(D=D, d=6, init_per_proj=2)
strategy3 = HeSBOStrategy(D=D, d=6, init_per_proj=10, name=f"HeSBO, d=d")
strategy4 = HeSBOStrategy(D=D, d=12, init_per_proj=10, name=f"HeSBO, d=2d")
all_benchmarks = full_benchmark_run(
num_replications=1, # Running them 1 at a time for distributed
num_trials=200,
batch_size=1,
methods=[strategy0, strategy1, strategy2, strategy3, strategy4],
problems=[problem],
)
rs_str = 'random_subspace_' if random_subspace else ''
with open(
f'results/hartmann6_{rs_str}{D}_alebo_rembo_hesbo_sobol_rep_{rep}.json', "w"
) as fout:
json.dump(object_to_json(all_benchmarks), fout)
def run_branin_and_gramacy_100_benchmarks(rep):
strategy0 = GenerationStrategy(
name="Sobol",
steps=[
GenerationStep(
model=Models.SOBOL, num_arms=-1, model_kwargs={'seed': rep + 1}
)
],
)
strategy1 = ALEBOStrategy(D=100, d=4, init_size=10)
strategy2 = REMBOStrategy(D=100, d=2, init_per_proj=2)
strategy3 = HeSBOStrategy(D=100, d=4, init_per_proj=10, name=f"HeSBO, d=2d")
all_benchmarks = full_benchmark_run(
num_replications=1,
num_trials=50,
batch_size=1,
methods=[strategy0, strategy1, strategy2, strategy3],
problems=[branin_100, gramacy_100],
)
with open(
f'results/branin_gramacy_100_alebo_rembo_hesbo_sobol_rep_{rep}.json', "w"
) as fout:
json.dump(object_to_json(all_benchmarks), fout)
def run_sensitivity_D_benchmarks(rep):
results_dict = {}
for D, problem in branin_by_D.items():
strategy1 = ALEBOStrategy(D=D, d=4, init_size=10)
all_benchmarks = full_benchmark_run(
num_replications=1,
num_trials=50,
batch_size=1,
methods=[strategy1],
problems=[problem],
)
results_dict[D] = object_to_json(all_benchmarks)
with open(f'results/sensitivity_D_rep_{rep}.json', "w") as fout:
json.dump(results_dict, fout)
def run_sensitivity_d_e_benchmarks(rep):
strategies = [
ALEBOStrategy(D=100, d=d_e, init_size=10, name=f'ALEBO, d={d_e}')
for d_e in [2, 3, 5, 6, 7, 8]
]
all_benchmarks = full_benchmark_run(
num_replications=1,
num_trials=50,
batch_size=1,
methods=strategies,
problems=[branin_100],
)
with open(f'results/sensitivity_d_e_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(all_benchmarks), fout)
def run_ablation_benchmarks(rep):
strategies = [
ALEBOStrategy_projection_ablation(D=100, d=4, init_size=10, name='ALEBO, projection ablation'),
ALEBOStrategy_kernel_ablation(D=100, d=4, init_size=10, name='ALEBO, kernel ablation'),
ALEBOStrategy(D=100, d=4, init_size=10, name='ALEBO, base'),
]
all_benchmarks = full_benchmark_run(
num_replications=1,
num_trials=50,
batch_size=1,
methods=strategies,
problems=[branin_100],
)
with open(f'results/ablation_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(all_benchmarks), fout)
if __name__ == '__main__':
# Run all of the benchmark replicates.
# They are set up here to run as individual replicates becaus they can be
# distributed.
for i in range(50):
# Hartmann6, D=100: Each rep takes ~2 hrs
run_hartmann6_benchmarks(D=100, rep=i)
# Hartmann6, D=1000: Each rep takes ~2.5 hrs
run_hartmann6_benchmarks(D=1000, rep=i)
# Hartmann6, D=1000: Each rep takes ~2.5 hrs
run_hartmann6_benchmarks(D=1000, rep=i, random_subspace=True)
# Branin and Gramacy, D=100: Each rep takes ~20 mins
run_branin_and_gramacy_100_benchmarks(rep=i)
# Sensitivity benchmarks: Each rep takes ~2 hrs
run_sensitivity_D_benchmarks(rep=i)
run_sensitivity_d_e_benchmarks(rep=i)
for i in range(100):
# Ablation benchmarks
run_ablation_benchmarks(rep=i)
| alebo-main | benchmarks/run_ax_benchmarks.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Run benchmarks for Ensemble BO.
A few steps are required to use EBO:
(1) git clone https://github.com/zi-w/Ensemble-Bayesian-Optimization
in this directory. These experiments used commit
4e6f9ed04833cc2e21b5906b1181bc067298f914.
(2) fix a python3 issue by editing ebo_core/helper.py to insert
shape = int(shape)
in line 7.
"""
import os
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['OMP_NUM_THREADS'] = '1'
import sys
sys.path.insert(1, os.path.join(os.getcwd(), 'Ensemble-Bayesian-Optimization'))
from ebo_core.ebo import ebo
import json
import numpy as np
from benchmark_problems import (
branin_100,
hartmann6_100,
hartmann6_1000,
)
from ax.benchmark.benchmark import benchmark_minimize_callable
from ax.storage.json_store.encoder import object_to_json
# These options are taken as package defaults from test_ebo.py
core_options = {
#'x_range':x_range, # input domain
#'dx':x_range.shape[1], # input dimension
#'max_value':f.f_max + sigma*5, # target value
#'T':10, # number of iterations
'B':10, # number of candidates to be evaluated
'dim_limit':3, # max dimension of the input for each additive function component
'isplot':0, # 1 if plotting the result; otherwise 0.
'z':None, 'k':None, # group assignment and number of cuts in the Gibbs sampling subroutine
'alpha':1., # hyperparameter of the Gibbs sampling subroutine
'beta':np.array([5.,2.]),
'opt_n':1000, # points randomly sampled to start continuous optimization of acfun
'pid':'test3', # process ID for Azure
'datadir':'tmp_data/', # temporary data directory for Azure
'gibbs_iter':10, # number of iterations for the Gibbs sampling subroutine
'useAzure':False, # set to True if use Azure for batch evaluation
'func_cheap':True, # if func cheap, we do not use Azure to test functions
'n_add':None, # this should always be None. it makes dim_limit complicated if not None.
'nlayers': 100, # number of the layers of tiles
'gp_type':'l1', # other choices are l1, sk, sf, dk, df
#'gp_sigma':0.1, # noise standard deviation
'n_bo':10, # min number of points selected for each partition
'n_bo_top_percent': 0.5, # percentage of top in bo selections
'n_top':10, # how many points to look ahead when doing choose Xnew
'min_leaf_size':10, # min number of samples in each leaf
'max_n_leaves':10, # max number of leaves
'thresAzure':1, # if batch size > thresAzure, we use Azure
'save_file_name': 'tmp/tmp.pk',
}
def run_hartmann6_benchmarks(D, rep):
if D == 100:
problem = hartmann6_100
elif D == 1000:
problem = hartmann6_1000
experiment, f = benchmark_minimize_callable(
problem=problem,
num_trials=200,
method_name='ebo',
replication_index=rep,
)
options = {
'x_range': np.vstack((np.zeros(D), np.ones(D))),
'dx': D,
'max_value': 3.32237, # Let it cheat and know the true max value
'T': 200,
'gp_sigma': 1e-7,
}
options.update(core_options)
f_max = lambda x: -f(x) # since EBO maximizes
e = ebo(f_max, options)
try:
e.run()
except ValueError:
pass # EBO can ask for more than T function evaluations
with open(f'results/hartmann6_{D}_ebo_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
def run_branin_benchmarks(rep):
experiment, f = benchmark_minimize_callable(
problem=branin_100,
num_trials=50,
method_name='ebo',
replication_index=rep,
)
options = {
'x_range': np.vstack((
np.hstack((-5 * np.ones(50), np.zeros(50))),
np.hstack((10 * np.ones(50), 15 * np.ones(50))),
)),
'dx': 100,
'max_value': -0.397887, # Let it cheat and know the true max value
'T': 50,
'gp_sigma': 1e-7,
}
options.update(core_options)
f_max = lambda x: -f(x) # since EBO maximizes
e = ebo(f_max, options)
try:
e.run()
except ValueError:
pass # EBO can ask for more than T function evaluations
with open(f'results/branin_100_ebo_rep_{rep}.json', "w") as fout:
json.dump(object_to_json(experiment), fout)
if __name__ == '__main__':
# Run all of the EBO benchmarks.
# These can be distributed.
for i in range(50):
# Hartmann6, D=100: Each rep takes ~2 hours
run_hartmann6_benchmarks(D=100, rep=i)
## Hartmann6, D=1000: Too slow, not run
#run_hartmann6_benchmarks(D=1000, rep=i)
# Branin, D=100: Each rep takes ~20 mins
run_branin_benchmarks(rep=i)
| alebo-main | benchmarks/run_ebo_benchmarks.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
"""
Requires nasbench==1.0 from https://github.com/google-research/nasbench
Also requires dataset nasbench_only108.tfrecord to be downloaded here.
Creates an evaluation functionn for neural architecture search
"""
import numpy as np
from ax.service.ax_client import AxClient
from nasbench.lib.model_spec import ModelSpec
from nasbench import api
nasbench = api.NASBench('nasbench_only108.tfrecord')
def get_spec(adj_indxs, op_indxs):
"""
Construct a NASBench spec from adjacency matrix and op indicators
"""
op_names = ['conv1x1-bn-relu', 'conv3x3-bn-relu', 'maxpool3x3']
ops = ['input']
ops.extend([op_names[i] for i in op_indxs])
ops.append('output')
iu = np.triu_indices(7, k=1)
adj_matrix = np.zeros((7, 7), dtype=np.int32)
adj_matrix[(iu[0][adj_indxs], iu[1][adj_indxs])] = 1
spec = ModelSpec(adj_matrix, ops)
return spec
def evaluate_x(x):
"""
Evaluate NASBench on the model defined by x.
x is a 36-d array.
The first 21 are for the adjacency matrix. Largest entries will have the
corresponding element in the adjacency matrix set to 1, with as many 1s as
possible within the NASBench model space.
The last 15 are for the ops in each of the five NASBench model components.
One-hot encoded for each of the 5 components, 3 options.
"""
assert len(x) == 36
x_adj = x[:21]
x_op = x[-15:]
x_ord = x_adj.argsort()[::-1]
op_indxs = x_op.reshape(3, 5).argmax(axis=0).tolist()
last_good = None
for i in range(1, 22):
model_spec = get_spec(x_ord[:i], op_indxs)
if model_spec.matrix is not None:
# We have a connected graph
# See if it has too many edges
if model_spec.matrix.sum() > 9:
break
last_good = model_spec
if last_good is None:
# Could not get a valid spec from this x. Return bad metric values.
return [0.80], [50 * 60]
fixed_metrics, computed_metrics = nasbench.get_metrics_from_spec(last_good)
test_acc = [r['final_test_accuracy'] for r in computed_metrics[108]]
train_time = [r['final_training_time'] for r in computed_metrics[108]]
return np.mean(test_acc), np.mean(train_time)
def evaluate_parameters(parameters):
x = np.array([parameters[f'x{i}'] for i in range(36)])
test_acc, train_time = evaluate_x(x)
return {
'final_test_accuracy': (test_acc, 0.0),
'final_training_time': (train_time, 0.0),
}
def get_nasbench_ax_client(generation_strategy):
# Get parameters
parameters = [
{
"name": f"x{i}",
"type": "range",
"bounds": [0, 1],
"value_type": "float",
"log_scale": False,
} for i in range(36)
]
axc = AxClient(generation_strategy=generation_strategy, verbose_logging=False)
axc.create_experiment(
name="nasbench",
parameters=parameters,
objective_name="final_test_accuracy",
minimize=False,
outcome_constraints=["final_training_time <= 1800"],
)
return axc
class NASBenchRunner:
"""
A runner for non-Ax methods.
Assumes method MINIMIZES.
"""
def __init__(self, max_eval):
# For tracking iterations
self.fs = []
self.feas = []
self.n_eval = 0
self.max_eval = max_eval
def f(self, x):
if self.n_eval >= self.max_eval:
raise ValueError("Evaluation budget exhuasted")
test_acc, train_time = evaluate_x(x)
feas = bool(train_time <= 1800)
if not feas:
val = 0.80 # bad value for infeasible
else:
val = test_acc
self.n_eval += 1
self.fs.append(test_acc) # Store the true, not-negated value
self.feas.append(feas)
return -val # ASSUMES METHOD MINIMIZES
| alebo-main | benchmarks/nasbench_evaluation.py |
import os
import cv2
import json
from tqdm import tqdm
import numpy as np
import argparse
import glob
from src.common.utils.preprocessing import load_skeleton
from src.common.utils.vis import vis_keypoints
from src.common.utils.transforms import world2pixel
def visualize_pose_on_frame(frame_path, camera_name, joints_3d_dict, calib, skeleton):
"""
Overlay 3D keypoints on the given frame and return the visualized frame.
"""
img = cv2.imread(frame_path)
assert len(img.shape) == 3, "Image must be a 3-channel BGR image."
frame_id = os.path.basename(frame_path).split('.')[0]
K = calib["intrinsics"][camera_name]
Rt = calib["extrinsics"][frame_id][camera_name]
KRT = np.dot(K, Rt)
joints_3d = np.asarray(joints_3d_dict[frame_id]["world_coord"])
joint_valid = np.asarray(joints_3d_dict[frame_id]["joint_valid"])
joints_2d = world2pixel(joints_3d, KRT)[:, :2]
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
vis_img = vis_keypoints(img, joints_2d, joint_valid, skeleton)
return vis_img
def main(args):
os.makedirs(args.save_path, exist_ok=True)
# set image path
ego_image_dir = os.path.join(args.ego_image_root, args.vis_set, args.vis_seq_name, args.vis_camera_name)
assert os.path.exists(ego_image_dir), f"Path {ego_image_dir} does not exist."
frame_list = sorted(glob.glob(f"{ego_image_dir}/*"))
# read annotation
with open(args.calib_file) as f:
ego_calib = json.load(f)["calibration"][args.vis_seq_name]
with open(args.kpt_file) as f:
joints_3d_dict = json.load(f)["annotations"][args.vis_seq_name]
skeleton = load_skeleton(args.skeleton_file, 42)
# set video writer
output_video_path = os.path.join(args.save_path, f'vis_video_{args.vis_seq_name}_{args.vis_camera_name.replace("_mono10bit", "")}.mp4')
tmp_output_video_path = output_video_path.replace("vis_video", "tmp_vis_video")
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
vis_img = cv2.imread(frame_list[0])
H, W = vis_img.shape[:2]
videoWriter = cv2.VideoWriter(tmp_output_video_path, fourcc, args.vis_fps, (W, H))
for frame_path in tqdm(frame_list[:args.vis_limit]):
vis_img = visualize_pose_on_frame(frame_path, args.vis_camera_name, joints_3d_dict, ego_calib, skeleton)
vis_img = cv2.cvtColor(vis_img, cv2.COLOR_RGB2BGR)
videoWriter.write(vis_img)
videoWriter.release()
# reformat the video
ret = os.system(f"ffmpeg -y -i {tmp_output_video_path} -vcodec libx264 {output_video_path}")
assert ret == 0, "check ffmpeg processing"
os.system(f"rm {tmp_output_video_path}")
print(f"Saved visualization video to {output_video_path}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Visualize hand pose on video frames and create a video.")
parser.add_argument("--ego_image_root", default="./data/assemblyhands/images/ego_images_rectified", type=str)
parser.add_argument("--vis_set", default="val", type=str, help="val or test")
parser.add_argument("--vis_camera_name", default="HMC_21179183_mono10bit", type=str)
parser.add_argument("--vis_seq_name", default="nusar-2021_action_both_9081-c11b_9081_user_id_2021-02-12_161433", type=str)
parser.add_argument("--calib_file", default="./data/assemblyhands/annotations/val/assemblyhands_val_ego_calib_v1-1.json", type=str)
parser.add_argument("--data_file", default="./data/assemblyhands/annotations/val/assemblyhands_val_ego_data_v1-1.json", type=str)
parser.add_argument("--kpt_file", default="./data/assemblyhands/annotations/val/assemblyhands_val_joint_3d_v1-1.json", type=str)
parser.add_argument("--skeleton_file", default="./data/assemblyhands/annotations/skeleton.txt", type=str)
parser.add_argument("--save_path", default="vis-results/vis-gt", type=str)
parser.add_argument("--vis_limit", default=50, type=int, help="Limit number of frames for visualization.")
parser.add_argument("--vis_fps", default=10, type=int, help="Frames per second for the output video.")
args = parser.parse_args()
main(args)
| assemblyhands-toolkit-main | visualization/visualizer.py |
from src.main.config import base_cfg as cfg | assemblyhands-toolkit-main | src/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
import torch
import torch.utils.data
import cv2
import os
import os.path as osp
import random
from copy import deepcopy
from src.common.utils.preprocessing import (
load_img,
load_crop_img,
update_params_after_crop,
load_skeleton,
get_bbox,
process_bbox,
augmentation,
transform_input_to_output_space,
trans_point2d,
)
from src.common.utils.transforms import cam2pixel, pixel2cam, Camera
from src.common.utils.transforms import world2cam_assemblyhands as world2cam
from src.common.utils.transforms import cam2world_assemblyhands as cam2world
from src.common.utils.vis import vis_keypoints, vis_3d_keypoints
from copy import deepcopy
import json
from pycocotools.coco import COCO
ANNOT_VERSION = "v1-1"
IS_DEBUG = True
# IS_DEBUG = False
N_DEBUG_SAMPLES = 200
class Dataset(torch.utils.data.Dataset):
def __init__(self, transform, cfg, mode):
self.mode = mode # train, test, val
self.img_path = "data/assemblyhands/images"
self.annot_path = "data/assemblyhands/annotations"
self.modality = "ego"
self.transform = transform
self.cfg = cfg
self.joint_num = 21 # single hand
self.root_joint_idx = {"right": 20, "left": 41}
self.joint_type = {
"right": np.arange(0, self.joint_num),
"left": np.arange(self.joint_num, self.joint_num * 2),
}
self.skeleton = load_skeleton(
osp.join(self.annot_path, "skeleton.txt"), self.joint_num * 2
)
self.datalist = []
self.datalist_sh = []
self.datalist_ih = []
self.sequence_names = []
n_skip = 0
# load annotation
print(f"Load annotation from {self.annot_path}, mode: {self.mode}")
data_mode = self.mode
if IS_DEBUG and self.mode.startswith("train"):
print(">>> DEBUG MODE: Loading val data during training")
data_mode = "val"
self.invalid_data_file = os.path.join(
self.annot_path, data_mode, f"invalid_{data_mode}_{self.modality}.txt"
)
db = COCO(
osp.join(
self.annot_path,
data_mode,
"assemblyhands_"
+ data_mode
+ f"_{self.modality}_data_{ANNOT_VERSION}.json",
)
)
with open(
osp.join(
self.annot_path,
data_mode,
"assemblyhands_"
+ data_mode
+ f"_{self.modality}_calib_{ANNOT_VERSION}.json",
)
) as f:
cameras = json.load(f)["calibration"]
with open(
osp.join(
self.annot_path,
data_mode,
"assemblyhands_" + data_mode + f"_joint_3d_{ANNOT_VERSION}.json",
)
) as f:
joints = json.load(f)["annotations"]
print("Get bbox and root depth from groundtruth annotation")
invalid_data_list = None
if osp.exists(self.invalid_data_file):
with open(self.invalid_data_file) as f:
lines = f.readlines()
if len(lines) > 0:
invalid_data_list = [line.strip() for line in lines]
else:
print(
"Invalid data file does not exist. Checking the validity of generated crops"
)
f = open(self.invalid_data_file, "w")
annot_list = db.anns.keys()
for i, aid in enumerate(annot_list):
ann = db.anns[aid]
image_id = ann["image_id"]
img = db.loadImgs(image_id)[0]
seq_name = str(img["seq_name"])
camera_name = img["camera"]
frame_idx = img["frame_idx"]
file_name = img["file_name"]
img_path = osp.join(self.img_path, file_name)
assert osp.exists(img_path), f"Image path {img_path} does not exist"
K = np.array(
cameras[seq_name]["intrinsics"][camera_name + "_mono10bit"],
dtype=np.float32,
)
Rt = np.array(
cameras[seq_name]["extrinsics"][f"{frame_idx:06d}"][
camera_name + "_mono10bit"
],
dtype=np.float32,
)
retval_camera = Camera(K, Rt, dist=None, name=camera_name)
campos, camrot, focal, princpt = retval_camera.get_params()
joint_world = np.array(
joints[seq_name][f"{frame_idx:06d}"]["world_coord"], dtype=np.float32
)
joint_cam = world2cam(joint_world, camrot, campos)
joint_img = cam2pixel(joint_cam, focal, princpt)[:, :2]
joint_valid = np.array(ann["joint_valid"], dtype=np.float32).reshape(
self.joint_num * 2
)
# if root is not valid -> root-relative 3D pose is also not valid. Therefore, mark all joints as invalid
# joint_valid[self.joint_type['right']] *= joint_valid[self.root_joint_idx['right']]
# joint_valid[self.joint_type['left']] *= joint_valid[self.root_joint_idx['left']]
abs_depth = {
"right": joint_cam[self.root_joint_idx["right"], 2],
"left": joint_cam[self.root_joint_idx["left"], 2],
}
cam_param = {"focal": focal, "princpt": princpt}
for hand_id, hand_type in enumerate(["right", "left"]):
if ann["bbox"][hand_type] is None:
continue
hand_type_valid = np.ones(1, dtype=np.float32)
img_width, img_height = img["width"], img["height"]
bbox = np.array(ann["bbox"][hand_type], dtype=np.float32) # x,y,x,y
x0, y0, x1, y1 = bbox
original_bbox = [x0, y0, x1 - x0, y1 - y0] # x,y,w,h
bbox = process_bbox(
original_bbox, (img_height, img_width), scale=1.75
) # bbox = original_bbox
joint_valid_single_hand = deepcopy(joint_valid)
inv_hand_id = abs(1 - hand_id)
# make invlid for the other hand
joint_valid_single_hand[
inv_hand_id * self.joint_num : (inv_hand_id + 1) * self.joint_num
] = 0
if invalid_data_list is not None:
crop_name = f"{file_name},{hand_id}"
if crop_name in invalid_data_list: # skip registred invalid samples
n_skip += 1
continue
else: # first run to check the validity of generated crops
if sum(joint_valid_single_hand) < 10:
n_skip += 1
f.write(f"{file_name},{hand_id}\n")
continue
try:
load_crop_img(
img_path,
bbox,
joint_img.copy(),
joint_world.copy(),
joint_valid_single_hand.copy(),
deepcopy(retval_camera),
)
except:
n_skip += 1
f.write(f"{file_name},{hand_id}\n")
continue
joint = {
"cam_coord": joint_cam,
"img_coord": joint_img,
"world_coord": joint_world,
"valid": joint_valid_single_hand,
} # joint_valid}
data = {
"img_path": img_path,
"seq_name": seq_name,
"cam_param": cam_param,
"bbox": bbox,
"original_bbox": original_bbox,
"joint": joint,
"hand_type": hand_type,
"hand_type_valid": hand_type_valid,
"abs_depth": abs_depth,
"file_name": img["file_name"],
"seq_name": seq_name,
"cam": camera_name,
"frame": frame_idx,
"retval_camera": retval_camera,
}
if hand_type == "right" or hand_type == "left":
self.datalist_sh.append(data)
else:
self.datalist_ih.append(data)
if seq_name not in self.sequence_names:
self.sequence_names.append(seq_name)
if IS_DEBUG and i >= N_DEBUG_SAMPLES - 1:
print(">>> DEBUG MODE: Loaded %d samples" % N_DEBUG_SAMPLES)
break
self.datalist = self.datalist_sh + self.datalist_ih
assert len(self.datalist) > 0, "No data found."
if not osp.exists(self.invalid_data_file):
f.close()
print(
"Number of annotations in single hand sequences: "
+ str(len(self.datalist_sh))
)
print(
"Number of annotations in interacting hand sequences: "
+ str(len(self.datalist_ih))
)
print("Number of skipped annotations: " + str(n_skip))
def handtype_str2array(self, hand_type):
if hand_type == "right":
return np.array([1, 0], dtype=np.float32)
elif hand_type == "left":
return np.array([0, 1], dtype=np.float32)
elif hand_type == "interacting":
return np.array([1, 1], dtype=np.float32)
else:
assert 0, print("Not supported hand type: " + hand_type)
def __len__(self):
return len(self.datalist)
def __getitem__(self, idx):
data = self.datalist[idx]
img_path, bbox, joint, hand_type, hand_type_valid = (
data["img_path"],
data["bbox"],
data["joint"],
data["hand_type"],
data["hand_type_valid"],
)
joint_world = joint["world_coord"]
joint_img = joint["img_coord"].copy()
joint_valid = joint["valid"].copy()
hand_type = self.handtype_str2array(hand_type)
# image load # img = load_img(img_path, bbox)
img, bbox, joint_img, joint_cam, joint_valid, retval_camera = load_crop_img(
img_path,
bbox,
joint_img,
joint_world,
joint_valid,
deepcopy(data["retval_camera"]),
)
joint_coord = np.concatenate((joint_img, joint_cam[:, 2, None]), 1)
# augmentation
img, joint_coord, joint_valid, hand_type, inv_trans = augmentation(
img,
bbox,
joint_coord,
joint_valid,
hand_type,
self.mode,
self.joint_type,
no_aug=True,
)
rel_root_depth = np.array(
[
joint_coord[self.root_joint_idx["left"], 2]
- joint_coord[self.root_joint_idx["right"], 2]
],
dtype=np.float32,
).reshape(1)
root_valid = (
np.array(
[
joint_valid[self.root_joint_idx["right"]]
* joint_valid[self.root_joint_idx["left"]]
],
dtype=np.float32,
).reshape(1)
if hand_type[0] * hand_type[1] == 1
else np.zeros((1), dtype=np.float32)
)
# transform to output heatmap space
(
joint_coord_hm,
joint_valid,
rel_root_depth,
root_valid,
) = transform_input_to_output_space(
joint_coord.copy(),
joint_valid,
rel_root_depth,
root_valid,
self.root_joint_idx,
self.joint_type,
)
img = self.transform(img.astype(np.float32)) / 255.0
# update camera parameters after resize to cfg.input_img_shape
retval_camera.update_after_resize((bbox[3], bbox[2]), self.cfg.input_img_shape)
campos, camrot, focal, princpt = retval_camera.get_params()
cam_param = {"focal": focal, "princpt": princpt}
inputs = {"img": img, "idx": idx}
targets = {
"joint_coord": joint_coord_hm,
"_joint_coord": joint_coord,
"rel_root_depth": rel_root_depth,
"hand_type": hand_type,
}
meta_info = {
"joint_valid": joint_valid,
"root_valid": root_valid,
"hand_type_valid": hand_type_valid,
"inv_trans": inv_trans,
"seq_name": data["seq_name"],
"cam": data["cam"],
"frame": int(data["frame"]),
"cam_param_updated": cam_param,
}
return inputs, targets, meta_info
def view_samples(self, max_n_vis=10, is_crop=True):
print("\nVisualize GT...")
gts = self.datalist
sample_num = len(gts)
random.seed(0)
random_samples = random.sample(range(sample_num), max_n_vis)
for i in random_samples:
data = gts[i]
img_path, joint, gt_hand_type = (
data["img_path"],
data["joint"],
data["hand_type"],
)
frame_id = int(img_path.split("/")[-1].split(".")[0])
gt_joint_coord_img = joint["img_coord"].copy() # original image
gt_joint_coord_cam = joint["cam_coord"].copy()
joint_valid = joint["valid"]
if is_crop:
# read cropped image
inputs, targets, meta_info = self.__getitem__(i)
img = inputs["img"]
_img = img.numpy() * 255.0
gt_joint_coord_img = targets["joint_coord"].copy() # heatmap coord
gt_joint_coord_img[:, 0] = (
gt_joint_coord_img[:, 0]
/ self.cfg.output_hm_shape[2]
* self.cfg.input_img_shape[1]
)
gt_joint_coord_img[:, 1] = (
gt_joint_coord_img[:, 1]
/ self.cfg.output_hm_shape[1]
* self.cfg.input_img_shape[0]
)
# restore depth to original camera space
gt_joint_coord_img[:, 2] = (
gt_joint_coord_img[:, 2] / self.cfg.output_hm_shape[0] * 2 - 1
) * (self.cfg.bbox_3d_size / 2)
gt_joint_coord_img[self.joint_type["right"], 2] += data["abs_depth"][
"right"
]
gt_joint_coord_img[self.joint_type["left"], 2] += data["abs_depth"][
"left"
]
else:
# read full image
_img = cv2.imread(img_path)
_img = _img.transpose(2, 0, 1)
_img = _img.astype(np.uint8)
vis_kps = gt_joint_coord_img.copy()
vis_valid = joint_valid.copy()
filename = f"vis_{frame_id:04d}_{gt_hand_type}_2d.jpg"
vis_keypoints(
_img,
vis_kps,
vis_valid,
self.skeleton,
filename,
self.cfg,
is_print=True,
)
filename = f"vis_{frame_id:04d}_{gt_hand_type}_3d.jpg"
vis_kps = gt_joint_coord_cam.copy()
vis_3d_keypoints(
vis_kps, joint_valid, self.skeleton, filename, self.cfg, is_print=True
)
def evaluate(self, preds):
print("\nEvaluation start...")
# set False to view full images
IS_CROP = True # False
gts = self.datalist
preds_joint_coord, preds_rel_root_depth, preds_hand_type, inv_trans = (
preds["joint_coord"],
preds["rel_root_depth"],
preds["hand_type"],
preds["inv_trans"],
)
assert len(gts) == len(preds_joint_coord)
sample_num = len(gts)
mpjpe_sh = [[] for _ in range(self.joint_num * 2)]
mpjpe_ih = [[] for _ in range(self.joint_num * 2)]
mrrpe = []
acc_hand_cls = 0
hand_cls_cnt = 0
img_size = None
for n in range(sample_num):
data = gts[n]
img_path, bbox, cam_param, joint, gt_hand_type, hand_type_valid = (
data["img_path"],
data["bbox"],
data["cam_param"],
data["joint"],
data["hand_type"],
data["hand_type_valid"],
)
if img_size is None:
img_size = cv2.imread(img_path).shape[:2]
gt_joint_coord_img = joint["img_coord"].copy() # original image
gt_joint_coord_cam = joint["cam_coord"].copy()
joint_valid = joint["valid"]
if IS_CROP:
inputs, targets, meta_info = self.__getitem__(n)
cam_param = meta_info["cam_param_updated"]
focal = cam_param["focal"]
princpt = cam_param["princpt"]
# restore xy coordinates to original image space
pred_joint_coord_img = preds_joint_coord[n].copy()
pred_joint_coord_img[:, 0] = (
pred_joint_coord_img[:, 0]
/ self.cfg.output_hm_shape[2]
* self.cfg.input_img_shape[1]
)
pred_joint_coord_img[:, 1] = (
pred_joint_coord_img[:, 1]
/ self.cfg.output_hm_shape[1]
* self.cfg.input_img_shape[0]
)
# for j in range(self.joint_num*2):
# pred_joint_coord_img[j, :2] = trans_point2d(pred_joint_coord_img[j, :2], inv_trans[n])
# restore depth to original camera space
pred_joint_coord_img[:, 2] = (
pred_joint_coord_img[:, 2] / self.cfg.output_hm_shape[0] * 2 - 1
) * (self.cfg.bbox_3d_size / 2)
# mrrpe
if (
gt_hand_type == "interacting"
and joint_valid[self.root_joint_idx["left"]]
and joint_valid[self.root_joint_idx["right"]]
):
pred_rel_root_depth = (
preds_rel_root_depth[n] / self.cfg.output_root_hm_shape * 2 - 1
) * (self.cfg.bbox_3d_size_root / 2)
pred_left_root_img = pred_joint_coord_img[
self.root_joint_idx["left"]
].copy()
pred_left_root_img[2] += (
data["abs_depth"]["right"] + pred_rel_root_depth
)
pred_left_root_cam = pixel2cam(
pred_left_root_img[None, :], focal, princpt
)[0]
pred_right_root_img = pred_joint_coord_img[
self.root_joint_idx["right"]
].copy()
pred_right_root_img[2] += data["abs_depth"]["right"]
pred_right_root_cam = pixel2cam(
pred_right_root_img[None, :], focal, princpt
)[0]
pred_rel_root = pred_left_root_cam - pred_right_root_cam
gt_rel_root = (
gt_joint_coord_cam[self.root_joint_idx["left"]]
- gt_joint_coord_cam[self.root_joint_idx["right"]]
)
mrrpe.append(float(np.sqrt(np.sum((pred_rel_root - gt_rel_root) ** 2))))
# add root joint depth
pred_joint_coord_img[self.joint_type["right"], 2] += data["abs_depth"][
"right"
]
pred_joint_coord_img[self.joint_type["left"], 2] += data["abs_depth"][
"left"
]
# back project to camera coordinate system
pred_joint_coord_cam = pixel2cam(pred_joint_coord_img, focal, princpt)
# root joint alignment
for h in ("right", "left"):
pred_joint_coord_cam[self.joint_type[h]] = (
pred_joint_coord_cam[self.joint_type[h]]
- pred_joint_coord_cam[self.root_joint_idx[h], None, :]
)
gt_joint_coord_cam[self.joint_type[h]] = (
gt_joint_coord_cam[self.joint_type[h]]
- gt_joint_coord_cam[self.root_joint_idx[h], None, :]
)
# mpjpe
for j in range(self.joint_num * 2):
if joint_valid[j]:
if gt_hand_type == "right" or gt_hand_type == "left":
mpjpe_sh[j].append(
np.sqrt(
np.sum(
(pred_joint_coord_cam[j] - gt_joint_coord_cam[j])
** 2
)
)
)
else:
mpjpe_ih[j].append(
np.sqrt(
np.sum(
(pred_joint_coord_cam[j] - gt_joint_coord_cam[j])
** 2
)
)
)
# handedness accuray
if hand_type_valid:
if (
gt_hand_type == "right"
and preds_hand_type[n][0] > 0.5
and preds_hand_type[n][1] < 0.5
):
acc_hand_cls += 1
elif (
gt_hand_type == "left"
and preds_hand_type[n][0] < 0.5
and preds_hand_type[n][1] > 0.5
):
acc_hand_cls += 1
elif (
gt_hand_type == "interacting"
and preds_hand_type[n][0] > 0.5
and preds_hand_type[n][1] > 0.5
):
acc_hand_cls += 1
hand_cls_cnt += 1
if hand_cls_cnt > 0:
print("Handedness accuracy: " + str(acc_hand_cls / hand_cls_cnt))
if len(mrrpe) > 0:
print("MRRPE: " + str(sum(mrrpe) / len(mrrpe)))
print()
if len(mpjpe_ih[j]) > 0:
tot_err = []
eval_summary = "MPJPE for each joint: \n"
for j in range(self.joint_num * 2):
tot_err_j = np.mean(
np.concatenate((np.stack(mpjpe_sh[j]), np.stack(mpjpe_ih[j])))
)
joint_name = self.skeleton[j]["name"]
eval_summary += joint_name + ": %.2f, " % tot_err_j
tot_err.append(tot_err_j)
print(eval_summary)
print("MPJPE for all hand sequences: %.2f\n" % (np.nanmean(tot_err)))
eval_summary = "MPJPE for each joint: \n"
for j in range(self.joint_num * 2):
mpjpe_ih[j] = np.mean(np.stack(mpjpe_ih[j]))
joint_name = self.skeleton[j]["name"]
eval_summary += joint_name + ": %.2f, " % mpjpe_ih[j]
print(eval_summary)
print(
"MPJPE for interacting hand sequences: %.2f\n" % (np.nanmean(mpjpe_ih))
)
eval_summary = "MPJPE for each joint: \n"
for j in range(self.joint_num * 2):
if len(mpjpe_sh[j]) > 0:
mpjpe_sh[j] = np.mean(np.stack(mpjpe_sh[j]))
else:
mpjpe_sh[j] = np.nan
joint_name = self.skeleton[j]["name"]
eval_summary += joint_name + ": %.2f, " % mpjpe_sh[j]
print(eval_summary)
print("MPJPE for single hand sequences: %.2f\n" % (np.nanmean(mpjpe_sh)))
if __name__ == "__main__":
from tqdm import tqdm
from src.main.config import Config
args_gpu_ids = "0"
args_dataset = "AssemblyHands-Ego"
args_test_set = "val"
args_test_epoch = "20"
cfg = Config(dataset=args_dataset)
cfg.set_args(args_gpu_ids)
cfg.print_config()
from src.common.base import Tester
tester = Tester(cfg, args_test_epoch)
tester._make_batch_generator(args_test_set, shuffle=True)
checkpoint_dir = "checkpoints"
tester._make_model(checkpoint_dir)
# visualize samples
tester.testset.view_samples()
for itr, (inputs, targets, meta_info) in enumerate(tqdm(tester.batch_generator)):
print(f"OK: data get {itr}")
break
| assemblyhands-toolkit-main | src/dataset/AssemblyHands-Ego/dataset.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
# -----------------------LICENSE--------------------------
# Fast R-CNN
#
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
#
# MIT License
#
# 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.
# --------------------------------------------------------
#
# The code is from the publicly available implementation of Fast R-CNN
# https://github.com/rbgirshick/fast-rcnn/blob/master/lib/utils/timer.py
import time
class Timer(object):
"""A simple timer."""
def __init__(self):
self.total_time = 0.0
self.calls = 0
self.start_time = 0.0
self.diff = 0.0
self.average_time = 0.0
self.warm_up = 0
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def toc(self, average=True):
self.diff = time.time() - self.start_time
if self.warm_up < 10:
self.warm_up += 1
return self.diff
else:
self.total_time += self.diff
self.calls += 1
self.average_time = self.total_time / self.calls
if average:
return self.average_time
else:
return self.diff
| assemblyhands-toolkit-main | src/common/timer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import logging
import os
OK = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
END = "\033[0m"
PINK = "\033[95m"
BLUE = "\033[94m"
GREEN = OK
RED = FAIL
WHITE = END
YELLOW = WARNING
class colorlogger:
def __init__(self, log_dir, log_name="train_logs.txt"):
# set log
self._logger = logging.getLogger(log_name)
self._logger.setLevel(logging.INFO)
log_file = os.path.join(log_dir, log_name)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
file_log = logging.FileHandler(log_file, mode="a")
file_log.setLevel(logging.INFO)
console_log = logging.StreamHandler()
console_log.setLevel(logging.INFO)
formatter = logging.Formatter(
"{}%(asctime)s{} %(message)s".format(GREEN, END), "%m-%d %H:%M:%S"
)
file_log.setFormatter(formatter)
console_log.setFormatter(formatter)
self._logger.addHandler(file_log)
self._logger.addHandler(console_log)
def debug(self, msg):
self._logger.debug(str(msg))
def info(self, msg):
self._logger.info(str(msg))
def warning(self, msg):
self._logger.warning(WARNING + "WRN: " + str(msg) + END)
def critical(self, msg):
self._logger.critical(RED + "CRI: " + str(msg) + END)
def error(self, msg):
self._logger.error(RED + "ERR: " + str(msg) + END)
| assemblyhands-toolkit-main | src/common/logger.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import os.path as osp
import math
import time
import glob
import abc
from torch.utils.data import DataLoader
import torch.optim
import torchvision.transforms as transforms
# from src import cfg
from dataset import Dataset
from src.common.timer import Timer
from src.common.logger import colorlogger
from torch.nn.parallel.data_parallel import DataParallel
from src.main.model import get_model
class Base(object):
__metaclass__ = abc.ABCMeta
def __init__(self, cfg, log_name="logs.txt"):
self.cur_epoch = 0
self.cfg = cfg
# timer
self.tot_timer = Timer()
self.gpu_timer = Timer()
self.read_timer = Timer()
# logger
self.logger = colorlogger(self.cfg.log_dir, log_name=log_name)
@abc.abstractmethod
def _make_batch_generator(self):
return
@abc.abstractmethod
def _make_model(self):
return
class Trainer(Base):
def __init__(self, cfg):
super(Trainer, self).__init__(cfg, log_name="train_logs.txt")
def get_optimizer(self, model):
optimizer = torch.optim.Adam(model.parameters(), lr=self.cfg.lr)
return optimizer
def set_lr(self, epoch):
if len(self.cfg.lr_dec_epoch) == 0:
return self.cfg.lr
for e in self.cfg.lr_dec_epoch:
if epoch < e:
break
if epoch < self.cfg.lr_dec_epoch[-1]:
idx = self.cfg.lr_dec_epoch.index(e)
for g in self.optimizer.param_groups:
g["lr"] = self.cfg.lr / (self.cfg.lr_dec_factor**idx)
else:
for g in self.optimizer.param_groups:
g["lr"] = self.cfg.lr / (
self.cfg.lr_dec_factor ** len(self.cfg.lr_dec_epoch)
)
def get_lr(self):
for g in self.optimizer.param_groups:
cur_lr = g["lr"]
return cur_lr
def _make_batch_generator(self):
# data load and construct batch generator
self.logger.info("Creating train dataset...")
trainset_loader = Dataset(transforms.ToTensor(), self.cfg, "train")
batch_generator = DataLoader(
dataset=trainset_loader,
batch_size=self.cfg.num_gpus * self.cfg.train_batch_size,
shuffle=True,
num_workers=self.cfg.num_thread,
pin_memory=True,
)
self.joint_num = trainset_loader.joint_num
self.itr_per_epoch = math.ceil(
trainset_loader.__len__() / self.cfg.num_gpus / self.cfg.train_batch_size
)
self.batch_generator = batch_generator
self.trainset = trainset_loader
def _make_model(self, resume_epoch=None):
# prepare network
self.logger.info("Creating graph and optimizer...")
model = get_model("train", self.joint_num)
model = DataParallel(model).cuda()
optimizer = self.get_optimizer(model)
if self.cfg.continue_train:
start_epoch, model, optimizer = self.load_model(
model, optimizer, resume_epoch
)
else:
start_epoch = 0
model.train()
self.start_epoch = start_epoch
self.model = model
self.optimizer = optimizer
def save_model(self, state, epoch):
file_path = osp.join(
self.cfg.model_dir, "snapshot_{:02d}.pth.tar".format(int(epoch))
)
torch.save(state, file_path)
self.logger.info("Write snapshot into {}".format(file_path))
def load_model(self, model, optimizer, resume_epoch=None):
model_file_list = glob.glob(osp.join(self.cfg.model_dir, "*.pth.tar"))
if resume_epoch is not None:
cur_epoch = resume_epoch
else:
cur_epoch = max(
[
int(
file_name[
file_name.find("snapshot_") + 9 : file_name.find(".pth.tar")
]
)
for file_name in model_file_list
]
)
model_path = osp.join(
self.cfg.model_dir, "snapshot_{:02d}.pth.tar".format(int(cur_epoch))
)
self.logger.info("Load checkpoint from {}".format(model_path))
ckpt = torch.load(model_path)
start_epoch = ckpt["epoch"] + 1
model.load_state_dict(ckpt["network"])
try:
optimizer.load_state_dict(ckpt["optimizer"])
except:
pass
return start_epoch, model, optimizer
class Tester(Base):
def __init__(self, cfg, test_epoch):
super(Tester, self).__init__(cfg, log_name="test_logs.txt")
self.test_epoch = int(test_epoch)
def _make_batch_generator(self, test_set, shuffle=False):
# data load and construct batch generator
self.logger.info("Creating " + test_set + " dataset...")
testset_loader = Dataset(transforms.ToTensor(), self.cfg, test_set)
batch_generator = DataLoader(
dataset=testset_loader,
batch_size=self.cfg.num_gpus * self.cfg.test_batch_size,
shuffle=shuffle,
num_workers=self.cfg.num_thread,
pin_memory=True,
)
self.joint_num = testset_loader.joint_num
self.batch_generator = batch_generator
self.testset = testset_loader
def _make_model(self, checkpoint_dir=None):
if checkpoint_dir is not None:
model_path = os.path.join(
checkpoint_dir, "snapshot_%02d.pth.tar" % self.test_epoch
)
if not os.path.exists(model_path):
model_path = os.path.join(
self.cfg.model_dir, "snapshot_%02d.pth.tar" % self.test_epoch
)
else:
model_path = os.path.join(
self.cfg.model_dir, "snapshot_%02d.pth.tar" % self.test_epoch
)
# assert os.path.exists(model_path), 'Cannot find model at ' + model_path
# prepare network
self.logger.info("Creating graph...")
model = get_model("test", self.joint_num)
model = DataParallel(model).cuda()
if os.path.exists(model_path):
self.logger.info("Load checkpoint from {}".format(model_path))
ckpt = torch.load(model_path)
model.load_state_dict(ckpt["network"])
else:
self.logger.info("Load checkpoint not found {}".format(model_path))
model.eval()
self.model = model
def _evaluate(self, preds):
self.testset.evaluate(preds)
| assemblyhands-toolkit-main | src/common/base.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import numpy as np
from scipy import linalg
def cam2pixel(cam_coord, f, c):
x = cam_coord[:, 0] / (cam_coord[:, 2] + 1e-8) * f[0] + c[0]
y = cam_coord[:, 1] / (cam_coord[:, 2] + 1e-8) * f[1] + c[1]
z = cam_coord[:, 2]
img_coord = np.concatenate((x[:,None], y[:,None], z[:,None]),1)
return img_coord
def pixel2cam(pixel_coord, f, c):
x = (pixel_coord[:, 0] - c[0]) / f[0] * pixel_coord[:, 2]
y = (pixel_coord[:, 1] - c[1]) / f[1] * pixel_coord[:, 2]
z = pixel_coord[:, 2]
cam_coord = np.concatenate((x[:,None], y[:,None], z[:,None]),1)
return cam_coord
def world2cam(world_coord, R, T):
cam_coord = np.dot(R, world_coord - T)
return cam_coord
def world2cam_assemblyhands(pts_3d, R, t):
pts_cam = np.dot(R, pts_3d.T).T + t
return pts_cam
def cam2world_assemblyhands(pts_cam_3d, R, t):
inv_R = np.linalg.inv(R)
pts_3d = np.dot(inv_R, (pts_cam_3d - t).T).T
return pts_3d
def world2pixel(pts_3d, KRT):
assert pts_3d.shape[1] == 3, f"shape error: {pts_3d.shape}"
_pts_3d = np.concatenate((pts_3d[:, :3], np.ones((pts_3d.shape[0], 1))), axis=-1)
pts_2d = np.matmul(_pts_3d, KRT.T)
pts_2d /= pts_2d[:, 2:3]
return pts_2d
def multi_meshgrid(*args):
"""
Creates a meshgrid from possibly many
elements (instead of only 2).
Returns a nd tensor with as many dimensions
as there are arguments
"""
args = list(args)
template = [1 for _ in args]
for i in range(len(args)):
n = args[i].shape[0]
template_copy = template.copy()
template_copy[i] = n
args[i] = args[i].view(*template_copy)
# there will be some broadcast magic going on
return tuple(args)
def flip(tensor, dims):
if not isinstance(dims, (tuple, list)):
dims = [dims]
indices = [torch.arange(tensor.shape[dim] - 1, -1, -1,
dtype=torch.int64) for dim in dims]
multi_indices = multi_meshgrid(*indices)
final_indices = [slice(i) for i in tensor.shape]
for i, dim in enumerate(dims):
final_indices[dim] = multi_indices[i]
flipped = tensor[final_indices]
assert flipped.device == tensor.device
assert flipped.requires_grad == tensor.requires_grad
return flipped
class Camera(object):
def __init__(self, K, Rt, dist=None, name=""):
# Rotate first then translate
self.K = np.array(K).copy()
assert self.K.shape == (3, 3)
self.Rt = np.array(Rt).copy()
assert self.Rt.shape == (3, 4)
self.dist = dist
if self.dist is not None:
self.dist = np.array(self.dist).copy().flatten()
self.name = name
def update_after_crop(self, bbox):
left, upper, right, lower = bbox
cx, cy = self.K[0, 2], self.K[1, 2]
new_cx = cx - left
new_cy = cy - upper
self.K[0, 2], self.K[1, 2] = new_cx, new_cy
def update_after_resize(self, image_shape, new_image_shape):
height, width = image_shape
new_height, new_width = new_image_shape
fx, fy, cx, cy = self.K[0, 0], self.K[1, 1], self.K[0, 2], self.K[1, 2]
new_fx = fx * (new_width / width)
new_fy = fy * (new_height / height)
new_cx = cx * (new_width / width)
new_cy = cy * (new_height / height)
self.K[0, 0], self.K[1, 1], self.K[0, 2], self.K[1, 2] = new_fx, new_fy, new_cx, new_cy
@property
def projection(self):
return np.dot(self.K, self.Rt)
def factor(self):
""" Factorize the camera matrix into K,R,t as P = K[R|t]. """
# factor first 3*3 part
K,R = linalg.rq(self.projection[:, :3])
# make diagonal of K positive
T = np.diag(np.sign(np.diag(K)))
if linalg.det(T) < 0:
T[1,1] *= -1
K = np.dot(K,T)
R = np.dot(T,R) # T is its own inverse
t = np.dot(linalg.inv(self.K), self.projection[:,3])
return K, R, t
def get_params(self):
K, R, t = self.factor()
campos, camrot = t, R
focal = [K[0, 0], K[1, 1]]
princpt = [K[0, 2], K[1, 2]]
return campos, camrot, focal, princpt
| assemblyhands-toolkit-main | src/common/utils/transforms.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import sys
def make_folder(folder_name):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
def add_pypath(path):
if path not in sys.path:
sys.path.insert(0, path)
| assemblyhands-toolkit-main | src/common/utils/dir.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import os.path as osp
import cv2
import numpy as np
import matplotlib
# matplotlib.use('tkagg')
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib as mpl
from src import cfg
from PIL import Image, ImageDraw
import io
hand_colors = [
[0, 0, 255],
[255, 0, 0],
]
def get_keypoint_rgb(skeleton):
rgb_dict= {}
for joint_id in range(len(skeleton)):
joint_name = skeleton[joint_id]['name']
if joint_name.endswith('thumb_null'):
rgb_dict[joint_name] = (255, 0, 0)
elif joint_name.endswith('thumb3'):
rgb_dict[joint_name] = (255, 51, 51)
elif joint_name.endswith('thumb2'):
rgb_dict[joint_name] = (255, 102, 102)
elif joint_name.endswith('thumb1'):
rgb_dict[joint_name] = (255, 153, 153)
elif joint_name.endswith('thumb0'):
rgb_dict[joint_name] = (255, 204, 204)
elif joint_name.endswith('index_null'):
rgb_dict[joint_name] = (0, 255, 0)
elif joint_name.endswith('index3'):
rgb_dict[joint_name] = (51, 255, 51)
elif joint_name.endswith('index2'):
rgb_dict[joint_name] = (102, 255, 102)
elif joint_name.endswith('index1'):
rgb_dict[joint_name] = (153, 255, 153)
elif joint_name.endswith('middle_null'):
rgb_dict[joint_name] = (255, 128, 0)
elif joint_name.endswith('middle3'):
rgb_dict[joint_name] = (255, 153, 51)
elif joint_name.endswith('middle2'):
rgb_dict[joint_name] = (255, 178, 102)
elif joint_name.endswith('middle1'):
rgb_dict[joint_name] = (255, 204, 153)
elif joint_name.endswith('ring_null'):
rgb_dict[joint_name] = (0, 128, 255)
elif joint_name.endswith('ring3'):
rgb_dict[joint_name] = (51, 153, 255)
elif joint_name.endswith('ring2'):
rgb_dict[joint_name] = (102, 178, 255)
elif joint_name.endswith('ring1'):
rgb_dict[joint_name] = (153, 204, 255)
elif joint_name.endswith('pinky_null'):
rgb_dict[joint_name] = (255, 0, 255)
elif joint_name.endswith('pinky3'):
rgb_dict[joint_name] = (255, 51, 255)
elif joint_name.endswith('pinky2'):
rgb_dict[joint_name] = (255, 102, 255)
elif joint_name.endswith('pinky1'):
rgb_dict[joint_name] = (255, 153, 255)
else:
rgb_dict[joint_name] = (230, 230, 0)
return rgb_dict
def draw_bbox_on_image(img, bbox):
if not isinstance(bbox, list):
bbox = [bbox]
idx = 0
for idx in range(len(bbox)):
box = list(bbox[idx])
x0, y0, w, h = box
x1, y1 = x0 + w, y0 + h
cv2.rectangle(
img,
(int(x0), int(y0)),
(int(x1), int(y1)),
hand_colors[idx % len(hand_colors)],
2,
)
return img
def vis_keypoints(img, kps, score, skeleton, filename=None, vis_dir=None, score_thr=0.4, line_width=3, circle_rad = 3, bbox=None, is_print=False):
rgb_dict = get_keypoint_rgb(skeleton)
if img.shape[0] == 3:
img = img.transpose(1,2,0)
_img = Image.fromarray(img.astype('uint8'))
draw = ImageDraw.Draw(_img)
for i in range(len(skeleton)):
joint_name = skeleton[i]['name']
pid = skeleton[i]['parent_id']
parent_joint_name = skeleton[pid]['name']
kps_i = (kps[i][0].astype(np.int32), kps[i][1].astype(np.int32))
kps_pid = (kps[pid][0].astype(np.int32), kps[pid][1].astype(np.int32))
if score[i] > score_thr and score[pid] > score_thr and pid != -1:
draw.line([(kps[i][0], kps[i][1]), (kps[pid][0], kps[pid][1])], fill=rgb_dict[parent_joint_name], width=line_width)
if score[i] > score_thr:
draw.ellipse((kps[i][0]-circle_rad, kps[i][1]-circle_rad, kps[i][0]+circle_rad, kps[i][1]+circle_rad), fill=rgb_dict[joint_name])
if score[pid] > score_thr and pid != -1:
draw.ellipse((kps[pid][0]-circle_rad, kps[pid][1]-circle_rad, kps[pid][0]+circle_rad, kps[pid][1]+circle_rad), fill=rgb_dict[parent_joint_name])
if bbox is not None:
_img = draw_bbox_on_image(np.asarray(_img), bbox)
_img = Image.fromarray(_img)
if vis_dir is not None:
_img.save(osp.join(vis_dir, filename))
if is_print: print(f"save vis image to {osp.join(vis_dir, filename)}")
return np.asarray(_img)
def fig2img(fig):
fig.canvas.draw()
data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
return data
def vis_3d_keypoints(kps_3d, score, skeleton, filename=None, vis_dir=None, score_thr=0.4, line_width=3, circle_rad=3, is_print=False):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
white = (1.0, 1.0, 1.0, 0.0)
ax.xaxis.set_pane_color(white)
ax.yaxis.set_pane_color(white)
ax.zaxis.set_pane_color(white)
ax.tick_params('x', labelbottom = False)
ax.tick_params('y', labelleft = False)
ax.tick_params('z', labelleft = False)
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
rgb_dict = get_keypoint_rgb(skeleton)
for i in range(len(skeleton)):
joint_name = skeleton[i]['name']
pid = skeleton[i]['parent_id']
parent_joint_name = skeleton[pid]['name']
x = np.array([kps_3d[i,0], kps_3d[pid,0]])
y = np.array([kps_3d[i,1], kps_3d[pid,1]])
z = np.array([kps_3d[i,2], kps_3d[pid,2]])
if score[i] > score_thr and score[pid] > score_thr and pid != -1:
ax.plot(x, z, -y, c = np.array(rgb_dict[parent_joint_name])/255., linewidth = line_width)
if score[i] > score_thr:
ax.scatter(kps_3d[i,0], kps_3d[i,2], -kps_3d[i,1], c = np.array(rgb_dict[joint_name]).reshape(1,3)/255., marker='o')
if score[pid] > score_thr and pid != -1:
ax.scatter(kps_3d[pid,0], kps_3d[pid,2], -kps_3d[pid,1], c = np.array(rgb_dict[parent_joint_name]).reshape(1,3)/255., marker='o')
img_array = None
if vis_dir is not None:
fig.savefig(osp.join(vis_dir, filename), dpi=fig.dpi)
if is_print: print(f"save vis image to {osp.join(vis_dir, filename)}")
else:
img_array = fig2img(fig)
img_array = img_array[:, :, :3]
img_array = img_array[:, :, ::-1]
plt.close()
return img_array
| assemblyhands-toolkit-main | src/common/utils/vis.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import cv2
import numpy as np
from PIL import Image
from src import cfg
from src.common.utils.transforms import world2cam, cam2pixel, pixel2cam, world2cam_assemblyhands
import random
import math
def load_img(path, order='RGB'):
# load
img = cv2.imread(path, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
if not isinstance(img, np.ndarray):
raise IOError("Fail to read %s" % path)
if order=='RGB':
img = img[:,:,::-1].copy()
img = img.astype(np.float32)
return img
def update_params_after_crop(bbox, pts_2d, joint_world, joint_valid, retval_camera, img_size, dataset='assemblyhands'):
(img_h, img_w) = img_size
x0, y0, w, h = bbox
box_l = max(int(max(w, h)), 100) # at least 100px
x0 = int((x0 + (x0 + w)) * 0.5 - box_l * 0.5)
y0 = int((y0 + (y0 + h)) * 0.5 - box_l * 0.5)
x1, y1 = x0 + box_l, y0 + box_l
# change coordinates
bbox = [0, 0, box_l, box_l]
pts_2d[:, 0] -= x0
pts_2d[:, 1] -= y0
# 2d visibility check
joint_valid = (joint_valid > 0 & (pts_2d[:, :2].max(axis=1) < box_l))
joint_valid = joint_valid.astype(int)
retval_camera.update_after_crop([x0, y0, x1, y1])
campos, camrot, focal, princpt = retval_camera.get_params()
if dataset == 'assemblyhands':
joint_cam = world2cam_assemblyhands(joint_world, camrot, campos)
else:
joint_cam = world2cam(joint_world.transpose(1,0), camrot, campos.reshape(3,1)).transpose(1,0)
return (x0, y0, x1, y1), bbox, pts_2d, joint_cam, joint_valid, retval_camera
def load_crop_img(path, bbox, pts_2d, joint_world, joint_valid, retval_camera, order='RGB'):
img = cv2.imread(path, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
if not isinstance(img, np.ndarray):
raise IOError("Fail to read %s" % path)
if order=='RGB':
img = img[:,:,::-1].copy()
img = img.astype(np.float32)
(x0, y0, x1, y1), bbox, pts_2d, joint_cam, joint_valid, retval_camera = update_params_after_crop(bbox, pts_2d, joint_world, joint_valid, retval_camera, img.shape[:2])
assert sum(joint_valid) >= 10, f"sum(joint_valid): {sum(joint_valid)}, path: {path}, joint_valid: {joint_valid}"
# crop
img = Image.fromarray(img.astype(np.uint8))
img = img.crop([x0, y0, x1, y1])
img = np.asarray(img)
assert img.shape[0] > 50 and img.shape[1] > 50, f"img.shape: {img.shape}, path: {path}, bbox: {x0}, {y0}, {bbox[2]}"
return img, bbox, pts_2d, joint_cam, joint_valid, retval_camera
def load_skeleton(path, joint_num):
# load joint_world info (name, parent_id)
skeleton = [{} for _ in range(joint_num)]
with open(path) as fp:
for line in fp:
if line[0] == '#': continue
splitted = line.split(' ')
joint_name, joint_id, joint_parent_id = splitted
joint_id, joint_parent_id = int(joint_id), int(joint_parent_id)
skeleton[joint_id]['name'] = joint_name
skeleton[joint_id]['parent_id'] = joint_parent_id
# save child_id
for i in range(len(skeleton)):
joint_child_id = []
for j in range(len(skeleton)):
if skeleton[j]['parent_id'] == i:
joint_child_id.append(j)
skeleton[i]['child_id'] = joint_child_id
return skeleton
def get_aug_config():
trans_factor = 0.15
scale_factor = 0.25
rot_factor = 45
color_factor = 0.2
trans = [np.random.uniform(-trans_factor, trans_factor), np.random.uniform(-trans_factor, trans_factor)]
scale = np.clip(np.random.randn(), -1.0, 1.0) * scale_factor + 1.0
rot = np.clip(np.random.randn(), -2.0,
2.0) * rot_factor if random.random() <= 0.6 else 0
do_flip = random.random() <= 0.5
c_up = 1.0 + color_factor
c_low = 1.0 - color_factor
color_scale = np.array([random.uniform(c_low, c_up), random.uniform(c_low, c_up), random.uniform(c_low, c_up)])
return trans, scale, rot, do_flip, color_scale
def augmentation(img, bbox, joint_coord, joint_valid, hand_type, mode, joint_type, no_aug=False):
img = img.copy()
joint_coord = joint_coord.copy()
hand_type = hand_type.copy()
original_img_shape = img.shape
joint_num = len(joint_coord)
if mode == 'train' and not no_aug:
trans, scale, rot, do_flip, color_scale = get_aug_config()
else:
trans, scale, rot, do_flip, color_scale = [0,0], 1.0, 0.0, False, np.array([1,1,1])
# trans, scale, rot, do_flip, color_scale = get_aug_config()
bbox[0] = bbox[0] + bbox[2] * trans[0]
bbox[1] = bbox[1] + bbox[3] * trans[1]
img, trans, inv_trans = generate_patch_image(img, bbox, do_flip, scale, rot, cfg.input_img_shape)
img = np.clip(img * color_scale[None,None,:], 0, 255)
if do_flip:
joint_coord[:,0] = original_img_shape[1] - joint_coord[:,0] - 1
joint_coord[joint_type['right']], joint_coord[joint_type['left']] = joint_coord[joint_type['left']].copy(), joint_coord[joint_type['right']].copy()
joint_valid[joint_type['right']], joint_valid[joint_type['left']] = joint_valid[joint_type['left']].copy(), joint_valid[joint_type['right']].copy()
hand_type[0], hand_type[1] = hand_type[1].copy(), hand_type[0].copy()
for i in range(joint_num):
joint_coord[i,:2] = trans_point2d(joint_coord[i,:2], trans)
joint_valid[i] = joint_valid[i] * (joint_coord[i,0] >= 0) * (joint_coord[i,0] < cfg.input_img_shape[1]) * (joint_coord[i,1] >= 0) * (joint_coord[i,1] < cfg.input_img_shape[0])
return img, joint_coord, joint_valid, hand_type, inv_trans
def transform_input_to_output_space(joint_coord, joint_valid, rel_root_depth, root_valid, root_joint_idx, joint_type):
# transform to output heatmap space
joint_coord = joint_coord.copy()
joint_valid = joint_valid.copy()
joint_coord[:,0] = joint_coord[:,0] / cfg.input_img_shape[1] * cfg.output_hm_shape[2]
joint_coord[:,1] = joint_coord[:,1] / cfg.input_img_shape[0] * cfg.output_hm_shape[1]
joint_coord[joint_type['right'],2] = joint_coord[joint_type['right'],2] - joint_coord[root_joint_idx['right'],2]
joint_coord[joint_type['left'],2] = joint_coord[joint_type['left'],2] - joint_coord[root_joint_idx['left'],2]
joint_coord[:,2] = (joint_coord[:,2] / (cfg.bbox_3d_size/2) + 1)/2. * cfg.output_hm_shape[0]
joint_valid = joint_valid * ((joint_coord[:,2] >= 0) * (joint_coord[:,2] < cfg.output_hm_shape[0])).astype(np.float32)
rel_root_depth = (rel_root_depth / (cfg.bbox_3d_size_root/2) + 1)/2. * cfg.output_root_hm_shape
root_valid = root_valid * ((rel_root_depth >= 0) * (rel_root_depth < cfg.output_root_hm_shape)).astype(np.float32)
return joint_coord, joint_valid, rel_root_depth, root_valid
def get_bbox(joint_img, joint_valid):
x_img = joint_img[:,0][joint_valid==1]
y_img = joint_img[:,1][joint_valid==1]
xmin = min(x_img)
ymin = min(y_img)
xmax = max(x_img)
ymax = max(y_img)
x_center = (xmin+xmax)/2.
width = xmax-xmin
xmin = x_center - 0.5*width*1.2
xmax = x_center + 0.5*width*1.2
y_center = (ymin+ymax)/2.
height = ymax-ymin
ymin = y_center - 0.5*height*1.2
ymax = y_center + 0.5*height*1.2
bbox = np.array([xmin, ymin, xmax-xmin, ymax-ymin]).astype(np.float32)
return bbox
def process_bbox(bbox, original_img_shape, scale=1.25):
# aspect ratio preserving bbox
w = bbox[2]
h = bbox[3]
c_x = bbox[0] + w/2.
c_y = bbox[1] + h/2.
aspect_ratio = cfg.input_img_shape[1]/cfg.input_img_shape[0]
if w > aspect_ratio * h:
h = w / aspect_ratio
elif w < aspect_ratio * h:
w = h * aspect_ratio
bbox[2] = w * scale
bbox[3] = h * scale
bbox[0] = c_x - bbox[2]/2.
bbox[1] = c_y - bbox[3]/2.
return bbox
def generate_patch_image(cvimg, bbox, do_flip, scale, rot, out_shape):
img = cvimg.copy()
img_height, img_width, img_channels = img.shape
bb_c_x = float(bbox[0] + 0.5*bbox[2])
bb_c_y = float(bbox[1] + 0.5*bbox[3])
bb_width = float(bbox[2])
bb_height = float(bbox[3])
if do_flip:
img = img[:, ::-1, :]
bb_c_x = img_width - bb_c_x - 1
trans = gen_trans_from_patch_cv(bb_c_x, bb_c_y, bb_width, bb_height, out_shape[1], out_shape[0], scale, rot)
try:
img_patch = cv2.warpAffine(img, trans, (int(out_shape[1]), int(out_shape[0])), flags=cv2.INTER_LINEAR)
except:
print(img.shape, (int(out_shape[1]), int(out_shape[0])))
raise Exception()
img_patch = img_patch.astype(np.float32)
inv_trans = gen_trans_from_patch_cv(bb_c_x, bb_c_y, bb_width, bb_height, out_shape[1], out_shape[0], scale, rot, inv=True)
return img_patch, trans, inv_trans
def rotate_2d(pt_2d, rot_rad):
x = pt_2d[0]
y = pt_2d[1]
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
xx = x * cs - y * sn
yy = x * sn + y * cs
return np.array([xx, yy], dtype=np.float32)
def gen_trans_from_patch_cv(c_x, c_y, src_width, src_height, dst_width, dst_height, scale, rot, inv=False):
# augment size with scale
src_w = src_width * scale
src_h = src_height * scale
src_center = np.array([c_x, c_y], dtype=np.float32)
# augment rotation
rot_rad = np.pi * rot / 180
src_downdir = rotate_2d(np.array([0, src_h * 0.5], dtype=np.float32), rot_rad)
src_rightdir = rotate_2d(np.array([src_w * 0.5, 0], dtype=np.float32), rot_rad)
dst_w = dst_width
dst_h = dst_height
dst_center = np.array([dst_w * 0.5, dst_h * 0.5], dtype=np.float32)
dst_downdir = np.array([0, dst_h * 0.5], dtype=np.float32)
dst_rightdir = np.array([dst_w * 0.5, 0], dtype=np.float32)
src = np.zeros((3, 2), dtype=np.float32)
src[0, :] = src_center
src[1, :] = src_center + src_downdir
src[2, :] = src_center + src_rightdir
dst = np.zeros((3, 2), dtype=np.float32)
dst[0, :] = dst_center
dst[1, :] = dst_center + dst_downdir
dst[2, :] = dst_center + dst_rightdir
if inv:
trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
else:
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
trans = trans.astype(np.float32)
return trans
def trans_point2d(pt_2d, trans):
src_pt = np.array([pt_2d[0], pt_2d[1], 1.]).T
dst_pt = np.dot(trans, src_pt)
return dst_pt[0:2]
| assemblyhands-toolkit-main | src/common/utils/preprocessing.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from src import cfg
import math
class JointHeatmapLoss(nn.Module):
def __ini__(self):
super(JointHeatmapLoss, self).__init__()
def forward(self, joint_out, joint_gt, joint_valid):
loss = (joint_out - joint_gt) ** 2 * joint_valid[:, :, None, None, None]
return loss
class HandTypeLoss(nn.Module):
def __init__(self):
super(HandTypeLoss, self).__init__()
def forward(self, hand_type_out, hand_type_gt, hand_type_valid):
loss = F.binary_cross_entropy(hand_type_out, hand_type_gt, reduction="none")
loss = loss.mean(1)
loss = loss * hand_type_valid
return loss
class RelRootDepthLoss(nn.Module):
def __init__(self):
super(RelRootDepthLoss, self).__init__()
def forward(self, root_depth_out, root_depth_gt, root_valid):
loss = torch.abs(root_depth_out - root_depth_gt) * root_valid
return loss
| assemblyhands-toolkit-main | src/common/nets/loss.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import os.path as osp
from src import cfg
import torch
import torch.nn as nn
from torchvision.models.resnet import BasicBlock, Bottleneck
from torchvision.models.resnet import model_urls
class ResNetBackbone(nn.Module):
def __init__(self, resnet_type):
resnet_spec = {
18: (BasicBlock, [2, 2, 2, 2], [64, 64, 128, 256, 512], "resnet18"),
34: (BasicBlock, [3, 4, 6, 3], [64, 64, 128, 256, 512], "resnet34"),
50: (Bottleneck, [3, 4, 6, 3], [64, 256, 512, 1024, 2048], "resnet50"),
101: (Bottleneck, [3, 4, 23, 3], [64, 256, 512, 1024, 2048], "resnet101"),
152: (Bottleneck, [3, 8, 36, 3], [64, 256, 512, 1024, 2048], "resnet152"),
}
block, layers, channels, name = resnet_spec[resnet_type]
self.name = name
self.inplanes = 64
super(ResNetBackbone, self).__init__()
self.conv1 = nn.Conv2d(
3, 64, kernel_size=7, stride=2, padding=3, bias=False
) # RGB
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
for m in self.modules():
if isinstance(m, nn.Conv2d):
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
nn.init.normal_(m.weight, mean=0, std=0.001)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(
self.inplanes,
planes * block.expansion,
kernel_size=1,
stride=stride,
bias=False,
),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
return x
def init_weights(self):
org_resnet = torch.utils.model_zoo.load_url(model_urls[self.name])
# drop orginal resnet fc layer, add 'None' in case of no fc layer, that will raise error
org_resnet.pop("fc.weight", None)
org_resnet.pop("fc.bias", None)
self.load_state_dict(org_resnet)
print("Initialize resnet from model zoo")
| assemblyhands-toolkit-main | src/common/nets/resnet.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import math
from src import cfg
def make_linear_layers(feat_dims, relu_final=True):
layers = []
for i in range(len(feat_dims) - 1):
layers.append(nn.Linear(feat_dims[i], feat_dims[i + 1]))
# Do not use ReLU for final estimation
if i < len(feat_dims) - 2 or (i == len(feat_dims) - 2 and relu_final):
layers.append(nn.ReLU(inplace=True))
return nn.Sequential(*layers)
def make_conv_layers(feat_dims, kernel=3, stride=1, padding=1, bnrelu_final=True):
layers = []
for i in range(len(feat_dims) - 1):
layers.append(
nn.Conv2d(
in_channels=feat_dims[i],
out_channels=feat_dims[i + 1],
kernel_size=kernel,
stride=stride,
padding=padding,
)
)
# Do not use BN and ReLU for final estimation
if i < len(feat_dims) - 2 or (i == len(feat_dims) - 2 and bnrelu_final):
layers.append(nn.BatchNorm2d(feat_dims[i + 1]))
layers.append(nn.ReLU(inplace=True))
return nn.Sequential(*layers)
def make_deconv_layers(feat_dims, bnrelu_final=True):
layers = []
for i in range(len(feat_dims) - 1):
layers.append(
nn.ConvTranspose2d(
in_channels=feat_dims[i],
out_channels=feat_dims[i + 1],
kernel_size=4,
stride=2,
padding=1,
output_padding=0,
bias=False,
)
)
# Do not use BN and ReLU for final estimation
if i < len(feat_dims) - 2 or (i == len(feat_dims) - 2 and bnrelu_final):
layers.append(nn.BatchNorm2d(feat_dims[i + 1]))
layers.append(nn.ReLU(inplace=True))
return nn.Sequential(*layers)
class Interpolate(nn.Module):
def __init__(self, scale_factor, mode):
super(Interpolate, self).__init__()
self.interp = F.interpolate
self.scale_factor = scale_factor
self.mode = mode
def forward(self, x):
x = self.interp(
x, scale_factor=self.scale_factor, mode=self.mode, align_corners=False
)
return x
def make_upsample_layers(feat_dims, bnrelu_final=True):
layers = []
for i in range(len(feat_dims) - 1):
layers.append(Interpolate(2, "bilinear"))
layers.append(
nn.Conv2d(
in_channels=feat_dims[i],
out_channels=feat_dims[i + 1],
kernel_size=3,
stride=1,
padding=1,
)
)
# Do not use BN and ReLU for final estimation
if i < len(feat_dims) - 2 or (i == len(feat_dims) - 2 and bnrelu_final):
layers.append(nn.BatchNorm2d(feat_dims[i + 1]))
layers.append(nn.ReLU(inplace=True))
return nn.Sequential(*layers)
class ResBlock(nn.Module):
def __init__(self, in_feat, out_feat):
super(ResBlock, self).__init__()
self.in_feat = in_feat
self.out_feat = out_feat
self.conv = make_conv_layers([in_feat, out_feat, out_feat], bnrelu_final=False)
self.bn = nn.BatchNorm2d(out_feat)
if self.in_feat != self.out_feat:
self.shortcut_conv = nn.Conv2d(
in_feat, out_feat, kernel_size=1, stride=1, padding=0
)
self.shortcut_bn = nn.BatchNorm2d(out_feat)
def forward(self, input):
x = self.bn(self.conv(input))
if self.in_feat != self.out_feat:
x = F.relu(x + self.shortcut_bn(self.shortcut_conv(input)))
else:
x = F.relu(x + input)
return x
def make_conv3d_layers(feat_dims, kernel=3, stride=1, padding=1, bnrelu_final=True):
layers = []
for i in range(len(feat_dims) - 1):
layers.append(
nn.Conv3d(
in_channels=feat_dims[i],
out_channels=feat_dims[i + 1],
kernel_size=kernel,
stride=stride,
padding=padding,
)
)
# Do not use BN and ReLU for final estimation
if i < len(feat_dims) - 2 or (i == len(feat_dims) - 2 and bnrelu_final):
layers.append(nn.BatchNorm3d(feat_dims[i + 1]))
layers.append(nn.ReLU(inplace=True))
return nn.Sequential(*layers)
def make_deconv3d_layers(feat_dims, bnrelu_final=True):
layers = []
for i in range(len(feat_dims) - 1):
layers.append(
nn.ConvTranspose3d(
in_channels=feat_dims[i],
out_channels=feat_dims[i + 1],
kernel_size=4,
stride=2,
padding=1,
output_padding=0,
bias=False,
)
)
# Do not use BN and ReLU for final estimation
if i < len(feat_dims) - 2 or (i == len(feat_dims) - 2 and bnrelu_final):
layers.append(nn.BatchNorm3d(feat_dims[i + 1]))
layers.append(nn.ReLU(inplace=True))
return nn.Sequential(*layers)
| assemblyhands-toolkit-main | src/common/nets/layer.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torch.nn as nn
from torch.nn import functional as F
from src import cfg
from src.common.nets.layer import (
make_linear_layers,
make_conv_layers,
make_deconv_layers,
make_upsample_layers,
)
from src.common.nets.resnet import ResNetBackbone
import math
class BackboneNet(nn.Module):
def __init__(self):
super(BackboneNet, self).__init__()
self.resnet = ResNetBackbone(cfg.resnet_type)
def init_weights(self):
self.resnet.init_weights()
def forward(self, img):
img_feat = self.resnet(img)
return img_feat
class PoseNet(nn.Module):
def __init__(self, joint_num):
super(PoseNet, self).__init__()
self.joint_num = joint_num # single hand
self.joint_deconv_1 = make_deconv_layers([2048, 256, 256, 256])
self.joint_conv_1 = make_conv_layers(
[256, self.joint_num * cfg.output_hm_shape[0]],
kernel=1,
stride=1,
padding=0,
bnrelu_final=False,
)
self.joint_deconv_2 = make_deconv_layers([2048, 256, 256, 256])
self.joint_conv_2 = make_conv_layers(
[256, self.joint_num * cfg.output_hm_shape[0]],
kernel=1,
stride=1,
padding=0,
bnrelu_final=False,
)
self.root_fc = make_linear_layers(
[2048, 512, cfg.output_root_hm_shape], relu_final=False
)
self.hand_fc = make_linear_layers([2048, 512, 2], relu_final=False)
def soft_argmax_1d(self, heatmap1d):
heatmap1d = F.softmax(heatmap1d, 1)
accu = (
heatmap1d * torch.arange(cfg.output_root_hm_shape).float().cuda()[None, :]
)
coord = accu.sum(dim=1)
return coord
def forward(self, img_feat):
joint_img_feat_1 = self.joint_deconv_1(img_feat)
joint_heatmap3d_1 = self.joint_conv_1(joint_img_feat_1).view(
-1,
self.joint_num,
cfg.output_hm_shape[0],
cfg.output_hm_shape[1],
cfg.output_hm_shape[2],
)
joint_img_feat_2 = self.joint_deconv_2(img_feat)
joint_heatmap3d_2 = self.joint_conv_2(joint_img_feat_2).view(
-1,
self.joint_num,
cfg.output_hm_shape[0],
cfg.output_hm_shape[1],
cfg.output_hm_shape[2],
)
joint_heatmap3d = torch.cat((joint_heatmap3d_1, joint_heatmap3d_2), 1)
img_feat_gap = F.avg_pool2d(
img_feat, (img_feat.shape[2], img_feat.shape[3])
).view(-1, 2048)
root_heatmap1d = self.root_fc(img_feat_gap)
root_depth = self.soft_argmax_1d(root_heatmap1d).view(-1, 1)
hand_type = torch.sigmoid(self.hand_fc(img_feat_gap))
return joint_heatmap3d, root_depth, hand_type
| assemblyhands-toolkit-main | src/common/nets/module.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import os.path as osp
import numpy as np
from src.common.utils.dir import add_pypath, make_folder
class BaseConfig(object):
def __init__(self):
"""
Base config for model and heatmap generation
"""
## input, output
self.input_img_shape = (256, 256)
self.output_hm_shape = (64, 64, 64) # (depth, height, width)
self.sigma = 2.5
self.bbox_3d_size = 400 # depth axis
self.bbox_3d_size_root = 400 # depth axis
self.output_root_hm_shape = 64 # depth axis
## model
self.resnet_type = 50 # 18, 34, 50, 101, 152
def print_config(self):
"""
Print configuration
"""
print(">>> Configuration:")
for key, value in self.__dict__.items():
print(f"{key}: {value}")
class Config(BaseConfig):
def __init__(self, dataset="InterHand2.6M"):
super(Config, self).__init__()
## dataset
self.dataset = dataset
## training config
if dataset in ("InterHand2.6M", "AssemblyHands-Ego"):
self.lr_dec_epoch = [15, 17]
else:
self.lr_dec_epoch = [45, 47]
if dataset in ("InterHand2.6M", "AssemblyHands-Ego"):
self.end_epoch = 20
else:
self.end_epoch = 50
self.lr = 1e-4
self.lr_dec_factor = 10
self.train_batch_size = 8 # 16
## testing config
self.test_batch_size = 8 # 32
if dataset == "InterHand2.6M":
self.trans_test = "gt" # gt, rootnet
self.bbox_scale = 1.25
elif dataset == "AssemblyHands-Ego":
self.trans_test = "gt"
self.bbox_scale = 1.75
else:
self.trans_test = "gt"
## directory
self.cur_dir = osp.dirname(os.path.abspath(__file__))
assert self.cur_dir.endswith("main"), f"cur_dir: {self.cur_dir}"
self.root_dir = self.cur_dir.rsplit("/src", 1)[0]
assert self.root_dir.endswith(
"assemblyhands-toolkit"
), f"root_dir: {self.root_dir}"
self.src_dir = osp.join(self.root_dir, "src")
self.data_dir = osp.join(
self.root_dir, "data", dataset.lower().rsplit("-", 1)[0]
)
self.dataset_dir = osp.join(self.src_dir, "dataset")
self.output_dir = osp.join(self.root_dir, f"output/{dataset.lower()}")
self.model_dir = osp.join(self.output_dir, "model_dump")
self.vis_dir = osp.join(self.output_dir, "vis")
self.log_dir = osp.join(self.output_dir, "log")
self.result_dir = osp.join(self.output_dir, "result")
print(">>> data_dir: {}".format(self.data_dir))
print(">>> output_dir: {}".format(self.output_dir))
## others
self.num_thread = 4 # 40
self.gpu_ids = "0"
self.num_gpus = 1
self.continue_train = False
self.print_freq = 500
# set pathes
add_pypath(osp.join(self.dataset_dir))
print(">>> dataset_dir: {}/{}".format(self.dataset_dir, self.dataset))
add_pypath(osp.join(self.dataset_dir, self.dataset))
make_folder(self.model_dir)
make_folder(self.vis_dir)
make_folder(self.log_dir)
make_folder(self.result_dir)
def set_args(self, gpu_ids, continue_train=False):
self.gpu_ids = gpu_ids
self.num_gpus = len(self.gpu_ids.split(","))
self.continue_train = continue_train
os.environ["CUDA_VISIBLE_DEVICES"] = self.gpu_ids
print(">>> Using GPU: {}".format(self.gpu_ids))
# cfg = Config()
base_cfg = BaseConfig()
| assemblyhands-toolkit-main | src/main/config.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from tqdm import tqdm
import numpy as np
import cv2
import torch
from src.main.config import Config
import torch.backends.cudnn as cudnn
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--gpu", type=str, dest="gpu_ids", default="0")
parser.add_argument("--test_epoch", type=str, dest="test_epoch", default="20")
parser.add_argument("--test_set", type=str, dest="test_set")
parser.add_argument("--vis", action="store_true")
parser.add_argument("--vis_freq", type=int, dest="vis_freq", default=10)
parser.add_argument("--dataset", type=str, dest="dataset", default="InterHand2.6M")
args = parser.parse_args()
if "-" in args.gpu_ids:
gpus = args.gpu_ids.split("-")
gpus[0] = int(gpus[0])
gpus[1] = int(gpus[1]) + 1
args.gpu_ids = ",".join(map(lambda x: str(x), list(range(*gpus))))
return args
def main(cfg, args):
if cfg.dataset == "InterHand2.6M" or cfg.dataset.startswith("AssemblyHands"):
assert args.test_set, "Test set is required. Select one of test/val"
else:
args.test_set = "test"
checkpoint_dir = "checkpoints"
tester = Tester(cfg, args.test_epoch)
tester._make_batch_generator(args.test_set)
tester._make_model(checkpoint_dir)
preds = {"joint_coord": [], "rel_root_depth": [], "hand_type": [], "inv_trans": []}
with torch.no_grad():
for itr, (inputs, targets, meta_info) in enumerate(
tqdm(tester.batch_generator)
):
# forward
out = tester.model(inputs, targets, meta_info, "test")
joint_coord_out = out["joint_coord"].cpu().numpy()
rel_root_depth_out = out["rel_root_depth"].cpu().numpy()
hand_type_out = out["hand_type"].cpu().numpy()
inv_trans = out["inv_trans"].cpu().numpy()
preds["joint_coord"].append(joint_coord_out)
preds["rel_root_depth"].append(rel_root_depth_out)
preds["hand_type"].append(hand_type_out)
preds["inv_trans"].append(inv_trans)
if args.vis and itr % args.vis_freq == 0:
raise NotImplementedError()
# evaluate
preds = {k: np.concatenate(v) for k, v in preds.items()}
tester._evaluate(preds)
if __name__ == "__main__":
args = parse_args()
cfg = Config(dataset=args.dataset)
cfg.set_args(args.gpu_ids)
cudnn.benchmark = True
from src.common.base import Tester
from src.common.utils.vis import vis_keypoints
from src.common.utils.transforms import flip
main(cfg, args)
| assemblyhands-toolkit-main | src/main/test.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torch.nn as nn
import torch.nn.functional as F
from src.common.nets.module import BackboneNet, PoseNet
from src.common.nets.loss import JointHeatmapLoss, HandTypeLoss, RelRootDepthLoss
from src import cfg
import math
class Model(nn.Module):
def __init__(self, backbone_net, pose_net):
super(Model, self).__init__()
# modules
self.backbone_net = backbone_net
self.pose_net = pose_net
# loss functions
self.joint_heatmap_loss = JointHeatmapLoss()
self.rel_root_depth_loss = RelRootDepthLoss()
self.hand_type_loss = HandTypeLoss()
def render_gaussian_heatmap(self, joint_coord):
x = torch.arange(cfg.output_hm_shape[2])
y = torch.arange(cfg.output_hm_shape[1])
z = torch.arange(cfg.output_hm_shape[0])
zz, yy, xx = torch.meshgrid(z, y, x)
xx = xx[None, None, :, :, :].cuda().float()
yy = yy[None, None, :, :, :].cuda().float()
zz = zz[None, None, :, :, :].cuda().float()
x = joint_coord[:, :, 0, None, None, None]
y = joint_coord[:, :, 1, None, None, None]
z = joint_coord[:, :, 2, None, None, None]
heatmap = torch.exp(
-(((xx - x) / cfg.sigma) ** 2) / 2
- (((yy - y) / cfg.sigma) ** 2) / 2
- (((zz - z) / cfg.sigma) ** 2) / 2
)
heatmap = heatmap * 255
return heatmap
def forward(self, inputs, targets, meta_info, mode):
input_img = inputs["img"]
batch_size = input_img.shape[0]
img_feat = self.backbone_net(input_img)
joint_heatmap_out, rel_root_depth_out, hand_type = self.pose_net(img_feat)
if mode.startswith("train"):
target_joint_heatmap = self.render_gaussian_heatmap(targets["joint_coord"])
loss = {}
loss["joint_heatmap"] = self.joint_heatmap_loss(
joint_heatmap_out, target_joint_heatmap, meta_info["joint_valid"]
)
loss["rel_root_depth"] = self.rel_root_depth_loss(
rel_root_depth_out, targets["rel_root_depth"], meta_info["root_valid"]
)
loss["hand_type"] = self.hand_type_loss(
hand_type, targets["hand_type"], meta_info["hand_type_valid"]
)
if mode == "train":
return loss
if mode == "test" or mode == "train_with_preds":
out = {}
val_z, idx_z = torch.max(joint_heatmap_out, 2)
val_zy, idx_zy = torch.max(val_z, 2)
val_zyx, joint_x = torch.max(val_zy, 2)
joint_x = joint_x[:, :, None]
joint_y = torch.gather(idx_zy, 2, joint_x)
joint_z = torch.gather(
idx_z, 2, joint_y[:, :, :, None].repeat(1, 1, 1, cfg.output_hm_shape[1])
)[:, :, 0, :]
joint_z = torch.gather(joint_z, 2, joint_x)
joint_coord_out = torch.cat((joint_x, joint_y, joint_z), 2).float()
out["joint_coord"] = joint_coord_out
out["rel_root_depth"] = rel_root_depth_out
out["hand_type"] = hand_type
if "inv_trans" in meta_info:
out["inv_trans"] = meta_info["inv_trans"]
if "joint_coord" in targets:
out["target_joint"] = targets["joint_coord"]
if "joint_valid" in meta_info:
out["joint_valid"] = meta_info["joint_valid"]
if "hand_type_valid" in meta_info:
out["hand_type_valid"] = meta_info["hand_type_valid"]
if mode == "test":
return out
elif mode == "train_with_preds":
return loss, out
def init_weights(m):
if type(m) == nn.ConvTranspose2d:
nn.init.normal_(m.weight, std=0.001)
elif type(m) == nn.Conv2d:
nn.init.normal_(m.weight, std=0.001)
nn.init.constant_(m.bias, 0)
elif type(m) == nn.BatchNorm2d:
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
nn.init.constant_(m.bias, 0)
def get_model(mode, joint_num):
backbone_net = BackboneNet()
pose_net = PoseNet(joint_num)
if mode == "train":
backbone_net.init_weights()
pose_net.apply(init_weights)
model = Model(backbone_net, pose_net)
return model
| assemblyhands-toolkit-main | src/main/model.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
# from config import cfg
from src.main.config import Config
import numpy as np
import torch
import torch.backends.cudnn as cudnn
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--gpu", type=str, dest="gpu_ids", default="0")
parser.add_argument("--resume_epoch", type=int, default=None)
parser.add_argument("--continue", dest="continue_train", action="store_true")
parser.add_argument("--dataset", type=str, dest="dataset", default="InterHand2.6M")
parser.add_argument("--running_eval", dest="running_eval", action="store_true")
args = parser.parse_args()
if "-" in args.gpu_ids:
gpus = args.gpu_ids.split("-")
gpus[0] = int(gpus[0])
gpus[1] = int(gpus[1]) + 1
args.gpu_ids = ",".join(map(lambda x: str(x), list(range(*gpus))))
return args
def main(cfg, args):
trainer = Trainer(cfg)
trainer._make_batch_generator()
trainer._make_model(args.resume_epoch)
# train
for epoch in range(trainer.start_epoch, cfg.end_epoch):
trainer.set_lr(epoch)
trainer.tot_timer.tic()
trainer.read_timer.tic()
preds = {
"joint_coord": [],
"rel_root_depth": [],
"hand_type": [],
"inv_trans": [],
}
for itr, (inputs, targets, meta_info) in enumerate(trainer.batch_generator):
trainer.read_timer.toc()
trainer.gpu_timer.tic()
# forward
trainer.optimizer.zero_grad()
if args.running_eval:
loss, out = trainer.model(
inputs, targets, meta_info, "train_with_preds"
)
else:
loss = trainer.model(inputs, targets, meta_info, "train")
loss = {k: loss[k].mean() for k in loss}
# backward
sum(loss[k] for k in loss).backward()
trainer.optimizer.step()
trainer.gpu_timer.toc()
if itr % cfg.print_freq == 0:
screen = [
"Epoch %02d/%02d itr %05d/%05d:"
% (epoch, cfg.end_epoch, itr, trainer.itr_per_epoch),
"lr: %g" % (trainer.get_lr()),
"speed: %.2f(%.2fs r%.2f)s/itr"
% (
trainer.tot_timer.average_time,
trainer.gpu_timer.average_time,
trainer.read_timer.average_time,
),
"%.2fh/epoch"
% (trainer.tot_timer.average_time / 3600.0 * trainer.itr_per_epoch),
]
screen += [
"%s: %.4f" % ("loss_" + k, v.detach())
for k, v in loss.items()
if v > 0
]
trainer.logger.info(" ".join(screen))
trainer.tot_timer.toc()
trainer.tot_timer.tic()
trainer.read_timer.tic()
if args.running_eval:
# set preds for evaluation
joint_coord_out = out["joint_coord"].detach().cpu().numpy()
rel_root_depth_out = out["rel_root_depth"].detach().cpu().numpy()
hand_type_out = out["hand_type"].detach().cpu().numpy()
inv_trans = out["inv_trans"].detach().cpu().numpy()
preds["joint_coord"].append(joint_coord_out)
preds["rel_root_depth"].append(rel_root_depth_out)
preds["hand_type"].append(hand_type_out)
preds["inv_trans"].append(inv_trans)
# save model
trainer.save_model(
{
"epoch": epoch,
"network": trainer.model.state_dict(),
"optimizer": trainer.optimizer.state_dict(),
},
epoch,
)
# evaluate
if args.running_eval:
preds = {k: np.concatenate(v) for k, v in preds.items()}
trainer.trainset.evaluate(preds, cfg)
if __name__ == "__main__":
# argument parse and create log
args = parse_args()
cfg = Config(dataset=args.dataset)
cfg.set_args(args.gpu_ids, args.continue_train)
cudnn.benchmark = True
from src.common.base import Trainer
main(cfg, args)
| assemblyhands-toolkit-main | src/main/train.py |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os.path
import re
import sys
import setuptools
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "crypten"))
# Read description and requirements.
with open("README.md", encoding="utf8") as f:
readme = f.read()
with open("requirements.txt") as f:
reqs = f.read()
# get version string from module
init_path = os.path.join(os.path.dirname(__file__), "crypten/__init__.py")
with open(init_path, "r") as f:
version = re.search(r"__version__ = ['\"]([^'\"]*)['\"]", f.read(), re.M).group(1)
# Set key package information.
DISTNAME = "crypten"
DESCRIPTION = "CrypTen: secure machine learning in PyTorch."
LONG_DESCRIPTION = readme
AUTHOR = "Facebook AI Research"
LICENSE = "MIT licensed, as found in the LICENSE file"
REQUIREMENTS = (reqs.strip().split("\n"),)
VERSION = version
# Run installer.
if __name__ == "__main__":
if sys.version_info < (3, 7):
sys.exit("Sorry, Python >=3.7 is required for CrypTen.")
setuptools.setup(
name=DISTNAME,
install_requires=REQUIREMENTS,
packages=setuptools.find_packages(),
dependency_links=[],
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type="text/markdown",
url="https://github.com/facebookresearch/CrypTen",
author=AUTHOR,
license=LICENSE,
tests_require=["pytest"],
data_files=[("configs", ["configs/default.yaml"])],
)
| CrypTen-main | setup.py |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Based on
https://github.com/facebookresearch/CrypTen/blob/master/examples/multiprocess_launcher.py
"""
import logging
import multiprocessing
import os
import uuid
import crypten
class MultiProcessLauncher:
# run_process_fn will be run in subprocesses.
def __init__(self, world_size, run_process_fn, fn_args=None):
env = os.environ.copy()
env["WORLD_SIZE"] = str(world_size)
multiprocessing.set_start_method("spawn")
# Use random file so multiple jobs can be run simultaneously
INIT_METHOD = "file:///tmp/crypten-rendezvous-{}".format(uuid.uuid1())
env["RENDEZVOUS"] = INIT_METHOD
self.processes = []
for rank in range(world_size):
process_name = "process " + str(rank)
process = multiprocessing.Process(
target=self.__class__._run_process,
name=process_name,
args=(rank, world_size, env, run_process_fn, fn_args),
)
self.processes.append(process)
if crypten.mpc.ttp_required():
ttp_process = multiprocessing.Process(
target=self.__class__._run_process,
name="TTP",
args=(
world_size,
world_size,
env,
crypten.mpc.provider.TTPServer,
None,
),
)
self.processes.append(ttp_process)
@classmethod
def _run_process(cls, rank, world_size, env, run_process_fn, fn_args):
for env_key, env_value in env.items():
os.environ[env_key] = env_value
os.environ["RANK"] = str(rank)
orig_logging_level = logging.getLogger().level
logging.getLogger().setLevel(logging.INFO)
crypten.init()
logging.getLogger().setLevel(orig_logging_level)
if fn_args is None:
run_process_fn()
else:
run_process_fn(fn_args)
def start(self):
for process in self.processes:
process.start()
def join(self):
for process in self.processes:
process.join()
assert (
process.exitcode == 0
), f"{process.name} has non-zero exit code {process.exitcode}"
def terminate(self):
for process in self.processes:
process.terminate()
| CrypTen-main | pycon-workshop-2020/multiprocess_launcher.py |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
import crypten
import torch
import torchvision
from multiprocess_launcher import MultiProcessLauncher
# python 3.7 is required
assert sys.version_info[0] == 3 and sys.version_info[1] == 7, "python 3.7 is required"
# Alice is party 0
ALICE = 0
BOB = 1
class LogisticRegression(crypten.nn.Module):
def __init__(self):
super().__init__()
self.linear = crypten.nn.Linear(28 * 28, 10)
def forward(self, x):
x = x.view(-1, 28 * 28)
return self.linear(x)
def encrypt_digits():
"""Alice has images. Bob has labels"""
digits = torchvision.datasets.MNIST(
root="/tmp/data",
train=True,
transform=torchvision.transforms.ToTensor(),
download=True,
)
images, labels = take_samples(digits)
crypten.save_from_party(images, "/tmp/data/alice_images.pth", src=ALICE)
crypten.save_from_party(labels, "/tmp/data/bob_labels.pth", src=BOB)
def take_samples(digits, n_samples=100):
"""Returns images and labels based on sample size"""
images, labels = [], []
for i, digit in enumerate(digits):
if i == n_samples:
break
image, label = digit
images.append(image)
label_one_hot = torch.nn.functional.one_hot(torch.tensor(label), 10)
labels.append(label_one_hot)
images = torch.cat(images)
labels = torch.stack(labels)
return images, labels
def train_model(model, X, y, epochs=10, learning_rate=0.05):
criterion = crypten.nn.CrossEntropyLoss()
for epoch in range(epochs):
model.zero_grad()
output = model(X)
loss = criterion(output, y)
print(f"epoch {epoch} loss: {loss.get_plain_text()}")
loss.backward()
model.update_parameters(learning_rate)
return model
def jointly_train():
encrypt_digits()
alice_images_enc = crypten.load_from_party("/tmp/data/alice_images.pth", src=ALICE)
bob_labels_enc = crypten.load_from_party("/tmp/data/bob_labels.pth", src=BOB)
model = LogisticRegression().encrypt()
model = train_model(model, alice_images_enc, bob_labels_enc)
if __name__ == "__main__":
launcher = MultiProcessLauncher(2, jointly_train)
launcher.start()
launcher.join()
launcher.terminate()
| CrypTen-main | pycon-workshop-2020/training_across_parties.py |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import sys
import unittest
import crypten
import torch
from crypten.common.util import chebyshev_series
from crypten.config import cfg
from crypten.encoder import FixedPointEncoder, nearest_integer_division
def get_test_tensor(max_value=10, float=False):
"""Create simple test tensor."""
tensor = torch.tensor(list(range(max_value)), dtype=torch.long)
if float:
tensor = tensor.float()
return tensor
class TestCommon(unittest.TestCase):
"""
Test cases for common functionality.
"""
def _check(self, tensor, reference, msg):
test_passed = (tensor == reference).all().item() == 1
self.assertTrue(test_passed, msg=msg)
def test_encode_decode(self):
"""Tests tensor encoding and decoding."""
for float in [False, True]:
if float:
fpe = FixedPointEncoder(precision_bits=16)
else:
fpe = FixedPointEncoder(precision_bits=0)
tensor = get_test_tensor(float=float)
decoded = fpe.decode(fpe.encode(tensor))
self._check(
decoded,
tensor,
"Encoding/decoding a %s failed." % "float" if float else "long",
)
# Make sure encoding a subclass of CrypTensor is a no-op
cfg.mpc.provider = "TFP"
crypten.init()
tensor = get_test_tensor(float=True)
encrypted_tensor = crypten.cryptensor(tensor)
encrypted_tensor = fpe.encode(encrypted_tensor)
self._check(
encrypted_tensor.get_plain_text(),
tensor,
"Encoding an EncryptedTensor failed.",
)
# Try a few other types.
fpe = FixedPointEncoder(precision_bits=0)
for dtype in [torch.uint8, torch.int8, torch.int16]:
tensor = torch.zeros(5, dtype=dtype).random_()
decoded = fpe.decode(fpe.encode(tensor)).type(dtype)
self._check(decoded, tensor, "Encoding/decoding a %s failed." % dtype)
def test_nearest_integer_division(self):
# test without scaling:
scale = 1
reference = [[-26, -25, -7, -5, -4, -1, 0, 1, 3, 4, 5, 7, 25, 26]]
tensor = torch.tensor(reference, dtype=torch.long)
result = nearest_integer_division(tensor, scale)
self._check(
torch.tensor(result.tolist(), dtype=torch.long),
torch.tensor(reference, dtype=torch.long),
"Nearest integer division failed.",
)
# test with scaling:
scale = 4
reference = [[-6, -6, -2, -1, -1, 0, 0, 0, 1, 1, 1, 2, 6, 6]]
result = nearest_integer_division(tensor, scale)
self._check(
torch.tensor(result.tolist(), dtype=torch.long),
torch.tensor(reference, dtype=torch.long),
"Nearest integer division failed.",
)
def test_chebyshev_series(self):
"""Checks coefficients returned by chebyshev_series are correct"""
for width, terms in [(6, 10), (6, 20)]:
result = chebyshev_series(torch.tanh, width, terms)
# check shape
self.assertTrue(result.shape == torch.Size([terms]))
# check terms
self.assertTrue(result[0] < 1e-4)
self.assertTrue(torch.isclose(result[-1], torch.tensor(3.5e-2), atol=1e-1))
def test_config(self):
"""Checks setting configuartion with config manager works"""
# Set the config directly
crypten.init()
cfgs = [
"functions.exp_iterations",
"functions.max_method",
]
for _cfg in cfgs:
cfg[_cfg] = 10
self.assertTrue(cfg[_cfg] == 10, "cfg.set failed")
# Set with a context manager
with cfg.temp_override({_cfg: 3}):
self.assertTrue(cfg[_cfg] == 3, "temp_override failed to set values")
self.assertTrue(cfg[_cfg] == 10, "temp_override values persist")
if __name__ == "__main__":
unittest.main(argv=sys.argv[0])
| CrypTen-main | test/test_common.py |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import crypten.mpc.primitives.ot.baseOT as baseOT
from test.multiprocess_test_case import MultiProcessTestCase
class TestObliviousTransfer(MultiProcessTestCase):
def test_BaseOT(self):
ot = baseOT.BaseOT((self.rank + 1) % self.world_size)
if self.rank == 0:
# play the role of sender first
msg0s = ["123", "abc"]
msg1s = ["def", "123"]
ot.send(msg0s, msg1s)
# play the role of receiver later with choice bit [0, 1]
choices = [1, 0]
msgcs = ot.receive(choices)
self.assertEqual(msgcs, ["123", "123"])
else:
# play the role of receiver first with choice bit [1, 0]
choices = [0, 1]
msgcs = ot.receive(choices)
# play the role of sender later
msg0s = ["xyz", "123"]
msg1s = ["123", "uvw"]
ot.send(msg0s, msg1s)
self.assertEqual(msgcs, ["123", "123"])
if __name__ == "__main__":
unittest.main()
| CrypTen-main | test/test_baseOT.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.