Utils
The utils module contains the Discretizer and PowerTransformer classes for preparing continuous data for training, as well as a collection of miscellaneous functions for reproducible random number generation, evaluation, learning rate schedules, and serialization.
See the Utilities guide for an introduction to preparing data with the Discretizer and PowerTransformer.
ColumnParams
Discretizer
Discretizes dataframe columns into bit representations and converts them back. Columns whose names end in "_bit" are treated as single bits and are not scaled.
Source code in src/qbm/utils/discretization.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
__init__(df, n_bits, epsilon={})
Initializes the discretizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe of numerical values. |
required |
n_bits
|
int
|
Number of bits to discretize to. |
required |
epsilon
|
Mapping[str, Mapping[str, float]]
|
Optional dictionary of min/max offset values. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If n_bits is not positive, or if any non-bit column has zero range (x_max <= x_min). |
Source code in src/qbm/utils/discretization.py
bit_array_to_df(bit_array)
Converts a bit array to a dataframe of floats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bit_array
|
ndarray
|
Bit array which to convert. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Dataframe of shape (bit_array.shape[0], len(self.columns)). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the width of bit_array does not match n_bits_total. |
Source code in src/qbm/utils/discretization.py
bit_vector_to_int(bit_vector)
staticmethod
Converts a bit vector to its integer representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bit_vector
|
Sequence[int] | ndarray
|
Input bit vector. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Integer representation of the input bit vector. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any element of bit_vector is not 0 or 1. |
Source code in src/qbm/utils/discretization.py
bit_vector_to_string(bit_vector)
staticmethod
Converts a bit vector to a bit string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bit_vector
|
Sequence[int]
|
Input bit vector. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Bit string of the input bit vector. |
Source code in src/qbm/utils/discretization.py
df_to_bit_array(df)
Converts a dataframe of floats to a bit array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe which to convert. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of bits of shape (df.shape[0], self.n_bits_total). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the columns of df do not match the discretizer's columns. |
Source code in src/qbm/utils/discretization.py
discretize(x, n_bits, x_min, x_max)
staticmethod
Convert the value x into its n_bits-bit integer representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float
|
Float value to convert. |
required |
n_bits
|
int
|
Number of bits to discretize to. |
required |
x_min
|
float
|
Minimum value for scaling. |
required |
x_max
|
float
|
Maximum value for scaling. |
required |
Returns:
| Type | Description |
|---|---|
int
|
An integer representation of x. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If x is out of the range [0, 2**n_bits - 1]. |
TypeError
|
If the discretized value is not an integer. |
Source code in src/qbm/utils/discretization.py
discretize_df(df)
Convert all columns of a dataframe to bit representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe which to convert. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A discretized version of df. |
Source code in src/qbm/utils/discretization.py
int_to_bit_vector(x, n_bits)
staticmethod
Converts the integer x to an n_bits-bit bit vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
int
|
Integer value which to convert. |
required |
n_bits
|
int
|
Length of the bit vector. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
Bit vector of length n_bits. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If x is negative, if n_bits is not positive, or if x does not fit in n_bits bits. |
Source code in src/qbm/utils/discretization.py
undiscretize(x, n_bits, x_min, x_max)
staticmethod
Convert the value x into a float from its n_bits-bit integer representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float
|
Int value to convert. |
required |
n_bits
|
int
|
Number of bits to discretize to. |
required |
x_min
|
float
|
Minimum value for scaling. |
required |
x_max
|
float
|
Maximum value for scaling. |
required |
Returns:
| Type | Description |
|---|---|
float
|
A float representation of x. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If x >= 2**n_bits. |
Source code in src/qbm/utils/discretization.py
undiscretize_df(df)
Convert all columns of a dataframe to floats from bit representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe which to convert. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
An undiscretized version of df. |
Source code in src/qbm/utils/discretization.py
PowerTransformer
Transforms data points that lie beyond the provided threshold by taking their power (<1) to scale them closer to the mean.
Source code in src/qbm/utils/transformations.py
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
__init__(df, threshold=1.0, power=0.5, columns=None)
Initializes the transformer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe of data to scale. |
required |
threshold
|
float
|
Number of standard deviations from the mean beyond which to begin the scaling (applied to both tails). |
1.0
|
power
|
float
|
Power at which to scale the outlier. |
0.5
|
columns
|
Sequence[Hashable] | None
|
Optional list of columns to apply the transformation to. If no columns are provided, then all columns are transformed. |
None
|
Raises: ValueError: If power >= 1, if threshold < 1, if power <= 0, or if columns is not a subset of df.columns.
Source code in src/qbm/utils/transformations.py
inverse_transform(df, inplace=False)
Transforms the data back from the scaled space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe to scale. |
required |
inplace
|
bool
|
If True then it operates on the same dataframe, if False then it creates a copy. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Dataframe of untransformed data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a configured column is missing from df. |
Source code in src/qbm/utils/transformations.py
transform(df, inplace=False)
Transforms the data to the scaled space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe to scale. |
required |
inplace
|
bool
|
If True then it operates on the same dataframe, if False then it creates a copy. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Dataframe of transformed data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a configured column is missing from df. |
Source code in src/qbm/utils/transformations.py
compute_df_ensemble_stats(dfs)
Computes the means, medians, and standard deviations column/row-wise over the input list of dataframes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dfs
|
Sequence[DataFrame]
|
List of dataframes with identical row/column names. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, DataFrame]
|
Dictionary of dataframes with the means, medians, and standard deviations. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If dfs is empty. |
TypeError
|
If any of the computed statistics is not a DataFrame. |
Source code in src/qbm/utils/misc.py
compute_df_stats(df)
Compute the min, max, mean, median, and standard deviation of the columns in the dataframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Dataframe of the statistics. |
Source code in src/qbm/utils/misc.py
compute_kl_divergence(p_data, q_data, n_bins=32, epsilon_smooth=None, relative_smooth=False)
Computes the D_KL(p_data || q_data).
Note
this is a crude approximation of the KL divergence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p_data
|
ndarray
|
Array of data values to compute the p distribution from. |
required |
q_data
|
ndarray
|
Array of data values to compute the q distribution from. |
required |
n_bins
|
int
|
Number of bins to use in histograms. |
32
|
epsilon_smooth
|
float | None
|
Value to use with q distribution smoothing. |
None
|
relative_smooth
|
bool
|
Whether or not the smoothed values are relative to the p distribution. |
False
|
Returns:
| Type | Description |
|---|---|
float
|
D_KL(p || q). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If p_data or q_data is empty, if n_bins is not positive, or if either distribution does not sum to 1. |
Source code in src/qbm/utils/misc.py
compute_lower_tail_concentration(z, U, V)
Lower tail concentration function defined as: L(z) = P(U <= z | V <= z) = P(U <= z, V <= z) / P(U <= z) References: - https://freakonometrics.hypotheses.org/2435 - https://openacttexts.github.io/Loss-Data-Analytics/C-DependenceModel (section 14.5.4.3) - https://www.casact.org/sites/default/files/old/studynotes_venter_tails_of_copulas.pdf (section 3)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
float | ndarray
|
Tail dependence parameter (scalar or array of parameters). |
required |
U
|
ndarray
|
Input array for first variable (e.g. X.rank() / (len(X) + 1)). |
required |
V
|
ndarray
|
Input array for second variable (e.g. Y.rank() / (len(Y) + 1)). |
required |
Returns:
| Type | Description |
|---|---|
float | ndarray
|
Lower tail concentration function (scalar or array, one value per z). |
Source code in src/qbm/utils/misc.py
compute_lr_exp_decay(epoch, decay_epoch, period, base=2.0)
Exponential decay function for use in learning rate scheduling. It is relative, so one must multiply the base learning rate by the output of this function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
float | Sequence[float] | ndarray
|
Current epoch (scalar or array of epochs). |
required |
decay_epoch
|
float
|
Epoch at which to begin the decay. |
required |
period
|
float
|
Decay period. |
required |
base
|
float
|
Base number of the exponential decay. |
2.0
|
Returns:
| Type | Description |
|---|---|
float | ndarray
|
The learning rate scaling factor (scalar or array, matching the input). |
Source code in src/qbm/utils/misc.py
compute_upper_tail_concentration(z, U, V)
Upper tail concentration function defined as: R(z) = P(U > z | V > z) = P(U > z, V > z) / P(U > z) References: - https://freakonometrics.hypotheses.org/2435 - https://openacttexts.github.io/Loss-Data-Analytics/C-DependenceModel (section 14.5.4.3) - https://www.casact.org/sites/default/files/old/studynotes_venter_tails_of_copulas.pdf (section 3)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
float | ndarray
|
Tail dependence parameter (scalar or array of parameters). |
required |
U
|
ndarray
|
Input array for first variable (e.g. X.rank() / (len(X) + 1)). |
required |
V
|
ndarray
|
Input array for second variable (e.g. Y.rank() / (len(Y) + 1)). |
required |
Returns:
| Type | Description |
|---|---|
float | ndarray
|
Upper tail concentration function (scalar or array, one value per z). |
Source code in src/qbm/utils/misc.py
filter_df_on_values(df, column_values, drop_filter_columns=True)
Return a copy of the dataframe filtered conditionally on provided column values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataframe to filter. |
required |
column_values
|
Mapping[Any, Any]
|
Dictionary where the keys are column names, and the values are values on which to filter the dataframe. |
required |
drop_filter_columns
|
bool
|
If True returns a copy of the dataframe with the filtered columns dropped. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A dataframe filtered conditionally on the provided column values. |
Source code in src/qbm/utils/misc.py
get_rng(seed=None)
Creates a random number generator with the specified seed value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Seed value for the rng. |
None
|
Returns:
| Type | Description |
|---|---|
RandomState
|
Numpy RandomState object. |
Source code in src/qbm/utils/misc.py
load_artifact(file_path)
Loads a pickle or json artifact (depending on the file extension).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
Path of the file to load. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Loaded python object. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If the file has an unsupported file extension. |
Source code in src/qbm/utils/misc.py
save_artifact(artifact, file_path)
Saves a pickle or json artifact (depending on the file extension).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
artifact
|
Any
|
Python object to save. |
required |
file_path
|
str | Path
|
Path of the file to save. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file has an unsupported file extension. |