id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
168,174
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `make_gaussian_encoder` function. Write a Python function `def m...
Gin wrapper to create and apply a Gaussian encoder configurable with gin. This is a separate function so that several different models (such as BetaVAE and FactorVAE) can call this function while the gin binding always stays 'encoder.(...)'. This makes it easier to configure models and parse the results files. Args: in...
168,175
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `make_decoder` function. Write a Python function `def make_decod...
Gin wrapper to create and apply a decoder configurable with gin. This is a separate function so that several different models (such as BetaVAE and FactorVAE) can call this function while the gin binding always stays 'decoder.(...)'. This makes it easier to configure models and parse the results files. Args: latent_tens...
168,176
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `make_discriminator` function. Write a Python function `def make...
Gin wrapper to create and apply a discriminator configurable with gin. This is a separate function so that several different models (such as FactorVAE) can potentially call this function while the gin binding always stays 'discriminator.(...)'. This makes it easier to configure models and parse the results files. Args:...
168,177
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `fc_encoder` function. Write a Python function `def fc_encoder(i...
Fully connected encoder used in beta-VAE paper for the dSprites data. Based on row 1 of Table 1 on page 13 of "beta-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework" (https://openreview.net/forum?id=Sy2fzU9gl). Args: input_tensor: Input tensor of shape (batch_size, 64, 64, num_channels) to b...
168,178
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `conv_encoder` function. Write a Python function `def conv_encod...
Convolutional encoder used in beta-VAE paper for the chairs data. Based on row 3 of Table 1 on page 13 of "beta-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework" (https://openreview.net/forum?id=Sy2fzU9gl) Args: input_tensor: Input tensor of shape (batch_size, 64, 64, num_channels) to build ...
168,179
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `fc_decoder` function. Write a Python function `def fc_decoder(l...
Fully connected encoder used in beta-VAE paper for the dSprites data. Based on row 1 of Table 1 on page 13 of "beta-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework" (https://openreview.net/forum?id=Sy2fzU9gl) Args: latent_tensor: Input tensor to connect decoder to. output_shape: Shape of th...
168,180
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `deconv_decoder` function. Write a Python function `def deconv_d...
Convolutional decoder used in beta-VAE paper for the chairs data. Based on row 3 of Table 1 on page 13 of "beta-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework" (https://openreview.net/forum?id=Sy2fzU9gl) Args: latent_tensor: Input tensor of shape (batch_size,) to connect decoder to. output...
168,181
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `fc_discriminator` function. Write a Python function `def fc_dis...
Fully connected discriminator used in FactorVAE paper for all datasets. Based on Appendix A page 11 "Disentangling by Factorizing" (https://arxiv.org/pdf/1802.05983.pdf) Args: input_tensor: Input tensor of shape (None, num_latents) to build discriminator on. is_training: Whether or not the graph is built for training (...
168,182
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `test_encoder` function. Write a Python function `def test_encod...
Simple encoder for testing. Args: input_tensor: Input tensor of shape (batch_size, 64, 64, num_channels) to build encoder on. num_latent: Number of latent variables to output. is_training: Whether or not the graph is built for training (UNUSED). Returns: means: Output tensor of shape (batch_size, num_latent) with laten...
168,183
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `test_decoder` function. Write a Python function `def test_decod...
Simple decoder for testing. Args: latent_tensor: Input tensor to connect decoder to. output_shape: Output shape. is_training: Whether or not the graph is built for training (UNUSED). Returns: Output tensor of shape (batch_size, 64, 64, num_channels) with the [0,1] pixel intensities.
168,184
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf import gin.tf def make_optimizer(optimizer_fn, learning_rate): """Wrapper to create the optimizer with a given learning_rate.""" if learning_rate is None: # Learning rat...
Wrapper that uses gin to construct an optimizer for VAEs.
168,185
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf import gin.tf def make_optimizer(optimizer_fn, learning_rate): """Wrapper to create the optimizer with a given learning_rate.""" if learning_rate is None: # Learning rat...
Wrapper that uses gin to construct an optimizer for the discriminator.
168,186
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.methods.semi_supervised import semi_supervised_utils from disentanglement_lib.methods.semi_supervised ...
Trains a model based on the provided gin configuration. This function will set the provided gin bindings, call the train() function and clear the gin config. Please see the train() for required gin bindings. Args: model_dir: String with path to directory where model output should be saved. overwrite: Boolean indicating...
168,187
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np import gin.tf.external_configurables import gin.tf The provided code snippet includes necessary dependencies for implementing the `perfect_labeller` function. Write a Python func...
Returns the true factors of variations without artifacts. Args: labels: True observations of the factors of variations. Numpy array of shape (num_labelled_samples, num_factors) of Float32. dataset: Dataset class. random_state: Random state for the noise (unused). Returns: labels: True observations of the factors of var...
168,188
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np import gin.tf.external_configurables import gin.tf The provided code snippet includes necessary dependencies for implementing the `bin_labeller` function. Write a Python function...
Returns simplified factors of variations. The factors of variations are binned to take at most num_bins different values to simulate the process of a human roughly labelling the factors of variations. Args: labels: True observations of the factors of variations. dataset: Dataset class. random_state: Random state for th...
168,189
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np import gin.tf.external_configurables import gin.tf The provided code snippet includes necessary dependencies for implementing the `noisy_labeller` function. Write a Python functi...
Returns noisy factors of variations. With probability prob_random, the observation of the factor of variations is uniformly sampled from all possible factor values. Args: labels: True observations of the factors of variations. dataset: Dataset class. random_state: Random state for the noise. prob_random: Probability of...
168,190
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np import gin.tf.external_configurables import gin.tf def permute(factor, num_values, random_state): """Permutes the ordinal information of a given factor. Args: factor: Nump...
Returns factors of variations where the ordinal information is broken. Args: labels: True observations of the factors of variations. dataset: Dataset class. random_state: Random state for the noise (unused). Returns: labels: Noisy factors of variations. Numpy array of shape (num_labelled_samples, num_factors) of Float3...
168,191
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np import gin.tf.external_configurables import gin.tf def filter_factors(labels, num_observed_factors, random_state): """Filter observed factor keeping only a random subset of them...
Returns a few factors of variations without artifacts. Args: labels: True observations of the factors of variations. Numpy array of shape (num_labelled_samples, num_factors) of Float32. dataset: Dataset class. random_state: Random state for the noise (unused). num_observed_factors: How many factors are observed. Return...
168,192
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Sample from the encoder distribution with reparametrization trick.
168,193
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Compute KL divergence between input Gaussian and Standard Normal.
168,194
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Utility function to report tf.metrics in model functions.
168,195
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Wrapper that creates annealing function.
168,196
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
No annealing.
168,197
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Linear annealing.
168,198
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Fine tuning. This annealer returns zero if step < iteration_threshold and gamma otherwise. Args: gamma: Weight of supervised loss. step: Current step of training. iteration_threshold: When to return gamma instead of zero. Returns: Either gamma or zero.
168,199
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Wrapper that creates supervised loss.
168,200
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Implements a supervised l2 regularizer. If the number of latent dimension is greater than the number of factor of variations it only uses the first dimensions of the latent code to regularize. The number of factors of variation must be smaller or equal to the number of latent codes. The representation can be scaled wit...
168,201
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Implements a supervised cross_entropy regularizer. If the number of latent dimension is greater than the number of factor of variations it only uses the first dimensions of the latent code to regularize. If the number of factors of variation is larger than the latent code dimension it raise an exception. Labels are in ...
168,202
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Implements a supervised regularizer using a covariance. Penalize the deviation from the identity of the covariance between representation and factors of varations. If the number of latent dimension is greater than the number of factor of variations it only uses the first dimensions of the latent code to regularize. Lab...
168,203
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Embed factors in 1d and compute softmax with the representation. Assume a factor of variation indexed by j can take k values. We embed each value into k real numbers e_1, ..., e_k. Call e_label(r_j) the embedding of an observed label for the factor j. Then, for a dimension r_j of the representation, the loss is compute...
168,204
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_lib.methods.un...
Computes I(X, Z). Uses the algorithm in "Mutual Information Neural Estimation" (https://arxiv.org/pdf/1801.04062.pdf). Args: x: Samples from x [batch_size, size_x]. z: Samples from z [batch_size, size_z]. name_net: Scope for the variables forming the network. Returns: Estimate of the mutual information and the update o...
168,205
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.data.ground_truth import util from disentanglement_lib.methods.unsupervised import gaussian_encoder_mod...
Trains a model based on the provided gin configuration. This function will set the provided gin bindings, call the train() function and clear the gin config. Please see train() for required gin bindings. Args: model_dir: String with path to directory where model output should be saved. overwrite: Boolean indicating whe...
168,206
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_li...
Compute KL divergence between input Gaussian and Standard Normal.
168,207
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_li...
Utility function to report tf.metrics in model functions.
168,208
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_li...
Anneal function for anneal_vae (https://arxiv.org/abs/1804.03599). Args: c_max: Maximum capacity. step: Current step. iteration_threshold: How many iterations to reach c_max. Returns: Capacity annealed linearly until c_max.
168,209
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_li...
Computes the covariance of z_mean. Uses cov(z_mean) = E[z_mean*z_mean^T] - E[z_mean]E[z_mean]^T. Args: z_mean: Encoder mean, tensor of size [batch_size, num_latent]. Returns: cov_z_mean: Covariance of encoder mean, tensor of size [num_latent, num_latent].
168,210
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_li...
Compute on and off diagonal regularizers for DIP-VAE models. Penalize deviations of covariance_matrix from the identity matrix. Uses different weights for the deviations of the diagonal and off diagonal entries. Args: covariance_matrix: Tensor of size [num_latent, num_latent] to regularize. lambda_od: Weight of penalty...
168,211
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from disentanglement_lib.methods.shared import architectures from disentanglement_lib.methods.shared import losses from disentanglement_lib.methods.shared import optimizers from disentanglement_li...
Estimate of total correlation on a batch. We need to compute the expectation over a batch of: E_j [log(q(z(x_j))) - log(prod_l q(z(x_j)_l))]. We ignore the constants as they do not matter for the minimization. The constant should be equal to (num_latents - 1) * log(batch_size * dataset_size) Args: z: [batch_size, num_l...
168,212
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range import gin.tf def _prune_dims(variances, threshold=0.): """Mask for dimensions c...
Computes the FactorVAE disentanglement metric. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_dir: O...
168,213
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range import gin.tf def _compute_loss(x_train, y_train, x_test, y_test, predictor_fn): """Compute average accur...
Computes loss of downstream task. This task is about strong generalization under covariate shifts. We first perform an intervention fixing a value for a factor in the whole training set. Then, we train a GBT classifier, and at test time, we consider all other values for that factor. We repeat the experiment n_experimen...
168,214
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import range import sklearn from sklearn import ensemble from sklearn import linear_model from sklearn import model_selection import gin.tf The provided code snippet includes n...
Discretization based on histograms.
168,215
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import range import sklearn from sklearn import ensemble from sklearn import linear_model from sklearn import model_selection import gin.tf The provided code snippet includes n...
Logistic regression with 5 folds cross validation.
168,216
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import range import sklearn from sklearn import ensemble from sklearn import linear_model from sklearn import model_selection import gin.tf The provided code snippet includes n...
Default gradient boosting classifier.
168,217
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np import gin.tf def _drop_constant_dims(ys): """Returns a view of the matrix `ys` with dropped constant rows."...
Computes the Interventional Robustness Score. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_dir: Op...
168,218
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range from sklearn import linear_model from sklearn import metrics from sklearn import preprocessing import gin.t...
Computes the modularity metric according to Sec 3. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_di...
168,219
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range import gin.tf def compute_reduced_representation(mus...
Computes loss of a reduced downstream task. Measure the information leakage in each latent component after removing the k ("factors_to_remove") most informative features for the prediction task. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as inp...
168,220
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range import gin.tf "dci", The provided code snippet inc...
Computes the DCI importance matrix of the attributes. Args: mus_train: latent means of the training batch. ys_train: labels of the training batch. mus_test: latent means of the test batch. ys_test: labels of the test batch. Returns: Matrix with importance scores.
168,221
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging import numpy as np from six.moves import range from sklearn import linear_model import gin.tf def _generate_training_batch(ground_truth_data, representation_function, ...
Computes the BetaVAE disentanglement metric using scikit-learn. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness...
168,222
from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np import gin.tf def _compute_mig(mus_train, ys_train): """Computes score based on both training and testing codes and factors.""" score_dict = {} discretized_mus = utils.make_discretizer(mus_train) m = utils.discr...
Computes the mutual information gap. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_dir: Optional pa...
168,223
from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np import gin.tf def _compute_mig(mus_train, ys_train): """Computes score based on both training and testing codes and factors.""" score_dict = {} discretized_mus = utils.make_discretizer(mus_train) m = utils.discr...
Computes the MIG scores on the fixed set of observations and labels. Args: observations: Observations on which to compute the score. Observations have shape (num_observations, 64, 64, num_channels). labels: Observed factors of variations. representation_function: Function that takes observations as input and outputs a ...
168,224
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range import gin.tf def _compute_loss(x_train, y_train, x_test, y_test, predictor_fn): """Compute average accur...
Computes loss of downstream task. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_dir: Optional path ...
168,225
from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np import scipy import gin.tf def gaussian_total_correlation(cov): """Computes the total correlation of a Gaussian with covariance matrix cov. We use that the total correlation is the KL divergence between the Gaussian...
Computes unsupervised scores based on covariance and mutual information. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for r...
168,226
from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np import scipy import gin.tf The provided code snippet includes necessary dependencies for implementing the `kl_gaussians_numerically_unstable` function. Write a Python function `def kl_gaussians_numerically_unstable(mea...
Unstable version used for testing gaussian_total_correlation.
168,227
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Computes the unified disentanglement scores. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_dir: Opt...
168,228
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Computes the unified scores on the fixed set of observations and labels. Args: observations: Observations on which to compute the score. Observations have shape (num_observations, 64, 64, num_channels). labels: Observed factors of variations. representation_function: Function that takes observations as input and output...
168,229
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Computes the importance matrix of the DCI Disentanglement score. The importance matrix is based on the importance of each code to predict a factor of variation with GBT. Args: mus_train: Batch of learned representations to be used for training. ys_train: Observed factors of variation corresponding to the representation...
168,230
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Computes the mutual information matrix between codes and factors. The mutual information matrix is used to compute the MIG and Modularity scores. Args: mus_train: Batch of learned representations to be used for training. ys_train: Observed factors of variation corresponding to the representations in mus_train. mus_test...
168,231
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Prediction accuracy of a SVM predicting a factor from a single code. The matrix of accuracies is used to compute the SAP score. Args: mus_train: Batch of learned representations to be used for training. ys_train: Observed factors of variation corresponding to the representations in mus_train. mus_test: Batch of learned...
168,232
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Aggregation function of the DCI Disentanglement.
168,233
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Aggregation function of the MIG.
168,234
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Aggregation function of the SAP score.
168,235
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from disentanglement_lib.evaluation.metrics import dci from disentanglement_lib.evaluation.metrics import modularity_explicitness from disentanglement_lib.evaluation.metrics im...
Aggregation function of the modularity score.
168,236
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range import gin.tf def compute_scores_dict(metric, prefix): """Computes scores for combinations of predictive ...
Computes unfairness scores. We first compute either the mean or maximum total variation for a given sensitive and target variable. Then, we either average or take the maximum with respect to target and sensitive variable. For convenience, we compute and save all combinations. The score used in Section 4 of the paper is...
168,237
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np import scipy from six.moves import range from sklearn import ensemble import gin.tf def _compute_dci(mus_train...
Computes the DCI scores according to Sec 2. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_dir: Opti...
168,238
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np import scipy from six.moves import range from sklearn import ensemble import gin.tf def _compute_dci(mus_train...
Computes the DCI scores on the fixed set of observations and labels. Args: observations: Observations on which to compute the score. Observations have shape (num_observations, 64, 64, num_channels). labels: Observed factors of variations. representation_function: Function that takes observations as input and outputs a ...
168,239
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range from sklearn import svm import gin.tf def _compute_sap(mus, ys, mus_test, ys_test,...
Computes the SAP score. Args: ground_truth_data: GroundTruthData to be sampled from. representation_function: Function that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: Numpy random state used for randomness. artifact_dir: Optional path to directo...
168,240
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from disentanglement_lib.evaluation.metrics import utils import numpy as np from six.moves import range from sklearn import svm import gin.tf def _compute_sap(mus, ys, mus_test, ys_test,...
Computes the SAP score on the fixed set of observations and labels. Args: observations: Observations on which to compute the score. Observations have shape (num_observations, 64, 64, num_channels). labels: Observed factors of variations. representation_function: Function that takes observations as input and outputs a d...
168,241
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging import numpy as np import scipy from sklearn import linear_model from sklearn import preprocessing import gin.tf def relative_strength_disentanglement(corr_matrix): """Computes disenta...
Computes the UDR score using scikit-learn. Args: ground_truth_data: GroundTruthData to be sampled from. representation_functions: functions that takes observations as input and outputs a dim_representation sized representation for each observation. random_state: numpy random state used for randomness. batch_size: Numbe...
168,242
from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib import os import time from absl import flags from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.evaluation.udr.metrics import udr from disentanglement_lib.ut...
Loads a trained estimator and evaluates it according to beta-VAE metric.
168,243
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np The provided code snippet includes necessary dependencies for implementing the `sample_easy_alternative` function. Write a Python function `def sample_easy_alternative(design, matrix, already...
Samples easy alternative based on sampling a new PGM.
168,244
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np The provided code snippet includes necessary dependencies for implementing the `sample_hard_alternative` function. Write a Python function `def sample_hard_alternative(design, matrix, already...
Samples hard alternative based on sampling a new PGM.
168,245
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def is_constant_row(row): return len(np.unique(row)) == 1
null
168,246
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def is_distinct_row(row): return len(np.unique(row)) == len(row)
null
168,247
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from disentanglement_lib.evaluation.abstract_reasoning import models from disentanglement_lib.evaluation.abstract_reasoning import pgm_data from disentanglement_lib.utils import results im...
Trains a model based on the provided gin configuration. This function will set the provided gin bindings, call the reason() function and clear the gin config. Please see reason() for required gin bindings. Args: input_dir: String with path to directory where the representation is saved. output_dir: String with the path...
168,248
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.data.ground_truth import dsprites from disentanglement_lib.data.ground_truth import dummy_data from disentanglement_lib.data.ground_truth import ground_truth_data as gtd from disentangle...
Returns an image of the question mark.
168,249
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.data.ground_truth import dsprites from disentanglement_lib.data.ground_truth import dummy_data from disentanglement_lib.data.ground_truth import ground_truth_data as gtd from disentangle...
Embeds the indices as one hot vectors.
168,250
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.evaluation.abstract_reasoning import relational_layers import gin import tensorflow.compat.v1 as tf import tensorflow_hub as hub from tensorflow.contrib import tpu as contrib_tpu def ge...
null
168,251
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.evaluation.abstract_reasoning import relational_layers import gin import tensorflow.compat.v1 as tf import tensorflow_hub as hub from tensorflow.contrib import tpu as contrib_tpu def ge...
null
168,252
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf The provided code snippet includes necessary dependencies for implementing the `repeat` function. Write a Python function `def repeat(tensor, num, axis)` to solve the following...
Repeats tensor num times along the specified axis.
168,253
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf The provided code snippet includes necessary dependencies for implementing the `positional_encoding_like` function. Write a Python function `def positional_encoding_like(tensor...
Creates positional encoding matching the provided tensor. Let each slice along the last axis of the tensor be a row. This function computes the index of each row with respect to the specified positional_encoding_axis and returns this index using a one-hot embedding. The resulting tensor has the same shape as the provid...
168,254
from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import os import time import warnings from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.evaluation.metrics import beta_vae from disentanglement_lib.evaluation....
Evaluate a representation based on the provided gin configuration. This function will set the provided gin bindings, call the evaluate() function and clear the gin config. Please see the evaluate() for required gin bindings. Args: model_dir: String with path to directory where the representation is saved. output_dir: S...
168,255
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.config import study from disentanglement_lib.utils import resources import disentanglement_lib.utils.hyperparams as h from six.moves import range def get_num_latent(sweep): return h.s...
null
168,256
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.config import study from disentanglement_lib.utils import resources import disentanglement_lib.utils.hyperparams as h from six.moves import range def get_datasets(): """Returns all the...
Returns the hyperparameter configs for different experiments.
168,258
from __future__ import absolute_import from __future__ import division from __future__ import print_function from disentanglement_lib.config import study from disentanglement_lib.utils import resources import disentanglement_lib.utils.hyperparams as h from six.moves import range def get_datasets(): """Returns all the...
Returns the hyperparameter configs for different experiments.
168,261
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.postprocessing import methods from disentanglement_lib.utils import convolute_hub from disentanglement...
Postprocess a trained model based on the provided gin configuration. This function will set the provided gin bindings, call the postprocess() function and clear the gin config. Please see the postprocess() for required gin bindings. Args: model_dir: String with path to directory where the model is saved. output_dir: St...
168,262
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `mean_representation` function. Write a Python function `def mean_representation( ...
Extracts the mean representation from a Gaussian encoder. Args: ground_truth_data: GroundTruthData to be sampled from. gaussian_encoder: Function that takes observations as input and outputs a dictionary with mean and log variances of the encodings in the keys "mean" and "logvar" respectively. random_state: Numpy rando...
168,263
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf import gin.tf The provided code snippet includes necessary dependencies for implementing the `sampled_representation` function. Write a Python function `def sampled_representat...
Extracts the random representation from a Gaussian encoder. Args: ground_truth_data: GroundTruthData to be sampled from. gaussian_encoder: Function that takes observations as input and outputs a dictionary with mean and log variances of the encodings in the keys "mean" and "logvar" respectively. random_state: Numpy ran...
168,264
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numbers import os from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.utils import results from disentanglement_lib.visualize import visualize_util from disentanglement_l...
Takes trained model from model_dir and visualizes it in output_dir. Args: model_dir: Path to directory where the trained model is saved. output_dir: Path to output directory. overwrite: Boolean indicating whether to overwrite output directory. num_animations: Integer with number of distinct animations to create. num_fr...
168,265
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from disentanglement_lib.data.ground_truth import named_data from disentanglement_lib.visualize import visualize_util import numpy as np from six.moves import range from tensorflow.compat.v1 import gfi...
Visualizes the data set by saving images to output_path. For each latent factor, outputs 16 images where only that latent factor is varied while all others are kept constant. Args: dataset_name: String with name of dataset as defined in named_data.py. output_path: String with path in which to create the visualizations....
168,266
from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing from absl import logging import pandas as pd import simplejson as json from tensorflow.compat.v1 import gfile def _get(pattern): files = gfile.Glob(pattern) pool = multiprocessing.Pool...
Aggregates all the results files in the pattern into a single JSON file. Args: result_file_pattern: String with glob pattern to all the result files that should be aggregated (e.g. /tmp/*/results/aggregate/evaluation.json). output_path: String with path to output json file (e.g. /tmp/results.json).
168,267
from __future__ import absolute_import from __future__ import division from __future__ import print_function import multiprocessing from absl import logging import pandas as pd import simplejson as json from tensorflow.compat.v1 import gfile The provided code snippet includes necessary dependencies for implementing th...
Convenience function to load aggregated results from JSON file. Args: source_path: String with path to aggregated json file (e.g. /tmp/results.json). Returns: pd.DataFrame with aggregated results.
168,268
from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from six.moves import range from six.moves import zip def _escape_value(value): if isinstance(value, (str, six.text_type)) and not value.startswith("@"): return "'{}'".format(value) return str...
null
168,269
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os def get_files_in_folder(path): import pkg_resources # pylint: disable=g-bad-import-order, g-import-not-at-top for name in pkg_resources.resource_listdir("disentanglement_lib", path): new_path...
null
168,270
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf import tensorflow_hub as hub from tensorflow.contrib import framework as contrib_framework The provided code snippet includes necessary dependencies for implementing the `save_...
Saves several NumpyArrays to variables in a TF checkpoint. Args: checkpoint_path: String with the path to the checkpoint file. **dict_with_arrays: Dictionary with keys that signify variable names and values that are the corresponding Numpy arrays to be saved.
168,271
import argparse import os import torch from accelerate import Accelerator from datasets import load_dataset from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, set_peft_model_state_dict from torch.utils.data import IterableDataset from tqdm import tqdm from transformers import AutoConfig, Auto...
null
168,272
import argparse import os import torch from accelerate import Accelerator from datasets import load_dataset from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, set_peft_model_state_dict from torch.utils.data import IterableDataset from tqdm import tqdm from transformers import AutoConfig, Auto...
null
168,273
import argparse import os import torch from accelerate import Accelerator from datasets import load_dataset from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training, set_peft_model_state_dict from torch.utils.data import IterableDataset from tqdm import tqdm from transformers import AutoConfig, Auto...
null
168,274
from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel import torch import os import argparse def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--base_model_name_or_path", type=str, default="bigcode/large-model") parser.add_argument("--peft_model_path"...
null
168,275
import dataclasses import os from dataclasses import dataclass from typing import List, Optional from huggingface_hub import login from transformers import HfArgumentParser The provided code snippet includes necessary dependencies for implementing the `hf_login` function. Write a Python function `def hf_login()` to so...
Login to HuggingFace Hub if HF_TOKEN is defined in the environment
168,276
import json import os from dataclasses import asdict, dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Type, TypeVar, Union from huggingface_hub import ModelHubMixin, hf_hub_download class DialogueTemplate(ModelHubMixin): def get_training_prompt(self) -> str: def get_inference_...
null