Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for fairness.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
class FairnessTest(absltest.TestCase):
def test_metric(self):
gin.bind_parameter("predictor.predictor_fn",
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import fairness
from disentanglement_lib.evaluation.metrics import utils
import numpy as np
import gin.tf
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/fairness.py
# def compute_fairness(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test_points_per_class=gin.REQUIRED,
# batch_size=16):
# def compute_scores_dict(metric, prefix):
# def inter_group_fairness(counts):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | utils.gradient_boosting_classifier) |
Using the snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the dendrogram.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class DendrogramTest(parameterized.TestCase):
@parameterized.parameters((np.zeros((5, 10), dtype=np.float32),))
def test_dendrogram_plot(self, matrix):
<|code_end|>
, determine the next line of code. You have imports:
from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.visualize import dendrogram
import numpy as np
and context (class names, function names, or code) available:
# Path: disentanglement_lib/visualize/dendrogram.py
# def dendrogram_plot(matrix, output_dir, factor_names):
# def report_merges(z, num_factors):
# def _find(nodes, i):
# def _union(nodes, idx, idy, val, z, cluster_id, size, matrix, n_clusters,
# idx_found):
. Output only the next line. | dendrogram.dendrogram_plot( |
Here is a snippet: <|code_start|> scores_dict["num_active_dims"] = len(active_dims)
return scores_dict
@gin.configurable("prune_dims", blacklist=["variances"])
def _prune_dims(variances, threshold=0.):
"""Mask for dimensions collapsed to the prior."""
scale_z = np.sqrt(variances)
return scale_z >= threshold
def _compute_variances(ground_truth_data,
representation_function,
batch_size,
random_state,
eval_batch_size=64):
"""Computes the variance for each dimension of the representation.
Args:
ground_truth_data: GroundTruthData to be sampled from.
representation_function: Function that takes observation as input and
outputs a representation.
batch_size: Number of points to be used to compute the variances.
random_state: Numpy random state used for randomness.
eval_batch_size: Batch size used to eval representation.
Returns:
Vector with the variance of each dimension.
"""
observations = ground_truth_data.sample_observations(batch_size, random_state)
<|code_end|>
. Write the next line using the current file imports:
from absl import logging
from disentanglement_lib.evaluation.metrics import utils
from six.moves import range
import numpy as np
import gin.tf
and context from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
, which may include functions, classes, or code. Output only the next line. | representations = utils.obtain_representation(observations, |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for unsupervised_metrics.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class UnsupervisedMetricsTest(absltest.TestCase):
def test_gaussian_total_correlation_zero(self):
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import absltest
from disentanglement_lib.evaluation.metrics import unsupervised_metrics
import numpy as np
import scipy
and context from other files:
# Path: disentanglement_lib/evaluation/metrics/unsupervised_metrics.py
# @gin.configurable(
# "unsupervised_metrics",
# blacklist=["ground_truth_data", "representation_function", "random_state",
# "artifact_dir"])
# def unsupervised_metrics(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# batch_size=16):
# """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 randomness.
# artifact_dir: Optional path to directory where artifacts can be saved.
# num_train: Number of points used for training.
# batch_size: Batch size for sampling.
#
# Returns:
# Dictionary with scores.
# """
# del artifact_dir
# scores = {}
# logging.info("Generating training set.")
# mus_train, _ = utils.generate_batch_factor_code(
# ground_truth_data, representation_function, num_train, random_state,
# batch_size)
# num_codes = mus_train.shape[0]
# cov_mus = np.cov(mus_train)
# assert num_codes == cov_mus.shape[0]
#
# # Gaussian total correlation.
# scores["gaussian_total_correlation"] = gaussian_total_correlation(cov_mus)
#
# # Gaussian Wasserstein correlation.
# scores["gaussian_wasserstein_correlation"] = gaussian_wasserstein_correlation(
# cov_mus)
# scores["gaussian_wasserstein_correlation_norm"] = (
# scores["gaussian_wasserstein_correlation"] / np.sum(np.diag(cov_mus)))
#
# # Compute average mutual information between different factors.
# mus_discrete = utils.make_discretizer(mus_train)
# mutual_info_matrix = utils.discrete_mutual_info(mus_discrete, mus_discrete)
# np.fill_diagonal(mutual_info_matrix, 0)
# mutual_info_score = np.sum(mutual_info_matrix) / (num_codes**2 - num_codes)
# scores["mutual_info_score"] = mutual_info_score
# return scores
, which may include functions, classes, or code. Output only the next line. | score = unsupervised_metrics.gaussian_total_correlation( |
Continue the code snippet: <|code_start|>"""Unsupervised scores based on code covariance and mutual information."""
@gin.configurable(
"unsupervised_metrics",
blacklist=["ground_truth_data", "representation_function", "random_state",
"artifact_dir"])
def unsupervised_metrics(ground_truth_data,
representation_function,
random_state,
artifact_dir=None,
num_train=gin.REQUIRED,
batch_size=16):
"""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 randomness.
artifact_dir: Optional path to directory where artifacts can be saved.
num_train: Number of points used for training.
batch_size: Batch size for sampling.
Returns:
Dictionary with scores.
"""
del artifact_dir
scores = {}
logging.info("Generating training set.")
<|code_end|>
. Use current file imports:
from absl import logging
from disentanglement_lib.evaluation.metrics import utils
import numpy as np
import scipy
import gin.tf
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | mus_train, _ = utils.generate_batch_factor_code( |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for utils.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class UtilsTest(absltest.TestCase):
def test_histogram_discretizer(self):
# Input of 2D samples.
target = np.array([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6],
[0.6, .5, .4, .3, .2, .1]])
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import absltest
from disentanglement_lib.evaluation.metrics import utils
import numpy as np
and context from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
, which may include functions, classes, or code. Output only the next line. | result = utils._histogram_discretize(target, num_bins=3) |
Predict the next line for this snippet: <|code_start|> lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 1.)
dip_type = h.fixed("dip_vae.dip_type", "ii")
config_dip_vae_ii = h.zipit(
[model_name, model_fn, lambda_od, lambda_d_factor, dip_type])
# BetaTCVAE config.
model_name = h.fixed("model.name", "beta_tc_vae")
model_fn = h.fixed("model.model", "@beta_tc_vae()")
betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.]))
config_beta_tc_vae = h.zipit([model_name, model_fn, betas])
all_models = h.chainit([
config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii,
config_beta_tc_vae, config_annealed_beta_vae
])
return all_models
def get_config():
"""Returns the hyperparameter configs for different experiments."""
arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1)
arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1)
architecture = h.zipit([arch_enc, arch_dec])
return h.product([
get_datasets(),
architecture,
get_default_models(),
get_seeds(50),
])
<|code_end|>
with the help of current file imports:
from disentanglement_lib.config import study
from disentanglement_lib.utils import resources
from six.moves import range
import disentanglement_lib.utils.hyperparams as h
and context from other files:
# Path: disentanglement_lib/config/study.py
# class Study(object):
# def get_model_config(self, model_num=0):
# def print_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def print_postprocess_config(self):
# def get_eval_config_files(self):
# def print_eval_config(self):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
, which may contain function names, class names, or code. Output only the next line. | class FairnessStudyV1(study.Study): |
Based on the snippet: <|code_start|> model_fn = h.fixed("model.model", "@beta_tc_vae()")
betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.]))
config_beta_tc_vae = h.zipit([model_name, model_fn, betas])
all_models = h.chainit([
config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii,
config_beta_tc_vae, config_annealed_beta_vae
])
return all_models
def get_config():
"""Returns the hyperparameter configs for different experiments."""
arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1)
arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1)
architecture = h.zipit([arch_enc, arch_dec])
return h.product([
get_datasets(),
architecture,
get_default_models(),
get_seeds(50),
])
class FairnessStudyV1(study.Study):
"""Defines the study for the paper."""
def get_model_config(self, model_num=0):
"""Returns model bindings and config file."""
config = get_config()[model_num]
model_bindings = h.to_bindings(config)
<|code_end|>
, predict the immediate next line with the help of imports:
from disentanglement_lib.config import study
from disentanglement_lib.utils import resources
from six.moves import range
import disentanglement_lib.utils.hyperparams as h
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/config/study.py
# class Study(object):
# def get_model_config(self, model_num=0):
# def print_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def print_postprocess_config(self):
# def get_eval_config_files(self):
# def print_eval_config(self):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
. Output only the next line. | model_config_file = resources.get_file( |
Given the code snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the visualize_scores.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class VisualizeScoresTest(parameterized.TestCase):
@parameterized.parameters((np.zeros((5, 10), dtype=np.float32),
np.zeros((2, 10), dtype=np.float32),
np.zeros((10, 10), dtype=np.float32)))
def plot_recovery_vs_independent(self, matrix):
<|code_end|>
, generate the next line using the imports in this file:
from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.visualize import visualize_scores
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/visualize/visualize_scores.py
# def heat_square(matrix, output_dir, name, xlabel, ylabel, max_val=None,
# factor_names=None):
# def plot_matrix_squares(matrix, max_val, palette, size_scale, ax):
# def to_color(val):
# def plot_bar_palette(palette, max_val, ax):
# def plot_recovery_vs_independent(matrix, output_dir, name):
# def precision(matrix, th):
# def recall(matrix, th):
# def bfs(matrix, to_visit, factors, codes, size):
. Output only the next line. | visualize_scores.plot_recovery_vs_independent( |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the architectures.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class ArchitecturesTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.named_parameters(
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import parameterized
from disentanglement_lib.methods.shared import architectures
import numpy as np
import tensorflow.compat.v1 as tf
and context from other files:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
, which may include functions, classes, or code. Output only the next line. | ('fc_encoder', architectures.fc_encoder), |
Next line prediction: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for udr.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class UdrTest(absltest.TestCase):
def test_metric_spearman(self):
<|code_end|>
. Use current file imports:
(from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.udr.metrics import udr
import numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/udr/metrics/udr.py
# def relative_strength_disentanglement(corr_matrix):
# def spearman_correlation_conv(vec1, vec2):
# def lasso_correlation_matrix(vec1, vec2, random_state=None):
# def _generate_representation_batch(ground_truth_data, representation_functions,
# batch_size, random_state):
# def _generate_representation_dataset(ground_truth_data,
# representation_functions, batch_size,
# num_data_points, random_state):
# def compute_udr_sklearn(ground_truth_data,
# representation_functions,
# random_state,
# batch_size,
# num_data_points,
# correlation_matrix="lasso",
# filter_low_kl=True,
# include_raw_correlations=True,
# kl_filter_threshold=0.01):
. Output only the next line. | ground_truth_data = dummy_data.DummyData() |
Based on the snippet: <|code_start|>
"""Tests for udr.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class UdrTest(absltest.TestCase):
def test_metric_spearman(self):
ground_truth_data = dummy_data.DummyData()
random_state = np.random.RandomState(0)
num_factors = ground_truth_data.num_factors
batch_size = 10
num_data_points = 1000
permutation = np.random.permutation(num_factors)
sign_inverse = np.random.choice(num_factors, int(num_factors / 2))
def rep_fn1(data):
return (np.reshape(data, (batch_size, -1))[:, :num_factors],
np.ones(num_factors))
# Should be invariant to permutation and sign inverse.
def rep_fn2(data):
raw_representation = np.reshape(data, (batch_size, -1))[:, :num_factors]
perm_rep = raw_representation[:, permutation]
perm_rep[:, sign_inverse] = -1.0 * perm_rep[:, sign_inverse]
return perm_rep, np.ones(num_factors)
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.udr.metrics import udr
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/udr/metrics/udr.py
# def relative_strength_disentanglement(corr_matrix):
# def spearman_correlation_conv(vec1, vec2):
# def lasso_correlation_matrix(vec1, vec2, random_state=None):
# def _generate_representation_batch(ground_truth_data, representation_functions,
# batch_size, random_state):
# def _generate_representation_dataset(ground_truth_data,
# representation_functions, batch_size,
# num_data_points, random_state):
# def compute_udr_sklearn(ground_truth_data,
# representation_functions,
# random_state,
# batch_size,
# num_data_points,
# correlation_matrix="lasso",
# filter_low_kl=True,
# include_raw_correlations=True,
# kl_filter_threshold=0.01):
. Output only the next line. | scores = udr.compute_udr_sklearn( |
Given the following code snippet before the placeholder: <|code_start|>
@gin.configurable(
"dci",
blacklist=["ground_truth_data", "representation_function", "random_state",
"artifact_dir"])
def compute_dci(ground_truth_data, representation_function, random_state,
artifact_dir=None,
num_train=gin.REQUIRED,
num_test=gin.REQUIRED,
batch_size=16):
"""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: Optional path to directory where artifacts can be saved.
num_train: Number of points used for training.
num_test: Number of points used for testing.
batch_size: Batch size for sampling.
Returns:
Dictionary with average disentanglement score, completeness and
informativeness (train and test).
"""
del artifact_dir
logging.info("Generating training set.")
# mus_train are of shape [num_codes, num_train], while ys_train are of shape
# [num_factors, num_train].
<|code_end|>
, predict the next line using imports from the current file:
from absl import logging
from disentanglement_lib.evaluation.metrics import utils
from six.moves import range
from sklearn import ensemble
import numpy as np
import scipy
import gin.tf
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | mus_train, ys_train = utils.generate_batch_factor_code( |
Given the following code snippet before the placeholder: <|code_start|>(https://arxiv.org/pdf/1802.04942.pdf).
"""
@gin.configurable(
"mig",
blacklist=["ground_truth_data", "representation_function", "random_state",
"artifact_dir"])
def compute_mig(ground_truth_data,
representation_function,
random_state,
artifact_dir=None,
num_train=gin.REQUIRED,
batch_size=16):
"""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 path to directory where artifacts can be saved.
num_train: Number of points used for training.
batch_size: Batch size for sampling.
Returns:
Dict with average mutual information gap.
"""
del artifact_dir
logging.info("Generating training set.")
<|code_end|>
, predict the next line using imports from the current file:
from absl import logging
from disentanglement_lib.evaluation.metrics import utils
import numpy as np
import gin.tf
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | mus_train, ys_train = utils.generate_batch_factor_code( |
Continue the code snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the semi supervised training protocol."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class S2VaeTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.parameters((0, 100., 100.01), (10, 100., 100.01),
(100, 100., 100.01), (101, 100., 100.01))
def test_fixed_annealer(self, step, target_low, target_high):
c_max = 100.
iteration_threshold = 100
<|code_end|>
. Use current file imports:
from absl.testing import parameterized
from disentanglement_lib.methods.semi_supervised import semi_supervised_vae # pylint: disable=unused-import
import numpy as np
import tensorflow.compat.v1 as tf
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/methods/semi_supervised/semi_supervised_vae.py
# class BaseS2VAE(vae.BaseVAE):
# class S2BetaVAE(BaseS2VAE):
# class SupervisedVAE(BaseS2VAE):
# class MineVAE(BaseS2VAE):
# class S2FactorVAE(BaseS2VAE):
# class S2DIPVAE(BaseS2VAE):
# class S2BetaTCVAE(BaseS2VAE):
# def __init__(self, factor_sizes):
# def model_fn(self, features, labels, mode, params):
# def sample_from_latent_distribution(z_mean, z_logvar):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def make_annealer(gamma,
# step,
# iteration_threshold=gin.REQUIRED,
# anneal_fn=gin.REQUIRED):
# def fixed_annealer(gamma, step, iteration_threshold):
# def annealed_annealer(gamma, step, iteration_threshold):
# def fine_tune_annealer(gamma, step, iteration_threshold):
# def make_supervised_loss(representation, labels,
# factor_sizes=None, loss_fn=gin.REQUIRED):
# def normalize_labels(labels, factors_num_values):
# def supervised_regularizer_l2(representation, labels,
# factor_sizes=None,
# learn_scale=True):
# def supervised_regularizer_xent(representation, labels,
# factor_sizes=None):
# def supervised_regularizer_cov(representation, labels,
# factor_sizes=None):
# def supervised_regularizer_embed(representation, labels,
# factor_sizes, sigma=gin.REQUIRED,
# use_order=False):
# def __init__(self, factor_sizes, beta=gin.REQUIRED, gamma_sup=gin.REQUIRED):
# def unsupervised_regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def mine(x, z, name_net="estimator_network"):
# def __init__(self, factor_sizes, gamma_sup=gin.REQUIRED, beta=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def __init__(self, factor_sizes, gamma=gin.REQUIRED, gamma_sup=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def __init__(self,
# factor_sizes,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# gamma_sup=gin.REQUIRED,
# dip_type="i"):
# def unsupervised_regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, factor_sizes, beta=gin.REQUIRED, gamma_sup=gin.REQUIRED):
# def unsupervised_regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
. Output only the next line. | test_value = semi_supervised_vae.fixed_annealer(c_max, step, |
Based on the snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for visualize_util.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class VisualizeUtilTest(absltest.TestCase):
def test_save_image(self):
image = np.zeros((128, 256, 3), dtype=np.float32)
path = os.path.join(self.create_tempdir().full_path, "save_image.png")
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import numpy as np
from absl.testing import absltest
from disentanglement_lib.visualize import visualize_util
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
. Output only the next line. | visualize_util.save_image(image, path) |
Predict the next line for this snippet: <|code_start|> # Piecewise constant learning rate.
bindings = [
"vae_optimizer.optimizer_fn = @GradientDescentOptimizer",
"vae_optimizer.learning_rate = @piecewise_constant",
"piecewise_constant.boundaries = (3, 5)",
"piecewise_constant.values = (0.2, 0.1, 0.01)",
]
yield (bindings, 0.01)
# Exponential decay learning rate.
bindings = [
"vae_optimizer.optimizer_fn = @GradientDescentOptimizer",
"vae_optimizer.learning_rate = @exponential_decay",
"exponential_decay.learning_rate = 0.1",
"exponential_decay.decay_steps = 1",
"exponential_decay.decay_rate = 0.9",
]
yield (bindings, 0.03486784401)
class OptimizerTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.parameters(list(_make_vae_optimizer_configs()))
def test_vae_optimizer(self, gin_bindings, expected_learning_rate):
gin.parse_config_files_and_bindings([], gin_bindings)
with self.test_session():
x = tf.Variable(0.0)
y = tf.pow(x + 2.0, 2.0)
global_step = tf.train.get_or_create_global_step()
<|code_end|>
with the help of current file imports:
from absl.testing import parameterized
from disentanglement_lib.methods.shared import optimizers
from six.moves import range
import tensorflow.compat.v1 as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
and context from other files:
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
, which may contain function names, class names, or code. Output only the next line. | optimizer = optimizers.make_vae_optimizer() |
Continue the code snippet: <|code_start|>@gin.configurable(
"sap_score",
blacklist=["ground_truth_data", "representation_function", "random_state",
"artifact_dir"])
def compute_sap(ground_truth_data,
representation_function,
random_state,
artifact_dir=None,
num_train=gin.REQUIRED,
num_test=gin.REQUIRED,
batch_size=16,
continuous_factors=gin.REQUIRED):
"""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 directory where artifacts can be saved.
num_train: Number of points used for training.
num_test: Number of points used for testing discrete variables.
batch_size: Batch size for sampling.
continuous_factors: Factors are continuous variable (True) or not (False).
Returns:
Dictionary with SAP score.
"""
del artifact_dir
logging.info("Generating training set.")
<|code_end|>
. Use current file imports:
from absl import logging
from disentanglement_lib.evaluation.metrics import utils
from six.moves import range
from sklearn import svm
import numpy as np
import gin.tf
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | mus, ys = utils.generate_batch_factor_code( |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DSprites dataset and new variants with probabilistic decoders."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
DSPRITES_PATH = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "dsprites",
"dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz")
SCREAM_PATH = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "scream", "scream.jpg")
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy as np
import PIL
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
from tensorflow.compat.v1 import gfile
and context from other files:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
, which may include functions, classes, or code. Output only the next line. | class DSprites(ground_truth_data.GroundTruthData): |
Given snippet: <|code_start|>
The data set was originally introduced in "beta-VAE: Learning Basic Visual
Concepts with a Constrained Variational Framework" and can be downloaded from
https://github.com/deepmind/dsprites-dataset.
The ground-truth factors of variation are (in the default setting):
0 - shape (3 different values)
1 - scale (6 different values)
2 - orientation (40 different values)
3 - position x (32 different values)
4 - position y (32 different values)
"""
def __init__(self, latent_factor_indices=None):
# By default, all factors (including shape) are considered ground truth
# factors.
if latent_factor_indices is None:
latent_factor_indices = list(range(6))
self.latent_factor_indices = latent_factor_indices
self.data_shape = [64, 64, 1]
# Load the data so that we can sample from it.
with gfile.Open(DSPRITES_PATH, "rb") as data_file:
# Data was saved originally using python2, so we need to set the encoding.
data = np.load(data_file, encoding="latin1", allow_pickle=True)
self.images = np.array(data["imgs"])
self.factor_sizes = np.array(
data["metadata"][()]["latents_sizes"], dtype=np.int64)
self.full_factor_sizes = [1, 3, 6, 40, 32, 32]
self.factor_bases = np.prod(self.factor_sizes) / np.cumprod(
self.factor_sizes)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
import PIL
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
from tensorflow.compat.v1 import gfile
and context:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
which might include code, classes, or functions. Output only the next line. | self.state_space = util.SplitDiscreteStateSpace(self.factor_sizes, |
Continue the code snippet: <|code_start|>
@gin.configurable(
"modularity_explicitness",
blacklist=["ground_truth_data", "representation_function", "random_state",
"artifact_dir"])
def compute_modularity_explicitness(ground_truth_data,
representation_function,
random_state,
artifact_dir=None,
num_train=gin.REQUIRED,
num_test=gin.REQUIRED,
batch_size=16):
"""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_dir: Optional path to directory where artifacts can be saved.
num_train: Number of points used for training.
num_test: Number of points used for testing.
batch_size: Batch size for sampling.
Returns:
Dictionary with average modularity score and average explicitness
(train and test).
"""
del artifact_dir
scores = {}
<|code_end|>
. Use current file imports:
from disentanglement_lib.evaluation.metrics import utils
from six.moves import range
from sklearn import linear_model
from sklearn import metrics
from sklearn import preprocessing
import numpy as np
import gin.tf
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | mus_train, ys_train = utils.generate_batch_factor_code( |
Continue the code snippet: <|code_start|> "discriminator_optimizer.optimizer_fn = @AdamOptimizer",
"factor_vae.gamma = 10."
]
yield [model_config_path], factor_vae
# Test DIP-VAE.
dip_vae_i = [
"model.model = @dip_vae()", "dip_vae.lambda_d_factor = 10",
"dip_vae.dip_type = 'i'", "dip_vae.lambda_od = 10."
]
yield [model_config_path], dip_vae_i
dip_vae_ii = [
"model.model = @dip_vae()", "dip_vae.lambda_d_factor = 1",
"dip_vae.dip_type = 'ii'", "dip_vae.lambda_od = 10."
]
yield [model_config_path], dip_vae_ii
# Test BetaTCVAE.
beta_tc_vae = ["model.model = @beta_tc_vae()", "beta_tc_vae.beta = 10."]
yield [model_config_path], beta_tc_vae
class TrainTest(parameterized.TestCase):
@parameterized.parameters(list(_config_generator()))
def test_train_model(self, gin_configs, gin_bindings):
# We clear the gin config before running. Otherwise, if a prior test fails,
# the gin config is locked and the current test fails.
gin.clear_config()
<|code_end|>
. Use current file imports:
from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.methods.unsupervised import train
from disentanglement_lib.utils import resources
import gin.tf
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/methods/unsupervised/train.py
# @gin.configurable("model", blacklist=["model_dir", "overwrite"])
# def train(model_dir,
# overwrite=False,
# model=gin.REQUIRED,
# training_steps=gin.REQUIRED,
# random_seed=gin.REQUIRED,
# batch_size=gin.REQUIRED,
# eval_steps=1000,
# name="",
# model_num=None):
# """Trains the estimator and exports the snapshot and the gin config.
#
# The use of this function requires the gin binding 'dataset.name' to be
# specified as that determines the data set used for training.
#
# Args:
# model_dir: String with path to directory where model output should be saved.
# overwrite: Boolean indicating whether to overwrite output directory.
# model: GaussianEncoderModel that should be trained and exported.
# training_steps: Integer with number of training steps.
# random_seed: Integer with random seed used for training.
# batch_size: Integer with the batch size.
# eval_steps: Optional integer with number of steps used for evaluation.
# name: Optional string with name of the model (can be used to name models).
# model_num: Optional integer with model number (can be used to identify
# models).
# """
# # We do not use the variables 'name' and 'model_num'. Instead, they can be
# # used to name results as they will be part of the saved gin config.
# del name, model_num
#
# # Delete the output directory if it already exists.
# if tf.gfile.IsDirectory(model_dir):
# if overwrite:
# tf.gfile.DeleteRecursively(model_dir)
# else:
# raise ValueError("Directory already exists and overwrite is False.")
#
# # Create a numpy random state. We will sample the random seeds for training
# # and evaluation from this.
# random_state = np.random.RandomState(random_seed)
#
# # Obtain the dataset.
# dataset = named_data.get_named_ground_truth_data()
#
# # We create a TPUEstimator based on the provided model. This is primarily so
# # that we could switch to TPU training in the future. For now, we train
# # locally on GPUs.
# run_config = contrib_tpu.RunConfig(
# tf_random_seed=random_seed,
# keep_checkpoint_max=1,
# tpu_config=contrib_tpu.TPUConfig(iterations_per_loop=500))
# tpu_estimator = contrib_tpu.TPUEstimator(
# use_tpu=False,
# model_fn=model.model_fn,
# model_dir=os.path.join(model_dir, "tf_checkpoint"),
# train_batch_size=batch_size,
# eval_batch_size=batch_size,
# config=run_config)
#
# # Set up time to keep track of elapsed time in results.
# experiment_timer = time.time()
#
# # Do the actual training.
# tpu_estimator.train(
# input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
# steps=training_steps)
#
# # Save model as a TFHub module.
# output_shape = named_data.get_named_ground_truth_data().observation_shape
# module_export_path = os.path.join(model_dir, "tfhub")
# gaussian_encoder_model.export_as_tf_hub(model, output_shape,
# tpu_estimator.latest_checkpoint(),
# module_export_path)
#
# # Save the results. The result dir will contain all the results and config
# # files that we copied along, as we progress in the pipeline. The idea is that
# # these files will be available for analysis at the end.
# results_dict = tpu_estimator.evaluate(
# input_fn=_make_input_fn(
# dataset, random_state.randint(2**32), num_batches=eval_steps))
# results_dir = os.path.join(model_dir, "results")
# results_dict["elapsed_time"] = time.time() - experiment_timer
# results.update_result_directory(results_dir, "train", results_dict)
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
. Output only the next line. | train.train_with_gin(self.create_tempdir().full_path, True, gin_configs, |
Continue the code snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for train.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def _config_generator():
"""Yields all model configurations that should be tested."""
<|code_end|>
. Use current file imports:
from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.methods.unsupervised import train
from disentanglement_lib.utils import resources
import gin.tf
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/methods/unsupervised/train.py
# @gin.configurable("model", blacklist=["model_dir", "overwrite"])
# def train(model_dir,
# overwrite=False,
# model=gin.REQUIRED,
# training_steps=gin.REQUIRED,
# random_seed=gin.REQUIRED,
# batch_size=gin.REQUIRED,
# eval_steps=1000,
# name="",
# model_num=None):
# """Trains the estimator and exports the snapshot and the gin config.
#
# The use of this function requires the gin binding 'dataset.name' to be
# specified as that determines the data set used for training.
#
# Args:
# model_dir: String with path to directory where model output should be saved.
# overwrite: Boolean indicating whether to overwrite output directory.
# model: GaussianEncoderModel that should be trained and exported.
# training_steps: Integer with number of training steps.
# random_seed: Integer with random seed used for training.
# batch_size: Integer with the batch size.
# eval_steps: Optional integer with number of steps used for evaluation.
# name: Optional string with name of the model (can be used to name models).
# model_num: Optional integer with model number (can be used to identify
# models).
# """
# # We do not use the variables 'name' and 'model_num'. Instead, they can be
# # used to name results as they will be part of the saved gin config.
# del name, model_num
#
# # Delete the output directory if it already exists.
# if tf.gfile.IsDirectory(model_dir):
# if overwrite:
# tf.gfile.DeleteRecursively(model_dir)
# else:
# raise ValueError("Directory already exists and overwrite is False.")
#
# # Create a numpy random state. We will sample the random seeds for training
# # and evaluation from this.
# random_state = np.random.RandomState(random_seed)
#
# # Obtain the dataset.
# dataset = named_data.get_named_ground_truth_data()
#
# # We create a TPUEstimator based on the provided model. This is primarily so
# # that we could switch to TPU training in the future. For now, we train
# # locally on GPUs.
# run_config = contrib_tpu.RunConfig(
# tf_random_seed=random_seed,
# keep_checkpoint_max=1,
# tpu_config=contrib_tpu.TPUConfig(iterations_per_loop=500))
# tpu_estimator = contrib_tpu.TPUEstimator(
# use_tpu=False,
# model_fn=model.model_fn,
# model_dir=os.path.join(model_dir, "tf_checkpoint"),
# train_batch_size=batch_size,
# eval_batch_size=batch_size,
# config=run_config)
#
# # Set up time to keep track of elapsed time in results.
# experiment_timer = time.time()
#
# # Do the actual training.
# tpu_estimator.train(
# input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
# steps=training_steps)
#
# # Save model as a TFHub module.
# output_shape = named_data.get_named_ground_truth_data().observation_shape
# module_export_path = os.path.join(model_dir, "tfhub")
# gaussian_encoder_model.export_as_tf_hub(model, output_shape,
# tpu_estimator.latest_checkpoint(),
# module_export_path)
#
# # Save the results. The result dir will contain all the results and config
# # files that we copied along, as we progress in the pipeline. The idea is that
# # these files will be available for analysis at the end.
# results_dict = tpu_estimator.evaluate(
# input_fn=_make_input_fn(
# dataset, random_state.randint(2**32), num_batches=eval_steps))
# results_dir = os.path.join(model_dir, "results")
# results_dict["elapsed_time"] = time.time() - experiment_timer
# results.update_result_directory(results_dir, "train", results_dict)
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
. Output only the next line. | model_config_path = resources.get_file( |
Given the following code snippet before the placeholder: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for convolute_hub.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class ConvoluteHubTest(tf.test.TestCase):
def test_convolute(self):
# Create variables to use.
random_state = np.random.RandomState(0)
data = random_state.normal(size=(5, 10))
variable1 = random_state.normal(size=(10, 6))
variable2 = random_state.normal(size=(6, 2))
# Save variables to checkpoint.
checkpoint_path = os.path.join(self.get_temp_dir(), "checkpoint.ckpt")
<|code_end|>
, predict the next line using imports from the current file:
import os
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
from disentanglement_lib.utils import convolute_hub
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/utils/convolute_hub.py
# def convolute_and_save(module_path, signature, export_path, transform_fn,
# transform_checkpoint_path, new_signature=None):
# def module_fn():
# def save_numpy_arrays_to_checkpoint(checkpoint_path, **dict_with_arrays):
# def _placeholders_from_module(tfhub_module, signature):
. Output only the next line. | convolute_hub.save_numpy_arrays_to_checkpoint( |
Given the code snippet: <|code_start|># Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for mig.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def _identity_discretizer(target, num_bins):
del num_bins
return target
class MIGTest(absltest.TestCase):
def test_metric(self):
gin.bind_parameter("discretizer.discretizer_fn", _identity_discretizer)
gin.bind_parameter("discretizer.num_bins", 10)
<|code_end|>
, generate the next line using the imports in this file:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import mig
import numpy as np
import gin.tf
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/mig.py
# def compute_mig(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# batch_size=16):
# def _compute_mig(mus_train, ys_train):
# def compute_mig_on_fixed_data(observations, labels, representation_function,
# batch_size=100):
. Output only the next line. | ground_truth_data = dummy_data.IdentityObservationsData() |
Given the code snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for mig.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def _identity_discretizer(target, num_bins):
del num_bins
return target
class MIGTest(absltest.TestCase):
def test_metric(self):
gin.bind_parameter("discretizer.discretizer_fn", _identity_discretizer)
gin.bind_parameter("discretizer.num_bins", 10)
ground_truth_data = dummy_data.IdentityObservationsData()
representation_function = lambda x: x
random_state = np.random.RandomState(0)
<|code_end|>
, generate the next line using the imports in this file:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import mig
import numpy as np
import gin.tf
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/mig.py
# def compute_mig(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# batch_size=16):
# def _compute_mig(mus_train, ys_train):
# def compute_mig_on_fixed_data(observations, labels, representation_function,
# batch_size=100):
. Output only the next line. | scores = mig.compute_mig( |
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""MPI3D data set."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, predict the next line using imports from the current file:
import os
import numpy as np
import tensorflow.compat.v1 as tf
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
. Output only the next line. | class MPI3D(ground_truth_data.GroundTruthData): |
Given the code snippet: <|code_start|> elif mode == "mpi3d_realistic":
mpi3d_path = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "mpi3d_realistic",
"mpi3d_realistic.npz")
if not tf.io.gfile.exists(mpi3d_path):
raise ValueError(
"Dataset '{}' not found. Make sure the dataset is publicly available and downloaded correctly."
.format(mode))
else:
with tf.io.gfile.GFile(mpi3d_path, "rb") as f:
data = np.load(f)
self.factor_sizes = [4, 4, 2, 3, 3, 40, 40]
elif mode == "mpi3d_real":
mpi3d_path = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "mpi3d_real",
"mpi3d_real.npz")
if not tf.io.gfile.exists(mpi3d_path):
raise ValueError(
"Dataset '{}' not found. Make sure the dataset is publicly available and downloaded correctly."
.format(mode))
else:
with tf.io.gfile.GFile(mpi3d_path, "rb") as f:
data = np.load(f)
self.factor_sizes = [6, 6, 2, 3, 3, 40, 40]
else:
raise ValueError("Unknown mode provided.")
self.images = data["images"]
self.latent_factor_indices = [0, 1, 2, 3, 4, 5, 6]
self.num_total_factors = 7
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
import tensorflow.compat.v1 as tf
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
. Output only the next line. | self.state_space = util.SplitDiscreteStateSpace(self.factor_sizes, |
Based on the snippet: <|code_start|> np.testing.assert_allclose(result, 2./3.)
def test_zero(self):
importance_matrix = np.zeros(shape=[10, 10], dtype=np.float64)
result = modularity_explicitness.modularity(importance_matrix)
np.testing.assert_allclose(result, .0)
def test_redundant_codes(self):
importance_matrix = np.diag(5.*np.ones(5))
importance_matrix = np.vstack([importance_matrix, importance_matrix])
result = modularity_explicitness.modularity(importance_matrix)
np.testing.assert_allclose(result, 1.)
def test_missed_factors(self):
importance_matrix = np.diag(5.*np.ones(5))
result = modularity_explicitness.modularity(importance_matrix[:2, :])
np.testing.assert_allclose(result, 1.0)
def test_one_code_two_factors(self):
importance_matrix = np.diag(5.*np.ones(5))
importance_matrix = np.hstack([importance_matrix, importance_matrix])
result = modularity_explicitness.modularity(importance_matrix)
np.testing.assert_allclose(result, 1. - 1./9)
class ModularityExplicitnessTest(absltest.TestCase):
def test_metric(self):
gin.bind_parameter("discretizer.discretizer_fn", _identity_discretizer)
gin.bind_parameter("discretizer.num_bins", 10)
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import modularity_explicitness
from six.moves import range
import numpy as np
import gin.tf
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/modularity_explicitness.py
# def compute_modularity_explicitness(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def explicitness_per_factor(mus_train, y_train, mus_test, y_test):
# def modularity(mutual_information):
. Output only the next line. | ground_truth_data = dummy_data.IdentityObservationsData() |
Predict the next line for this snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for modularity_explicitness.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def _identity_discretizer(target, num_bins):
del num_bins
return target
class ModularityTest(absltest.TestCase):
def test_diagonal(self):
importance_matrix = np.diag(5.*np.ones(5))
<|code_end|>
with the help of current file imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import modularity_explicitness
from six.moves import range
import numpy as np
import gin.tf
and context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/modularity_explicitness.py
# def compute_modularity_explicitness(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def explicitness_per_factor(mus_train, y_train, mus_test, y_test):
# def modularity(mutual_information):
, which may contain function names, class names, or code. Output only the next line. | result = modularity_explicitness.modularity(importance_matrix) |
Given the following code snippet before the placeholder: <|code_start|> for examples).
random_seed: Integer with random seed used for postprocessing (may be
unused).
name: Optional string with name of the representation (can be used to name
representations).
"""
# We do not use the variable 'name'. Instead, it can be used to name
# representations as it will be part of the saved gin config.
del name
# Delete the output directory if it already exists.
if tf.gfile.IsDirectory(output_dir):
if overwrite:
tf.gfile.DeleteRecursively(output_dir)
else:
raise ValueError("Directory already exists and overwrite is False.")
# Set up timer to keep track of elapsed time in results.
experiment_timer = time.time()
# Automatically set the proper data set if necessary. We replace the active
# gin config as this will lead to a valid gin config file where the data set
# is present.
if gin.query_parameter("dataset.name") == "auto":
# Obtain the dataset name from the gin config of the previous step.
gin_config_file = os.path.join(model_dir, "results", "gin", "train.gin")
gin_dict = results.gin_dict(gin_config_file)
with gin.unlock_config():
gin.bind_parameter("dataset.name", gin_dict["dataset.name"].replace(
"'", ""))
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.postprocessing import methods # pylint: disable=unused-import
from disentanglement_lib.utils import convolute_hub
from disentanglement_lib.utils import results
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/postprocessing/methods.py
# def mean_representation(
# ground_truth_data,
# gaussian_encoder,
# random_state,
# save_path,
# ):
# def transform_fn(mean, logvar):
# def sampled_representation(ground_truth_data, gaussian_encoder, random_state,
# save_path):
# def transform_fn(mean, logvar):
#
# Path: disentanglement_lib/utils/convolute_hub.py
# def convolute_and_save(module_path, signature, export_path, transform_fn,
# transform_checkpoint_path, new_signature=None):
# def module_fn():
# def save_numpy_arrays_to_checkpoint(checkpoint_path, **dict_with_arrays):
# def _placeholders_from_module(tfhub_module, signature):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | dataset = named_data.get_named_ground_truth_data() |
Based on the snippet: <|code_start|> # Obtain the dataset name from the gin config of the previous step.
gin_config_file = os.path.join(model_dir, "results", "gin", "train.gin")
gin_dict = results.gin_dict(gin_config_file)
with gin.unlock_config():
gin.bind_parameter("dataset.name", gin_dict["dataset.name"].replace(
"'", ""))
dataset = named_data.get_named_ground_truth_data()
# Path to TFHub module of previously trained model.
module_path = os.path.join(model_dir, "tfhub")
with hub.eval_function_for_module(module_path) as f:
def _gaussian_encoder(x):
"""Encodes images using trained model."""
# Push images through the TFHub module.
output = f(dict(images=x), signature="gaussian_encoder", as_dict=True)
# Convert to numpy arrays and return.
return {key: np.array(values) for key, values in output.items()}
# Run the postprocessing function which returns a transformation function
# that can be used to create the representation from the mean and log
# variance of the Gaussian distribution given by the encoder. Also returns
# path to a checkpoint if the transformation requires variables.
transform_fn, transform_checkpoint_path = postprocess_fn(
dataset, _gaussian_encoder, np.random.RandomState(random_seed),
output_dir)
# Takes the "gaussian_encoder" signature, extracts the representation and
# then saves under the signature "representation".
tfhub_module_dir = os.path.join(output_dir, "tfhub")
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.postprocessing import methods # pylint: disable=unused-import
from disentanglement_lib.utils import convolute_hub
from disentanglement_lib.utils import results
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/postprocessing/methods.py
# def mean_representation(
# ground_truth_data,
# gaussian_encoder,
# random_state,
# save_path,
# ):
# def transform_fn(mean, logvar):
# def sampled_representation(ground_truth_data, gaussian_encoder, random_state,
# save_path):
# def transform_fn(mean, logvar):
#
# Path: disentanglement_lib/utils/convolute_hub.py
# def convolute_and_save(module_path, signature, export_path, transform_fn,
# transform_checkpoint_path, new_signature=None):
# def module_fn():
# def save_numpy_arrays_to_checkpoint(checkpoint_path, **dict_with_arrays):
# def _placeholders_from_module(tfhub_module, signature):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | convolute_hub.convolute_and_save( |
Here is a snippet: <|code_start|> model_dir: String with path to directory where the model is saved.
output_dir: String with the path where the representation should be saved.
overwrite: Boolean indicating whether to overwrite output directory.
postprocess_fn: Function used to extract the representation (see methods.py
for examples).
random_seed: Integer with random seed used for postprocessing (may be
unused).
name: Optional string with name of the representation (can be used to name
representations).
"""
# We do not use the variable 'name'. Instead, it can be used to name
# representations as it will be part of the saved gin config.
del name
# Delete the output directory if it already exists.
if tf.gfile.IsDirectory(output_dir):
if overwrite:
tf.gfile.DeleteRecursively(output_dir)
else:
raise ValueError("Directory already exists and overwrite is False.")
# Set up timer to keep track of elapsed time in results.
experiment_timer = time.time()
# Automatically set the proper data set if necessary. We replace the active
# gin config as this will lead to a valid gin config file where the data set
# is present.
if gin.query_parameter("dataset.name") == "auto":
# Obtain the dataset name from the gin config of the previous step.
gin_config_file = os.path.join(model_dir, "results", "gin", "train.gin")
<|code_end|>
. Write the next line using the current file imports:
import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.postprocessing import methods # pylint: disable=unused-import
from disentanglement_lib.utils import convolute_hub
from disentanglement_lib.utils import results
and context from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/postprocessing/methods.py
# def mean_representation(
# ground_truth_data,
# gaussian_encoder,
# random_state,
# save_path,
# ):
# def transform_fn(mean, logvar):
# def sampled_representation(ground_truth_data, gaussian_encoder, random_state,
# save_path):
# def transform_fn(mean, logvar):
#
# Path: disentanglement_lib/utils/convolute_hub.py
# def convolute_and_save(module_path, signature, export_path, transform_fn,
# transform_checkpoint_path, new_signature=None):
# def module_fn():
# def save_numpy_arrays_to_checkpoint(checkpoint_path, **dict_with_arrays):
# def _placeholders_from_module(tfhub_module, signature):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
, which may include functions, classes, or code. Output only the next line. | gin_dict = results.gin_dict(gin_config_file) |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Cars3D data set."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
CARS3D_PATH = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "cars")
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy as np
import PIL
import scipy.io as sio
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
from sklearn.utils import extmath
from tensorflow.compat.v1 import gfile
and context from other files:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
, which may include functions, classes, or code. Output only the next line. | class Cars3D(ground_truth_data.GroundTruthData): |
Based on the snippet: <|code_start|>"""Cars3D data set."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
CARS3D_PATH = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "cars")
class Cars3D(ground_truth_data.GroundTruthData):
"""Cars3D data set.
The data set was first used in the paper "Deep Visual Analogy-Making"
(https://papers.nips.cc/paper/5845-deep-visual-analogy-making) and can be
downloaded from http://www.scottreed.info/. The images are rescaled to 64x64.
The ground-truth factors of variation are:
0 - elevation (4 different values)
1 - azimuth (24 different values)
2 - object type (183 different values)
"""
def __init__(self):
self.factor_sizes = [4, 24, 183]
features = extmath.cartesian(
[np.array(list(range(i))) for i in self.factor_sizes])
self.latent_factor_indices = [0, 1, 2]
self.num_total_factors = features.shape[1]
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import numpy as np
import PIL
import scipy.io as sio
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
from sklearn.utils import extmath
from tensorflow.compat.v1 import gfile
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
. Output only the next line. | self.index = util.StateSpaceAtomIndex(self.factor_sizes, features) |
Given the code snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Different studies that can be reproduced."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, generate the next line using the imports in this file:
from disentanglement_lib.config.abstract_reasoning_study_v1.stage1 import sweep as abstract_reasoning_study_v1
from disentanglement_lib.config.fairness_study_v1 import sweep as fairness_study_v1
from disentanglement_lib.config.tests import sweep as tests
from disentanglement_lib.config.unsupervised_study_v1 import sweep as unsupervised_study_v1
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/config/abstract_reasoning_study_v1/stage1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class AbstractReasoningStudyV1(study.Study):
#
# Path: disentanglement_lib/config/fairness_study_v1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class FairnessStudyV1(study.Study):
#
# Path: disentanglement_lib/config/tests/sweep.py
# class TestStudy(study.Study):
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
#
# Path: disentanglement_lib/config/unsupervised_study_v1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class UnsupervisedStudyV1(study.Study):
. Output only the next line. | from disentanglement_lib.config.abstract_reasoning_study_v1.stage1 import sweep as abstract_reasoning_study_v1 |
Given the code snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Different studies that can be reproduced."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, generate the next line using the imports in this file:
from disentanglement_lib.config.abstract_reasoning_study_v1.stage1 import sweep as abstract_reasoning_study_v1
from disentanglement_lib.config.fairness_study_v1 import sweep as fairness_study_v1
from disentanglement_lib.config.tests import sweep as tests
from disentanglement_lib.config.unsupervised_study_v1 import sweep as unsupervised_study_v1
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/config/abstract_reasoning_study_v1/stage1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class AbstractReasoningStudyV1(study.Study):
#
# Path: disentanglement_lib/config/fairness_study_v1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class FairnessStudyV1(study.Study):
#
# Path: disentanglement_lib/config/tests/sweep.py
# class TestStudy(study.Study):
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
#
# Path: disentanglement_lib/config/unsupervised_study_v1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class UnsupervisedStudyV1(study.Study):
. Output only the next line. | from disentanglement_lib.config.fairness_study_v1 import sweep as fairness_study_v1 |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Different studies that can be reproduced."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
. Write the next line using the current file imports:
from disentanglement_lib.config.abstract_reasoning_study_v1.stage1 import sweep as abstract_reasoning_study_v1
from disentanglement_lib.config.fairness_study_v1 import sweep as fairness_study_v1
from disentanglement_lib.config.tests import sweep as tests
from disentanglement_lib.config.unsupervised_study_v1 import sweep as unsupervised_study_v1
and context from other files:
# Path: disentanglement_lib/config/abstract_reasoning_study_v1/stage1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class AbstractReasoningStudyV1(study.Study):
#
# Path: disentanglement_lib/config/fairness_study_v1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class FairnessStudyV1(study.Study):
#
# Path: disentanglement_lib/config/tests/sweep.py
# class TestStudy(study.Study):
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
#
# Path: disentanglement_lib/config/unsupervised_study_v1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class UnsupervisedStudyV1(study.Study):
, which may include functions, classes, or code. Output only the next line. | from disentanglement_lib.config.tests import sweep as tests |
Next line prediction: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Different studies that can be reproduced."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
. Use current file imports:
(from disentanglement_lib.config.abstract_reasoning_study_v1.stage1 import sweep as abstract_reasoning_study_v1
from disentanglement_lib.config.fairness_study_v1 import sweep as fairness_study_v1
from disentanglement_lib.config.tests import sweep as tests
from disentanglement_lib.config.unsupervised_study_v1 import sweep as unsupervised_study_v1)
and context including class names, function names, or small code snippets from other files:
# Path: disentanglement_lib/config/abstract_reasoning_study_v1/stage1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class AbstractReasoningStudyV1(study.Study):
#
# Path: disentanglement_lib/config/fairness_study_v1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class FairnessStudyV1(study.Study):
#
# Path: disentanglement_lib/config/tests/sweep.py
# class TestStudy(study.Study):
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
#
# Path: disentanglement_lib/config/unsupervised_study_v1/sweep.py
# def get_datasets():
# def get_num_latent(sweep):
# def get_seeds(num):
# def get_default_models():
# def get_config():
# def get_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def get_eval_config_files(self):
# class UnsupervisedStudyV1(study.Study):
. Output only the next line. | from disentanglement_lib.config.unsupervised_study_v1 import sweep as unsupervised_study_v1 |
Given the code snippet: <|code_start|> is_training = (mode == tf.estimator.ModeKeys.TRAIN)
data_shape = features.get_shape().as_list()[1:]
data_shape[0] = int(data_shape[0] / 2)
features_1 = features[:, :data_shape[0], :, :]
features_2 = features[:, data_shape[0]:, :, :]
with tf.variable_scope(
tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
z_mean, z_logvar = self.gaussian_encoder(features_1,
is_training=is_training)
z_mean_2, z_logvar_2 = self.gaussian_encoder(features_2,
is_training=is_training)
labels = tf.squeeze(tf.one_hot(labels, z_mean.get_shape().as_list()[1]))
kl_per_point = compute_kl(z_mean, z_mean_2, z_logvar, z_logvar_2)
new_mean = 0.5 * z_mean + 0.5 * z_mean_2
var_1 = tf.exp(z_logvar)
var_2 = tf.exp(z_logvar_2)
new_log_var = tf.math.log(0.5*var_1 + 0.5*var_2)
mean_sample_1, log_var_sample_1 = self.aggregate(
z_mean, z_logvar, new_mean, new_log_var, labels, kl_per_point)
mean_sample_2, log_var_sample_2 = self.aggregate(
z_mean_2, z_logvar_2, new_mean, new_log_var, labels, kl_per_point)
z_sampled_1 = self.sample_from_latent_distribution(
mean_sample_1, log_var_sample_1)
z_sampled_2 = self.sample_from_latent_distribution(
mean_sample_2, log_var_sample_2)
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
reconstructions_1 = self.decode(z_sampled_1, data_shape, is_training)
reconstructions_2 = self.decode(z_sampled_2, data_shape, is_training)
<|code_end|>
, generate the next line using the imports in this file:
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import vae
from six.moves import zip
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec
import tensorflow.compat.v1 as tf
import gin.tf
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
. Output only the next line. | per_sample_loss_1 = losses.make_reconstruction_loss( |
Next line prediction: <|code_start|> mean_sample_1, log_var_sample_1 = self.aggregate(
z_mean, z_logvar, new_mean, new_log_var, labels, kl_per_point)
mean_sample_2, log_var_sample_2 = self.aggregate(
z_mean_2, z_logvar_2, new_mean, new_log_var, labels, kl_per_point)
z_sampled_1 = self.sample_from_latent_distribution(
mean_sample_1, log_var_sample_1)
z_sampled_2 = self.sample_from_latent_distribution(
mean_sample_2, log_var_sample_2)
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
reconstructions_1 = self.decode(z_sampled_1, data_shape, is_training)
reconstructions_2 = self.decode(z_sampled_2, data_shape, is_training)
per_sample_loss_1 = losses.make_reconstruction_loss(
features_1, reconstructions_1)
per_sample_loss_2 = losses.make_reconstruction_loss(
features_2, reconstructions_2)
reconstruction_loss_1 = tf.reduce_mean(per_sample_loss_1)
reconstruction_loss_2 = tf.reduce_mean(per_sample_loss_2)
reconstruction_loss = (0.5 * reconstruction_loss_1 +
0.5 * reconstruction_loss_2)
kl_loss_1 = vae.compute_gaussian_kl(mean_sample_1, log_var_sample_1)
kl_loss_2 = vae.compute_gaussian_kl(mean_sample_2, log_var_sample_2)
kl_loss = 0.5 * kl_loss_1 + 0.5 * kl_loss_2
regularizer = self.regularizer(
kl_loss, None, None, None)
loss = tf.add(reconstruction_loss,
regularizer,
name="loss")
elbo = tf.add(reconstruction_loss, kl_loss, name="elbo")
if mode == tf.estimator.ModeKeys.TRAIN:
<|code_end|>
. Use current file imports:
(from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import vae
from six.moves import zip
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec
import tensorflow.compat.v1 as tf
import gin.tf)
and context including class names, function names, or small code snippets from other files:
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
. Output only the next line. | optimizer = optimizers.make_vae_optimizer() |
Given snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library of losses for weakly-supervised disentanglement learning.
Implementation of weakly-supervised VAE based models from the paper
"Weakly-Supervised Disentanglement Without Compromises"
https://arxiv.org/pdf/2002.02886.pdf.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
@gin.configurable("weak_loss", blacklist=["z1", "z2", "labels"])
def make_weak_loss(z1, z2, labels, loss_fn=gin.REQUIRED):
"""Wrapper that creates weakly-supervised losses."""
return loss_fn(z1, z2, labels)
@gin.configurable("group_vae")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import vae
from six.moves import zip
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec
import tensorflow.compat.v1 as tf
import gin.tf
and context:
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
which might include code, classes, or functions. Output only the next line. | class GroupVAEBase(vae.BaseVAE): |
Given snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for unified_scores.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
def _identity_discretizer(target, num_bins):
del num_bins
return target
class StrongDownstreamTaskTest(absltest.TestCase):
def test_intervene(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import strong_downstream_task
from disentanglement_lib.evaluation.metrics import utils
import numpy as np
import gin.tf
and context:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/strong_downstream_task.py
# def compute_strong_downstream_task(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# n_experiment=gin.REQUIRED):
# def _compute_loss(x_train, y_train, x_test, y_test, predictor_fn):
# def _compute_loss_intervene(factors_train, factors_test, predictor_fn,
# ground_truth_data, representation_function,
# random_state, n_experiment=10):
# def intervene(y_train, y_test, target_y, num_factors, ground_truth_data):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
which might include code, classes, or functions. Output only the next line. | ground_truth_data = dummy_data.DummyData() |
Here is a snippet: <|code_start|># limitations under the License.
"""Tests for unified_scores.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
def _identity_discretizer(target, num_bins):
del num_bins
return target
class StrongDownstreamTaskTest(absltest.TestCase):
def test_intervene(self):
ground_truth_data = dummy_data.DummyData()
random_state = np.random.RandomState(0)
ys_train = ground_truth_data.sample_factors(1000, random_state)
ys_test = ground_truth_data.sample_factors(1000, random_state)
num_factors = ys_train.shape[1]
for i in range(num_factors):
(y_train_int, y_test_int, interv_factor,
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import strong_downstream_task
from disentanglement_lib.evaluation.metrics import utils
import numpy as np
import gin.tf
and context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/strong_downstream_task.py
# def compute_strong_downstream_task(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# n_experiment=gin.REQUIRED):
# def _compute_loss(x_train, y_train, x_test, y_test, predictor_fn):
# def _compute_loss_intervene(factors_train, factors_test, predictor_fn,
# ground_truth_data, representation_function,
# random_state, n_experiment=10):
# def intervene(y_train, y_test, target_y, num_factors, ground_truth_data):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
, which may include functions, classes, or code. Output only the next line. | factor_interv_train) = strong_downstream_task.intervene( |
Next line prediction: <|code_start|>
def _identity_discretizer(target, num_bins):
del num_bins
return target
class StrongDownstreamTaskTest(absltest.TestCase):
def test_intervene(self):
ground_truth_data = dummy_data.DummyData()
random_state = np.random.RandomState(0)
ys_train = ground_truth_data.sample_factors(1000, random_state)
ys_test = ground_truth_data.sample_factors(1000, random_state)
num_factors = ys_train.shape[1]
for i in range(num_factors):
(y_train_int, y_test_int, interv_factor,
factor_interv_train) = strong_downstream_task.intervene(
ys_train.copy(), ys_test.copy(), i, num_factors, ground_truth_data)
assert interv_factor != i, "Wrong factor interevened on."
assert (y_train_int[:, interv_factor] == factor_interv_train
).all(), "Training set not intervened on."
assert (y_test_int[:, interv_factor] != factor_interv_train
).all(), "Training set not intervened on."
def test_task(self):
gin.bind_parameter("predictor.predictor_fn",
<|code_end|>
. Use current file imports:
(from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import strong_downstream_task
from disentanglement_lib.evaluation.metrics import utils
import numpy as np
import gin.tf)
and context including class names, function names, or small code snippets from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/strong_downstream_task.py
# def compute_strong_downstream_task(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# n_experiment=gin.REQUIRED):
# def _compute_loss(x_train, y_train, x_test, y_test, predictor_fn):
# def _compute_loss_intervene(factors_train, factors_test, predictor_fn,
# ground_truth_data, representation_function,
# random_state, n_experiment=10):
# def intervene(y_train, y_test, target_y, num_factors, ground_truth_data):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | utils.gradient_boosting_classifier) |
Using the snippet: <|code_start|># Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""SmallNORB dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
SMALLNORB_TEMPLATE = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "small_norb",
"smallnorb-{}-{}.mat")
SMALLNORB_CHUNKS = [
"5x46789x9x18x6x2x96x96-training",
"5x01235x9x18x6x2x96x96-testing",
]
<|code_end|>
, determine the next line of code. You have imports:
import os
import numpy as np
import PIL
import tensorflow.compat.v1 as tf
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
from six.moves import zip
and context (class names, function names, or code) available:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
. Output only the next line. | class SmallNORB(ground_truth_data.GroundTruthData): |
Using the snippet: <|code_start|> "smallnorb-{}-{}.mat")
SMALLNORB_CHUNKS = [
"5x46789x9x18x6x2x96x96-training",
"5x01235x9x18x6x2x96x96-testing",
]
class SmallNORB(ground_truth_data.GroundTruthData):
"""SmallNORB dataset.
The data set can be downloaded from
https://cs.nyu.edu/~ylclab/data/norb-v1.0-small/. Images are resized to 64x64.
The ground-truth factors of variation are:
0 - category (5 different values)
1 - elevation (9 different values)
2 - azimuth (18 different values)
3 - lighting condition (6 different values)
The instance in each category is randomly sampled when generating the images.
"""
def __init__(self):
self.images, features = _load_small_norb_chunks(SMALLNORB_TEMPLATE,
SMALLNORB_CHUNKS)
self.factor_sizes = [5, 10, 9, 18, 6]
# Instances are not part of the latent space.
self.latent_factor_indices = [0, 2, 3, 4]
self.num_total_factors = features.shape[1]
<|code_end|>
, determine the next line of code. You have imports:
import os
import numpy as np
import PIL
import tensorflow.compat.v1 as tf
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
from six.moves import zip
and context (class names, function names, or code) available:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
. Output only the next line. | self.index = util.StateSpaceAtomIndex(self.factor_sizes, features) |
Given snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Shapes3D data set."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
SHAPES3D_PATH = os.path.join(
os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "3dshapes",
"look-at-object-room_floor-hueXwall-hueXobj-"
"hueXobj-sizeXobj-shapeXview-azi.npz"
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
import tensorflow.compat.v1 as tf
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
and context:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
which might include code, classes, or functions. Output only the next line. | class Shapes3D(ground_truth_data.GroundTruthData): |
Here is a snippet: <|code_start|>
class Shapes3D(ground_truth_data.GroundTruthData):
"""Shapes3D dataset.
The data set was originally introduced in "Disentangling by Factorising".
The ground-truth factors of variation are:
0 - floor color (10 different values)
1 - wall color (10 different values)
2 - object color (10 different values)
3 - object size (8 different values)
4 - object type (4 different values)
5 - azimuth (15 different values)
"""
def __init__(self):
with tf.gfile.GFile(SHAPES3D_PATH, "rb") as f:
# Data was saved originally using python2, so we need to set the encoding.
data = np.load(f, encoding="latin1")
images = data["images"]
labels = data["labels"]
n_samples = np.prod(images.shape[0:6])
self.images = (
images.reshape([n_samples, 64, 64, 3]).astype(np.float32) / 255.)
features = labels.reshape([n_samples, 6])
self.factor_sizes = [10, 10, 10, 8, 4, 15]
self.latent_factor_indices = list(range(6))
self.num_total_factors = features.shape[1]
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy as np
import tensorflow.compat.v1 as tf
from disentanglement_lib.data.ground_truth import ground_truth_data
from disentanglement_lib.data.ground_truth import util
from six.moves import range
and context from other files:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
, which may include functions, classes, or code. Output only the next line. | self.state_space = util.SplitDiscreteStateSpace(self.factor_sizes, |
Continue the code snippet: <|code_start|> lambda_d_factor = h.fixed("dip_vae.lambda_d_factor", 1.)
dip_type = h.fixed("dip_vae.dip_type", "ii")
config_dip_vae_ii = h.zipit(
[model_name, model_fn, lambda_od, lambda_d_factor, dip_type])
# BetaTCVAE config.
model_name = h.fixed("model.name", "beta_tc_vae")
model_fn = h.fixed("model.model", "@beta_tc_vae()")
betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.]))
config_beta_tc_vae = h.zipit([model_name, model_fn, betas])
all_models = h.chainit([
config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii,
config_beta_tc_vae, config_annealed_beta_vae
])
return all_models
def get_config():
"""Returns the hyperparameter configs for different experiments."""
arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1)
arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1)
architecture = h.zipit([arch_enc, arch_dec])
return h.product([
get_datasets(),
architecture,
get_default_models(),
get_seeds(50),
])
<|code_end|>
. Use current file imports:
from disentanglement_lib.config import study
from disentanglement_lib.utils import resources
from six.moves import range
import disentanglement_lib.utils.hyperparams as h
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/config/study.py
# class Study(object):
# def get_model_config(self, model_num=0):
# def print_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def print_postprocess_config(self):
# def get_eval_config_files(self):
# def print_eval_config(self):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
. Output only the next line. | class UnsupervisedStudyV1(study.Study): |
Here is a snippet: <|code_start|> model_fn = h.fixed("model.model", "@beta_tc_vae()")
betas = h.sweep("beta_tc_vae.beta", h.discrete([1., 2., 4., 6., 8., 10.]))
config_beta_tc_vae = h.zipit([model_name, model_fn, betas])
all_models = h.chainit([
config_beta_vae, config_factor_vae, config_dip_vae_i, config_dip_vae_ii,
config_beta_tc_vae, config_annealed_beta_vae
])
return all_models
def get_config():
"""Returns the hyperparameter configs for different experiments."""
arch_enc = h.fixed("encoder.encoder_fn", "@conv_encoder", length=1)
arch_dec = h.fixed("decoder.decoder_fn", "@deconv_decoder", length=1)
architecture = h.zipit([arch_enc, arch_dec])
return h.product([
get_datasets(),
architecture,
get_default_models(),
get_seeds(50),
])
class UnsupervisedStudyV1(study.Study):
"""Defines the study for the paper."""
def get_model_config(self, model_num=0):
"""Returns model bindings and config file."""
config = get_config()[model_num]
model_bindings = h.to_bindings(config)
<|code_end|>
. Write the next line using the current file imports:
from disentanglement_lib.config import study
from disentanglement_lib.utils import resources
from six.moves import range
import disentanglement_lib.utils.hyperparams as h
and context from other files:
# Path: disentanglement_lib/config/study.py
# class Study(object):
# def get_model_config(self, model_num=0):
# def print_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def print_postprocess_config(self):
# def get_eval_config_files(self):
# def print_eval_config(self):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
, which may include functions, classes, or code. Output only the next line. | model_config_file = resources.get_file( |
Predict the next line after this snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test study."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
using the current file's imports:
from disentanglement_lib.config import study
from disentanglement_lib.utils import resources
and any relevant context from other files:
# Path: disentanglement_lib/config/study.py
# class Study(object):
# def get_model_config(self, model_num=0):
# def print_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def print_postprocess_config(self):
# def get_eval_config_files(self):
# def print_eval_config(self):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
. Output only the next line. | class TestStudy(study.Study): |
Given snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test study."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class TestStudy(study.Study):
"""Defines a study for testing."""
def get_model_config(self, model_num=0):
"""Returns model bindings and config file."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from disentanglement_lib.config import study
from disentanglement_lib.utils import resources
and context:
# Path: disentanglement_lib/config/study.py
# class Study(object):
# def get_model_config(self, model_num=0):
# def print_model_config(self, model_num=0):
# def get_postprocess_config_files(self):
# def print_postprocess_config(self):
# def get_eval_config_files(self):
# def print_eval_config(self):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
which might include code, classes, or functions. Output only the next line. | return [], resources.get_file( |
Here is a snippet: <|code_start|>
def __init__(self, factor_sizes, gamma=gin.REQUIRED, gamma_sup=gin.REQUIRED):
"""Creates a semi-supervised FactorVAE model.
Implementing Eq. 2 of "Disentangling by Factorizing"
(https://arxiv.org/pdf/1802.05983).
Args:
factor_sizes: Size of each factor of variation.
gamma: Hyperparameter for the unsupervised regularizer.
gamma_sup: Hyperparameter for the supervised regularizer.
"""
self.gamma = gamma
self.gamma_sup = gamma_sup
super(S2FactorVAE, self).__init__(factor_sizes)
def model_fn(self, features, labels, mode, params):
"""TPUEstimator compatible model function."""
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
labelled_features = labels[0]
labels = tf.to_float(labels[1])
data_shape = features.get_shape().as_list()[1:]
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
z_mean, z_logvar = self.gaussian_encoder(
features, is_training=is_training)
z_mean_labelled, _ = self.gaussian_encoder(
labelled_features, is_training=is_training)
z_sampled = self.sample_from_latent_distribution(z_mean, z_logvar)
z_shuffle = vae.shuffle_codes(z_sampled)
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
<|code_end|>
. Write the next line using the current file imports:
from disentanglement_lib.methods.shared import architectures # pylint: disable=unused-import
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import vae
from six.moves import zip
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf
and context from other files:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
#
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
, which may include functions, classes, or code. Output only the next line. | logits_z, probs_z = architectures.make_discriminator( |
Predict the next line after this snippet: <|code_start|> """Abstract base class of a basic semi-supervised Gaussian encoder model."""
def __init__(self, factor_sizes):
self.factor_sizes = factor_sizes
def model_fn(self, features, labels, mode, params):
"""TPUEstimator compatible model function.
Args:
features: Batch of images [batch_size, 64, 64, 3].
labels: Tuple with batch of features [batch_size, 64, 64, 3] and the
labels [batch_size, labels_size].
mode: Mode for the TPUEstimator.
params: Dict with parameters.
Returns:
TPU estimator.
"""
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
labelled_features = labels[0]
labels = tf.to_float(labels[1])
data_shape = features.get_shape().as_list()[1:]
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
z_mean, z_logvar = self.gaussian_encoder(
features, is_training=is_training)
z_mean_labelled, _ = self.gaussian_encoder(
labelled_features, is_training=is_training)
z_sampled = self.sample_from_latent_distribution(z_mean, z_logvar)
reconstructions = self.decode(z_sampled, data_shape, is_training)
<|code_end|>
using the current file's imports:
from disentanglement_lib.methods.shared import architectures # pylint: disable=unused-import
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import vae
from six.moves import zip
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf
and any relevant context from other files:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
#
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
. Output only the next line. | per_sample_loss = losses.make_reconstruction_loss(features, reconstructions) |
Predict the next line after this snippet: <|code_start|> labels [batch_size, labels_size].
mode: Mode for the TPUEstimator.
params: Dict with parameters.
Returns:
TPU estimator.
"""
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
labelled_features = labels[0]
labels = tf.to_float(labels[1])
data_shape = features.get_shape().as_list()[1:]
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
z_mean, z_logvar = self.gaussian_encoder(
features, is_training=is_training)
z_mean_labelled, _ = self.gaussian_encoder(
labelled_features, is_training=is_training)
z_sampled = self.sample_from_latent_distribution(z_mean, z_logvar)
reconstructions = self.decode(z_sampled, data_shape, is_training)
per_sample_loss = losses.make_reconstruction_loss(features, reconstructions)
reconstruction_loss = tf.reduce_mean(per_sample_loss)
kl_loss = compute_gaussian_kl(z_mean, z_logvar)
gamma_annealed = make_annealer(self.gamma_sup, tf.train.get_global_step())
supervised_loss = make_supervised_loss(z_mean_labelled, labels,
self.factor_sizes)
regularizer = self.unsupervised_regularizer(
kl_loss, z_mean, z_logvar, z_sampled) + gamma_annealed * supervised_loss
loss = tf.add(reconstruction_loss, regularizer, name="loss")
elbo = tf.add(reconstruction_loss, kl_loss, name="elbo")
if mode == tf.estimator.ModeKeys.TRAIN:
<|code_end|>
using the current file's imports:
from disentanglement_lib.methods.shared import architectures # pylint: disable=unused-import
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import vae
from six.moves import zip
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf
and any relevant context from other files:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
#
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
. Output only the next line. | optimizer = optimizers.make_vae_optimizer() |
Using the snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library of losses for semi-supervised disentanglement learning.
Implementation of semi-supervised VAE based models for unsupervised learning of
disentangled representations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
, determine the next line of code. You have imports:
from disentanglement_lib.methods.shared import architectures # pylint: disable=unused-import
from disentanglement_lib.methods.shared import losses # pylint: disable=unused-import
from disentanglement_lib.methods.shared import optimizers # pylint: disable=unused-import
from disentanglement_lib.methods.unsupervised import vae
from six.moves import zip
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimatorSpec
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf
and context (class names, function names, or code) available:
# Path: disentanglement_lib/methods/shared/architectures.py
# def make_gaussian_encoder(input_tensor,
# is_training=True,
# num_latent=gin.REQUIRED,
# encoder_fn=gin.REQUIRED):
# def make_decoder(latent_tensor,
# output_shape,
# is_training=True,
# decoder_fn=gin.REQUIRED):
# def make_discriminator(input_tensor,
# is_training=False,
# discriminator_fn=gin.REQUIRED):
# def fc_encoder(input_tensor, num_latent, is_training=True):
# def conv_encoder(input_tensor, num_latent, is_training=True):
# def fc_decoder(latent_tensor, output_shape, is_training=True):
# def deconv_decoder(latent_tensor, output_shape, is_training=True):
# def fc_discriminator(input_tensor, is_training=True):
# def test_encoder(input_tensor, num_latent, is_training):
# def test_decoder(latent_tensor, output_shape, is_training=False):
#
# Path: disentanglement_lib/methods/shared/losses.py
# def bernoulli_loss(true_images,
# reconstructed_images,
# activation,
# subtract_true_image_entropy=False):
# def l2_loss(true_images, reconstructed_images, activation):
# def make_reconstruction_loss(true_images,
# reconstructed_images,
# loss_fn=gin.REQUIRED,
# activation="logits"):
#
# Path: disentanglement_lib/methods/shared/optimizers.py
# def make_optimizer(optimizer_fn, learning_rate):
# def make_vae_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
# def make_discriminator_optimizer(optimizer_fn=gin.REQUIRED, learning_rate=None):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
. Output only the next line. | class BaseS2VAE(vae.BaseVAE): |
Predict the next line after this snippet: <|code_start|> importance_matrix = np.array([[1., 0.,], [0., 1.], [0., 0.]])
result = dci.completeness(importance_matrix)
np.testing.assert_allclose(result, 1.0)
def test_zero(self):
importance_matrix = np.zeros(shape=[10, 10], dtype=np.float64)
result = dci.completeness(importance_matrix)
np.testing.assert_allclose(result, .0, atol=1e-7)
def test_redundant_codes(self):
importance_matrix = np.diag(5.*np.ones(5))
importance_matrix = np.vstack([importance_matrix, importance_matrix])
result = dci.completeness(importance_matrix)
np.testing.assert_allclose(result, 1. - np.log(2)/np.log(10))
def test_missed_factors(self):
importance_matrix = np.diag(5.*np.ones(5))
result = dci.completeness(importance_matrix[:2, :])
np.testing.assert_allclose(result, 1.0)
def test_one_code_two_factors(self):
importance_matrix = np.diag(5.*np.ones(5))
importance_matrix = np.hstack([importance_matrix, importance_matrix])
result = dci.completeness(importance_matrix)
np.testing.assert_allclose(result, 1.)
class DCITest(absltest.TestCase):
def test_metric(self):
<|code_end|>
using the current file's imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import dci
from six.moves import range
import numpy as np
and any relevant context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/dci.py
# def compute_dci(ground_truth_data, representation_function, random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def _compute_dci(mus_train, ys_train, mus_test, ys_test):
# def compute_dci_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED, batch_size=100):
# def compute_importance_gbt(x_train, y_train, x_test, y_test):
# def disentanglement_per_code(importance_matrix):
# def disentanglement(importance_matrix):
# def completeness_per_factor(importance_matrix):
# def completeness(importance_matrix):
. Output only the next line. | ground_truth_data = dummy_data.IdentityObservationsData() |
Predict the next line after this snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for dci_test.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
class DisentanglementTest(absltest.TestCase):
def test_diagonal(self):
importance_matrix = np.diag(5.*np.ones(5))
<|code_end|>
using the current file's imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import dci
from six.moves import range
import numpy as np
and any relevant context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/dci.py
# def compute_dci(ground_truth_data, representation_function, random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def _compute_dci(mus_train, ys_train, mus_test, ys_test):
# def compute_dci_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED, batch_size=100):
# def compute_importance_gbt(x_train, y_train, x_test, y_test):
# def disentanglement_per_code(importance_matrix):
# def disentanglement(importance_matrix):
# def completeness_per_factor(importance_matrix):
# def completeness(importance_matrix):
. Output only the next line. | result = dci.disentanglement(importance_matrix) |
Using the snippet: <|code_start|> """
# Fix the random seed for reproducibility.
random_state = np.random.RandomState(0)
# Create the output directory if necessary.
if tf.gfile.IsDirectory(output_dir):
if overwrite:
tf.gfile.DeleteRecursively(output_dir)
else:
raise ValueError("Directory already exists and overwrite is False.")
# Automatically set the proper data set if necessary. We replace the active
# gin config as this will lead to a valid gin config file where the data set
# is present.
# Obtain the dataset name from the gin config of the previous step.
gin_config_file = os.path.join(model_dir, "results", "gin", "train.gin")
gin_dict = results.gin_dict(gin_config_file)
gin.bind_parameter("dataset.name", gin_dict["dataset.name"].replace(
"'", ""))
# Automatically infer the activation function from gin config.
activation_str = gin_dict["reconstruction_loss.activation"]
if activation_str == "'logits'":
activation = sigmoid
elif activation_str == "'tanh'":
activation = tanh
else:
raise ValueError(
"Activation function could not be infered from gin config.")
<|code_end|>
, determine the next line of code. You have imports:
import numbers
import os
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import visualize_util
from disentanglement_lib.visualize.visualize_irs import vis_all_interventional_effects
from scipy import stats
from six.moves import range
from tensorflow.compat.v1 import gfile
and context (class names, function names, or code) available:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
#
# Path: disentanglement_lib/visualize/visualize_irs.py
# def vis_all_interventional_effects(gen_factors, latents, output_dir):
# """Compute Matrix of all interventional effects."""
# res = scalable_disentanglement_score(gen_factors, latents)
# parents = res["parents"]
# scores = res["disentanglement_scores"]
#
# fig_width_inches = 3.0 * gen_factors.shape[1]
# fig_height_inches = 3.0 * latents.shape[1]
# fig, axes = plt.subplots(
# latents.shape[1],
# gen_factors.shape[1],
# figsize=(fig_width_inches, fig_height_inches),
# sharex="col",
# sharey="row")
#
# for j in range(gen_factors.shape[1]): # Iterate over generative factors.
# for l in range(latents.shape[1]):
# ax = axes[l, j]
# if parents[l] != j:
# _visualize_interventional_effect(
# gen_factors, latents, l, parents[l], j, ax=ax, plot_legend=False)
# ax.set_title("")
# else:
# _visualize_interventional_effect(
# gen_factors, latents, l, parents[l], j, no_conditioning=True, ax=ax)
# ax.set_title("Parent={}, IRS = {:1.2}".format(parents[l], scores[l]))
#
# fig.tight_layout()
# if not tf.gfile.IsDirectory(output_dir):
# tf.gfile.MakeDirs(output_dir)
# output_path = os.path.join(output_dir, "interventional_effect.png")
# with tf.gfile.Open(output_path, "wb") as path:
# fig.savefig(path)
. Output only the next line. | dataset = named_data.get_named_ground_truth_data() |
Given the code snippet: <|code_start|> num_animations=5,
num_frames=20,
fps=10,
num_points_irs=10000):
"""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_frames: Integer with number of frames in each animation.
fps: Integer with frame rate for the animation.
num_points_irs: Number of points to be used for the IRS plots.
"""
# Fix the random seed for reproducibility.
random_state = np.random.RandomState(0)
# Create the output directory if necessary.
if tf.gfile.IsDirectory(output_dir):
if overwrite:
tf.gfile.DeleteRecursively(output_dir)
else:
raise ValueError("Directory already exists and overwrite is False.")
# Automatically set the proper data set if necessary. We replace the active
# gin config as this will lead to a valid gin config file where the data set
# is present.
# Obtain the dataset name from the gin config of the previous step.
gin_config_file = os.path.join(model_dir, "results", "gin", "train.gin")
<|code_end|>
, generate the next line using the imports in this file:
import numbers
import os
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import visualize_util
from disentanglement_lib.visualize.visualize_irs import vis_all_interventional_effects
from scipy import stats
from six.moves import range
from tensorflow.compat.v1 import gfile
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
#
# Path: disentanglement_lib/visualize/visualize_irs.py
# def vis_all_interventional_effects(gen_factors, latents, output_dir):
# """Compute Matrix of all interventional effects."""
# res = scalable_disentanglement_score(gen_factors, latents)
# parents = res["parents"]
# scores = res["disentanglement_scores"]
#
# fig_width_inches = 3.0 * gen_factors.shape[1]
# fig_height_inches = 3.0 * latents.shape[1]
# fig, axes = plt.subplots(
# latents.shape[1],
# gen_factors.shape[1],
# figsize=(fig_width_inches, fig_height_inches),
# sharex="col",
# sharey="row")
#
# for j in range(gen_factors.shape[1]): # Iterate over generative factors.
# for l in range(latents.shape[1]):
# ax = axes[l, j]
# if parents[l] != j:
# _visualize_interventional_effect(
# gen_factors, latents, l, parents[l], j, ax=ax, plot_legend=False)
# ax.set_title("")
# else:
# _visualize_interventional_effect(
# gen_factors, latents, l, parents[l], j, no_conditioning=True, ax=ax)
# ax.set_title("Parent={}, IRS = {:1.2}".format(parents[l], scores[l]))
#
# fig.tight_layout()
# if not tf.gfile.IsDirectory(output_dir):
# tf.gfile.MakeDirs(output_dir)
# output_path = os.path.join(output_dir, "interventional_effect.png")
# with tf.gfile.Open(output_path, "wb") as path:
# fig.savefig(path)
. Output only the next line. | gin_dict = results.gin_dict(gin_config_file) |
Using the snippet: <|code_start|> gin_dict = results.gin_dict(gin_config_file)
gin.bind_parameter("dataset.name", gin_dict["dataset.name"].replace(
"'", ""))
# Automatically infer the activation function from gin config.
activation_str = gin_dict["reconstruction_loss.activation"]
if activation_str == "'logits'":
activation = sigmoid
elif activation_str == "'tanh'":
activation = tanh
else:
raise ValueError(
"Activation function could not be infered from gin config.")
dataset = named_data.get_named_ground_truth_data()
num_pics = 64
module_path = os.path.join(model_dir, "tfhub")
with hub.eval_function_for_module(module_path) as f:
# Save reconstructions.
real_pics = dataset.sample_observations(num_pics, random_state)
raw_pics = f(
dict(images=real_pics), signature="reconstructions",
as_dict=True)["images"]
pics = activation(raw_pics)
paired_pics = np.concatenate((real_pics, pics), axis=2)
paired_pics = [paired_pics[i, :, :, :] for i in range(paired_pics.shape[0])]
results_dir = os.path.join(output_dir, "reconstructions")
if not gfile.IsDirectory(results_dir):
gfile.MakeDirs(results_dir)
<|code_end|>
, determine the next line of code. You have imports:
import numbers
import os
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import visualize_util
from disentanglement_lib.visualize.visualize_irs import vis_all_interventional_effects
from scipy import stats
from six.moves import range
from tensorflow.compat.v1 import gfile
and context (class names, function names, or code) available:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
#
# Path: disentanglement_lib/visualize/visualize_irs.py
# def vis_all_interventional_effects(gen_factors, latents, output_dir):
# """Compute Matrix of all interventional effects."""
# res = scalable_disentanglement_score(gen_factors, latents)
# parents = res["parents"]
# scores = res["disentanglement_scores"]
#
# fig_width_inches = 3.0 * gen_factors.shape[1]
# fig_height_inches = 3.0 * latents.shape[1]
# fig, axes = plt.subplots(
# latents.shape[1],
# gen_factors.shape[1],
# figsize=(fig_width_inches, fig_height_inches),
# sharex="col",
# sharey="row")
#
# for j in range(gen_factors.shape[1]): # Iterate over generative factors.
# for l in range(latents.shape[1]):
# ax = axes[l, j]
# if parents[l] != j:
# _visualize_interventional_effect(
# gen_factors, latents, l, parents[l], j, ax=ax, plot_legend=False)
# ax.set_title("")
# else:
# _visualize_interventional_effect(
# gen_factors, latents, l, parents[l], j, no_conditioning=True, ax=ax)
# ax.set_title("Parent={}, IRS = {:1.2}".format(parents[l], scores[l]))
#
# fig.tight_layout()
# if not tf.gfile.IsDirectory(output_dir):
# tf.gfile.MakeDirs(output_dir)
# output_path = os.path.join(output_dir, "interventional_effect.png")
# with tf.gfile.Open(output_path, "wb") as path:
# fig.savefig(path)
. Output only the next line. | visualize_util.grid_save_images( |
Predict the next line after this snippet: <|code_start|> images = []
for j in range(base_code.shape[0]):
code = np.repeat(np.expand_dims(base_code, 0), num_frames, axis=0)
loc = np.mean(means[:, j])
total_variance = np.mean(np.exp(logvars[:, j])) + np.var(means[:, j])
scale = np.sqrt(total_variance)
code[:, j] = visualize_util.cycle_interval(base_code[j], num_frames,
loc-2.*scale, loc+2.*scale)
images.append(np.array(activation(_decoder(code))))
filename = os.path.join(results_dir, "conf_interval_cycle%d.gif" % i)
visualize_util.save_animation(np.array(images), filename, fps)
# Cycle linearly through minmax of a fitted Gaussian.
for i, base_code in enumerate(means[:num_animations]):
images = []
for j in range(base_code.shape[0]):
code = np.repeat(np.expand_dims(base_code, 0), num_frames, axis=0)
code[:, j] = visualize_util.cycle_interval(base_code[j], num_frames,
np.min(means[:, j]),
np.max(means[:, j]))
images.append(np.array(activation(_decoder(code))))
filename = os.path.join(results_dir, "minmax_interval_cycle%d.gif" % i)
visualize_util.save_animation(np.array(images), filename, fps)
# Interventional effects visualization.
factors = dataset.sample_factors(num_points_irs, random_state)
obs = dataset.sample_observations_from_factors(factors, random_state)
latents = f(
dict(images=obs), signature="gaussian_encoder", as_dict=True)["mean"]
results_dir = os.path.join(output_dir, "interventional_effects")
<|code_end|>
using the current file's imports:
import numbers
import os
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import visualize_util
from disentanglement_lib.visualize.visualize_irs import vis_all_interventional_effects
from scipy import stats
from six.moves import range
from tensorflow.compat.v1 import gfile
and any relevant context from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
#
# Path: disentanglement_lib/visualize/visualize_irs.py
# def vis_all_interventional_effects(gen_factors, latents, output_dir):
# """Compute Matrix of all interventional effects."""
# res = scalable_disentanglement_score(gen_factors, latents)
# parents = res["parents"]
# scores = res["disentanglement_scores"]
#
# fig_width_inches = 3.0 * gen_factors.shape[1]
# fig_height_inches = 3.0 * latents.shape[1]
# fig, axes = plt.subplots(
# latents.shape[1],
# gen_factors.shape[1],
# figsize=(fig_width_inches, fig_height_inches),
# sharex="col",
# sharey="row")
#
# for j in range(gen_factors.shape[1]): # Iterate over generative factors.
# for l in range(latents.shape[1]):
# ax = axes[l, j]
# if parents[l] != j:
# _visualize_interventional_effect(
# gen_factors, latents, l, parents[l], j, ax=ax, plot_legend=False)
# ax.set_title("")
# else:
# _visualize_interventional_effect(
# gen_factors, latents, l, parents[l], j, no_conditioning=True, ax=ax)
# ax.set_title("Parent={}, IRS = {:1.2}".format(parents[l], scores[l]))
#
# fig.tight_layout()
# if not tf.gfile.IsDirectory(output_dir):
# tf.gfile.MakeDirs(output_dir)
# output_path = os.path.join(output_dir, "interventional_effect.png")
# with tf.gfile.Open(output_path, "wb") as path:
# fig.savefig(path)
. Output only the next line. | vis_all_interventional_effects(factors, latents, results_dir) |
Predict the next line for this snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for vae.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def _make_symmetric_psd(matrix):
return 0.5 * (matrix + matrix.T) + np.diag(np.ones(10)) * 10.
class VaeTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.parameters((np.zeros([10, 10]), np.zeros([10, 10]), 0., 0.01),
(np.ones([10, 10]), np.zeros([10, 10]), 5., 5.01),
(np.ones([10, 10]), np.ones([10, 10]), 8.58, 8.6))
def test_compute_gaussian_kl(self, mean, logvar, target_low, target_high):
mean_tf = tf.convert_to_tensor(mean, dtype=np.float32)
logvar_tf = tf.convert_to_tensor(logvar, dtype=np.float32)
with self.test_session() as sess:
<|code_end|>
with the help of current file imports:
from absl.testing import parameterized
from disentanglement_lib.methods.unsupervised import vae
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf.external_configurables # pylint: disable=unused-import
and context from other files:
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
, which may contain function names, class names, or code. Output only the next line. | test_value = sess.run(vae.compute_gaussian_kl(mean_tf, logvar_tf)) |
Given the following code snippet before the placeholder: <|code_start|> **kwargs: Other keyword arguments passed to tf.keras.Model.
"""
super(BaselineCNNEmbedder, self).__init__(name=name, **kwargs)
embedding_layers = [
tf.keras.layers.Conv2D(
32, (4, 4),
2,
activation=get_activation(),
padding="same",
kernel_initializer=get_kernel_initializer()),
tf.keras.layers.Conv2D(
32, (4, 4),
2,
activation=get_activation(),
padding="same",
kernel_initializer=get_kernel_initializer()),
tf.keras.layers.Conv2D(
64, (4, 4),
2,
activation=get_activation(),
padding="same",
kernel_initializer=get_kernel_initializer()),
tf.keras.layers.Conv2D(
64, (4, 4),
2,
activation=get_activation(),
padding="same",
kernel_initializer=get_kernel_initializer()),
tf.keras.layers.Flatten(),
]
<|code_end|>
, predict the next line using imports from the current file:
from disentanglement_lib.evaluation.abstract_reasoning import relational_layers
from tensorflow.contrib import tpu as contrib_tpu
import gin
import tensorflow.compat.v1 as tf
import tensorflow_hub as hub
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/evaluation/abstract_reasoning/relational_layers.py
# class RelationalLayer(tf.keras.layers.Layer):
# class PairwiseEdgeEmbeddings(tf.keras.layers.Layer):
# class AddPositionalEncoding(tf.keras.layers.Layer):
# class StackAnswers(tf.keras.layers.Layer):
# class MultiDimBatchApply(tf.keras.layers.Layer):
# def __init__(self, edge_layer, reduce_layer):
# def call(self, inputs, **kwargs):
# def call(self, inputs, **kwargs):
# def repeat(tensor, num, axis):
# def positional_encoding_like(tensor, positional_encoding_axis=-2,
# value_axis=-1):
# def __init__(self, positional_encoding_axis=-2, embedding_axis=-1):
# def call(self, inputs, **kwargs):
# def __init__(self, answer_axis=-2, stack_axis=-3):
# def call(self, inputs, **kwargs):
# def __init__(self, layer, num_dims_to_keep=3):
# def call(self, inputs, **kwargs):
. Output only the next line. | self.embedding_layer = relational_layers.MultiDimBatchApply( |
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for beta_vae.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BetaVaeTest(absltest.TestCase):
def test_metric(self):
<|code_end|>
, predict the next line using imports from the current file:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import beta_vae
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/beta_vae.py
# def compute_beta_vae_sklearn(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# batch_size=gin.REQUIRED,
# num_train=gin.REQUIRED,
# num_eval=gin.REQUIRED):
# def _generate_training_batch(ground_truth_data, representation_function,
# batch_size, num_points, random_state):
# def _generate_training_sample(ground_truth_data, representation_function,
# batch_size, random_state):
. Output only the next line. | ground_truth_data = dummy_data.IdentityObservationsData() |
Predict the next line after this snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for beta_vae.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BetaVaeTest(absltest.TestCase):
def test_metric(self):
ground_truth_data = dummy_data.IdentityObservationsData()
representation_function = lambda x: x
random_state = np.random.RandomState(0)
<|code_end|>
using the current file's imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import beta_vae
import numpy as np
and any relevant context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/beta_vae.py
# def compute_beta_vae_sklearn(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# batch_size=gin.REQUIRED,
# num_train=gin.REQUIRED,
# num_eval=gin.REQUIRED):
# def _generate_training_batch(ground_truth_data, representation_function,
# batch_size, num_points, random_state):
# def _generate_training_sample(ground_truth_data, representation_function,
# batch_size, random_state):
. Output only the next line. | scores = beta_vae.compute_beta_vae_sklearn( |
Next line prediction: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dummy data sets used for testing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
<|code_end|>
. Use current file imports:
(from disentanglement_lib.data.ground_truth import ground_truth_data)
and context including class names, function names, or small code snippets from other files:
# Path: disentanglement_lib/data/ground_truth/ground_truth_data.py
# class GroundTruthData(object):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def sample(self, num, random_state):
# def sample_observations(self, num, random_state):
. Output only the next line. | class IdentityObservationsData(ground_truth_data.GroundTruthData): |
Given snippet: <|code_start|> while True:
if num_elements > max_ratio * i * i:
return best_i
remainder = (i - num_elements % i) % i
if remainder == 0:
return i
if remainder < best_remainder:
best_remainder = remainder
best_i = i
i -= 1
def pad_around(image, padding_px=10, axis=None, value=None):
"""Adds a padding around each image."""
# If axis is None, pad both the first and the second axis.
if axis is None:
image = pad_around(image, padding_px, axis=0, value=value)
axis = 1
padding_arr = padding_array(image, padding_px, axis, value=value)
return np.concatenate([padding_arr, image, padding_arr], axis=axis)
def add_below(image, padding_px=10, value=None):
"""Adds a footer below."""
if len(image.shape) == 2:
image = np.expand_dims(image, -1)
if image.shape[2] == 1:
image = np.repeat(image, 3, 2)
if image.shape[2] != 3:
raise ValueError("Could not convert image to have three channels.")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import math
import numpy as np
import scipy
import tensorflow.compat.v1 as tf
import imageio
from disentanglement_lib.utils import resources
from PIL import Image
from six.moves import range
and context:
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
which might include code, classes, or functions. Output only the next line. | with tf.gfile.Open(resources.get_file("disentanglement_lib.png"), "rb") as f: |
Predict the next line after this snippet: <|code_start|> values for that factor. We repeat the experiment n_experiment times, to ensure
robustness.
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 directory where artifacts can be saved.
num_train: Number of points used for training.
num_test: Number of points used for testing.
n_experiment: Number of repetitions of the experiment.
Returns:
Dictionary with scores.
"""
del artifact_dir
scores = {}
for train_size in num_train:
# sample factors
factors_train = ground_truth_data.sample_factors(train_size, random_state)
factors_test = ground_truth_data.sample_factors(num_test, random_state)
# obtain_observations without intervention
x_train = ground_truth_data.sample_observations_from_factors(
factors_train, random_state)
x_test = ground_truth_data.sample_observations_from_factors(
factors_test, random_state)
mus_train = representation_function(x_train)
mus_test = representation_function(x_test)
# train predictor on data without interbention
<|code_end|>
using the current file's imports:
from disentanglement_lib.evaluation.metrics import utils
from six.moves import range
import numpy as np
import gin.tf
and any relevant context from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | predictor_model = utils.make_predictor_fn() |
Given snippet: <|code_start|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for visualize_model.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
MODEL_CONFIG_PATH = "../config/tests/methods/unsupervised/train_test.gin"
class VisualizeTest(parameterized.TestCase):
@parameterized.parameters(
("logits"),
("tanh"),
)
def test_visualize_sigmoid(self, activation):
activation_binding = (
"reconstruction_loss.activation = '{}'".format(activation))
self.model_dir = self.create_tempdir(
"model_{}".format(activation),
cleanup=absltest.TempFileCleanup.OFF).full_path
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.methods.unsupervised import train
from disentanglement_lib.utils import resources
from disentanglement_lib.visualize import visualize_model
and context:
# Path: disentanglement_lib/methods/unsupervised/train.py
# @gin.configurable("model", blacklist=["model_dir", "overwrite"])
# def train(model_dir,
# overwrite=False,
# model=gin.REQUIRED,
# training_steps=gin.REQUIRED,
# random_seed=gin.REQUIRED,
# batch_size=gin.REQUIRED,
# eval_steps=1000,
# name="",
# model_num=None):
# """Trains the estimator and exports the snapshot and the gin config.
#
# The use of this function requires the gin binding 'dataset.name' to be
# specified as that determines the data set used for training.
#
# Args:
# model_dir: String with path to directory where model output should be saved.
# overwrite: Boolean indicating whether to overwrite output directory.
# model: GaussianEncoderModel that should be trained and exported.
# training_steps: Integer with number of training steps.
# random_seed: Integer with random seed used for training.
# batch_size: Integer with the batch size.
# eval_steps: Optional integer with number of steps used for evaluation.
# name: Optional string with name of the model (can be used to name models).
# model_num: Optional integer with model number (can be used to identify
# models).
# """
# # We do not use the variables 'name' and 'model_num'. Instead, they can be
# # used to name results as they will be part of the saved gin config.
# del name, model_num
#
# # Delete the output directory if it already exists.
# if tf.gfile.IsDirectory(model_dir):
# if overwrite:
# tf.gfile.DeleteRecursively(model_dir)
# else:
# raise ValueError("Directory already exists and overwrite is False.")
#
# # Create a numpy random state. We will sample the random seeds for training
# # and evaluation from this.
# random_state = np.random.RandomState(random_seed)
#
# # Obtain the dataset.
# dataset = named_data.get_named_ground_truth_data()
#
# # We create a TPUEstimator based on the provided model. This is primarily so
# # that we could switch to TPU training in the future. For now, we train
# # locally on GPUs.
# run_config = contrib_tpu.RunConfig(
# tf_random_seed=random_seed,
# keep_checkpoint_max=1,
# tpu_config=contrib_tpu.TPUConfig(iterations_per_loop=500))
# tpu_estimator = contrib_tpu.TPUEstimator(
# use_tpu=False,
# model_fn=model.model_fn,
# model_dir=os.path.join(model_dir, "tf_checkpoint"),
# train_batch_size=batch_size,
# eval_batch_size=batch_size,
# config=run_config)
#
# # Set up time to keep track of elapsed time in results.
# experiment_timer = time.time()
#
# # Do the actual training.
# tpu_estimator.train(
# input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
# steps=training_steps)
#
# # Save model as a TFHub module.
# output_shape = named_data.get_named_ground_truth_data().observation_shape
# module_export_path = os.path.join(model_dir, "tfhub")
# gaussian_encoder_model.export_as_tf_hub(model, output_shape,
# tpu_estimator.latest_checkpoint(),
# module_export_path)
#
# # Save the results. The result dir will contain all the results and config
# # files that we copied along, as we progress in the pipeline. The idea is that
# # these files will be available for analysis at the end.
# results_dict = tpu_estimator.evaluate(
# input_fn=_make_input_fn(
# dataset, random_state.randint(2**32), num_batches=eval_steps))
# results_dir = os.path.join(model_dir, "results")
# results_dict["elapsed_time"] = time.time() - experiment_timer
# results.update_result_directory(results_dir, "train", results_dict)
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
#
# Path: disentanglement_lib/visualize/visualize_model.py
# def visualize(model_dir,
# output_dir,
# overwrite=False,
# num_animations=5,
# num_frames=20,
# fps=10,
# num_points_irs=10000):
# def _decoder(latent_vectors):
# def latent_traversal_1d_multi_dim(generator_fn,
# latent_vector,
# dimensions=None,
# values=None,
# transpose=False):
# def sigmoid(x):
# def tanh(x):
which might include code, classes, or functions. Output only the next line. | train.train_with_gin(self.model_dir, True, [ |
Given the following code snippet before the placeholder: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for visualize_model.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
MODEL_CONFIG_PATH = "../config/tests/methods/unsupervised/train_test.gin"
class VisualizeTest(parameterized.TestCase):
@parameterized.parameters(
("logits"),
("tanh"),
)
def test_visualize_sigmoid(self, activation):
activation_binding = (
"reconstruction_loss.activation = '{}'".format(activation))
self.model_dir = self.create_tempdir(
"model_{}".format(activation),
cleanup=absltest.TempFileCleanup.OFF).full_path
train.train_with_gin(self.model_dir, True, [
<|code_end|>
, predict the next line using imports from the current file:
from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.methods.unsupervised import train
from disentanglement_lib.utils import resources
from disentanglement_lib.visualize import visualize_model
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/methods/unsupervised/train.py
# @gin.configurable("model", blacklist=["model_dir", "overwrite"])
# def train(model_dir,
# overwrite=False,
# model=gin.REQUIRED,
# training_steps=gin.REQUIRED,
# random_seed=gin.REQUIRED,
# batch_size=gin.REQUIRED,
# eval_steps=1000,
# name="",
# model_num=None):
# """Trains the estimator and exports the snapshot and the gin config.
#
# The use of this function requires the gin binding 'dataset.name' to be
# specified as that determines the data set used for training.
#
# Args:
# model_dir: String with path to directory where model output should be saved.
# overwrite: Boolean indicating whether to overwrite output directory.
# model: GaussianEncoderModel that should be trained and exported.
# training_steps: Integer with number of training steps.
# random_seed: Integer with random seed used for training.
# batch_size: Integer with the batch size.
# eval_steps: Optional integer with number of steps used for evaluation.
# name: Optional string with name of the model (can be used to name models).
# model_num: Optional integer with model number (can be used to identify
# models).
# """
# # We do not use the variables 'name' and 'model_num'. Instead, they can be
# # used to name results as they will be part of the saved gin config.
# del name, model_num
#
# # Delete the output directory if it already exists.
# if tf.gfile.IsDirectory(model_dir):
# if overwrite:
# tf.gfile.DeleteRecursively(model_dir)
# else:
# raise ValueError("Directory already exists and overwrite is False.")
#
# # Create a numpy random state. We will sample the random seeds for training
# # and evaluation from this.
# random_state = np.random.RandomState(random_seed)
#
# # Obtain the dataset.
# dataset = named_data.get_named_ground_truth_data()
#
# # We create a TPUEstimator based on the provided model. This is primarily so
# # that we could switch to TPU training in the future. For now, we train
# # locally on GPUs.
# run_config = contrib_tpu.RunConfig(
# tf_random_seed=random_seed,
# keep_checkpoint_max=1,
# tpu_config=contrib_tpu.TPUConfig(iterations_per_loop=500))
# tpu_estimator = contrib_tpu.TPUEstimator(
# use_tpu=False,
# model_fn=model.model_fn,
# model_dir=os.path.join(model_dir, "tf_checkpoint"),
# train_batch_size=batch_size,
# eval_batch_size=batch_size,
# config=run_config)
#
# # Set up time to keep track of elapsed time in results.
# experiment_timer = time.time()
#
# # Do the actual training.
# tpu_estimator.train(
# input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
# steps=training_steps)
#
# # Save model as a TFHub module.
# output_shape = named_data.get_named_ground_truth_data().observation_shape
# module_export_path = os.path.join(model_dir, "tfhub")
# gaussian_encoder_model.export_as_tf_hub(model, output_shape,
# tpu_estimator.latest_checkpoint(),
# module_export_path)
#
# # Save the results. The result dir will contain all the results and config
# # files that we copied along, as we progress in the pipeline. The idea is that
# # these files will be available for analysis at the end.
# results_dict = tpu_estimator.evaluate(
# input_fn=_make_input_fn(
# dataset, random_state.randint(2**32), num_batches=eval_steps))
# results_dir = os.path.join(model_dir, "results")
# results_dict["elapsed_time"] = time.time() - experiment_timer
# results.update_result_directory(results_dir, "train", results_dict)
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
#
# Path: disentanglement_lib/visualize/visualize_model.py
# def visualize(model_dir,
# output_dir,
# overwrite=False,
# num_animations=5,
# num_frames=20,
# fps=10,
# num_points_irs=10000):
# def _decoder(latent_vectors):
# def latent_traversal_1d_multi_dim(generator_fn,
# latent_vector,
# dimensions=None,
# values=None,
# transpose=False):
# def sigmoid(x):
# def tanh(x):
. Output only the next line. | resources.get_file("config/tests/methods/unsupervised/train_test.gin") |
Based on the snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for visualize_model.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
MODEL_CONFIG_PATH = "../config/tests/methods/unsupervised/train_test.gin"
class VisualizeTest(parameterized.TestCase):
@parameterized.parameters(
("logits"),
("tanh"),
)
def test_visualize_sigmoid(self, activation):
activation_binding = (
"reconstruction_loss.activation = '{}'".format(activation))
self.model_dir = self.create_tempdir(
"model_{}".format(activation),
cleanup=absltest.TempFileCleanup.OFF).full_path
train.train_with_gin(self.model_dir, True, [
resources.get_file("config/tests/methods/unsupervised/train_test.gin")
], [activation_binding])
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from absl.testing import parameterized
from disentanglement_lib.methods.unsupervised import train
from disentanglement_lib.utils import resources
from disentanglement_lib.visualize import visualize_model
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/methods/unsupervised/train.py
# @gin.configurable("model", blacklist=["model_dir", "overwrite"])
# def train(model_dir,
# overwrite=False,
# model=gin.REQUIRED,
# training_steps=gin.REQUIRED,
# random_seed=gin.REQUIRED,
# batch_size=gin.REQUIRED,
# eval_steps=1000,
# name="",
# model_num=None):
# """Trains the estimator and exports the snapshot and the gin config.
#
# The use of this function requires the gin binding 'dataset.name' to be
# specified as that determines the data set used for training.
#
# Args:
# model_dir: String with path to directory where model output should be saved.
# overwrite: Boolean indicating whether to overwrite output directory.
# model: GaussianEncoderModel that should be trained and exported.
# training_steps: Integer with number of training steps.
# random_seed: Integer with random seed used for training.
# batch_size: Integer with the batch size.
# eval_steps: Optional integer with number of steps used for evaluation.
# name: Optional string with name of the model (can be used to name models).
# model_num: Optional integer with model number (can be used to identify
# models).
# """
# # We do not use the variables 'name' and 'model_num'. Instead, they can be
# # used to name results as they will be part of the saved gin config.
# del name, model_num
#
# # Delete the output directory if it already exists.
# if tf.gfile.IsDirectory(model_dir):
# if overwrite:
# tf.gfile.DeleteRecursively(model_dir)
# else:
# raise ValueError("Directory already exists and overwrite is False.")
#
# # Create a numpy random state. We will sample the random seeds for training
# # and evaluation from this.
# random_state = np.random.RandomState(random_seed)
#
# # Obtain the dataset.
# dataset = named_data.get_named_ground_truth_data()
#
# # We create a TPUEstimator based on the provided model. This is primarily so
# # that we could switch to TPU training in the future. For now, we train
# # locally on GPUs.
# run_config = contrib_tpu.RunConfig(
# tf_random_seed=random_seed,
# keep_checkpoint_max=1,
# tpu_config=contrib_tpu.TPUConfig(iterations_per_loop=500))
# tpu_estimator = contrib_tpu.TPUEstimator(
# use_tpu=False,
# model_fn=model.model_fn,
# model_dir=os.path.join(model_dir, "tf_checkpoint"),
# train_batch_size=batch_size,
# eval_batch_size=batch_size,
# config=run_config)
#
# # Set up time to keep track of elapsed time in results.
# experiment_timer = time.time()
#
# # Do the actual training.
# tpu_estimator.train(
# input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
# steps=training_steps)
#
# # Save model as a TFHub module.
# output_shape = named_data.get_named_ground_truth_data().observation_shape
# module_export_path = os.path.join(model_dir, "tfhub")
# gaussian_encoder_model.export_as_tf_hub(model, output_shape,
# tpu_estimator.latest_checkpoint(),
# module_export_path)
#
# # Save the results. The result dir will contain all the results and config
# # files that we copied along, as we progress in the pipeline. The idea is that
# # these files will be available for analysis at the end.
# results_dict = tpu_estimator.evaluate(
# input_fn=_make_input_fn(
# dataset, random_state.randint(2**32), num_batches=eval_steps))
# results_dir = os.path.join(model_dir, "results")
# results_dict["elapsed_time"] = time.time() - experiment_timer
# results.update_result_directory(results_dir, "train", results_dict)
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
#
# Path: disentanglement_lib/visualize/visualize_model.py
# def visualize(model_dir,
# output_dir,
# overwrite=False,
# num_animations=5,
# num_frames=20,
# fps=10,
# num_points_irs=10000):
# def _decoder(latent_vectors):
# def latent_traversal_1d_multi_dim(generator_fn,
# latent_vector,
# dimensions=None,
# values=None,
# transpose=False):
# def sigmoid(x):
# def tanh(x):
. Output only the next line. | visualize_model.visualize( |
Predict the next line for this snippet: <|code_start|> "dynamics.k = -1", "mlvae.beta = 1."],
["model.model = @mlvae_labels()",
"dynamics.k = 2", "mlvae.beta = 1."],
["model.model = @mlvae_argmax()",
"dynamics.k = 2", "mlvae.beta = 1."]]
def _config_generator():
"""Yields all model configurations that should be tested."""
model_config_path = resources.get_file(
"config/tests/methods/unsupervised/train_test.gin")
for model in MODELS_TEST:
yield [model_config_path], model
class TrainTest(parameterized.TestCase):
@parameterized.parameters(list(_config_generator()))
def test_train_model(self, gin_configs, gin_bindings):
# We clear the gin config before running. Otherwise, if a prior test fails,
# the gin config is locked and the current test fails.
gin.clear_config()
train_weak_lib.train_with_gin(
self.create_tempdir().full_path, True, gin_configs, gin_bindings)
class WeakDataTest(parameterized.TestCase, tf.test.TestCase):
def test_weak_data(self):
<|code_end|>
with the help of current file imports:
from absl.testing import parameterized
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.methods.weak import train_weak_lib
from disentanglement_lib.utils import resources
import tensorflow as tf
import gin.tf
and context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/methods/weak/train_weak_lib.py
# def simple_dynamics(z, ground_truth_data, random_state,
# return_index=False, k=gin.REQUIRED):
# def train_with_gin(model_dir,
# overwrite=False,
# gin_config_files=None,
# gin_bindings=None):
# def train(model_dir,
# overwrite=False,
# model=gin.REQUIRED,
# training_steps=gin.REQUIRED,
# random_seed=gin.REQUIRED,
# batch_size=gin.REQUIRED,
# name=""):
# def _make_input_fn(ground_truth_data, seed, num_batches=None):
# def load_dataset(params):
# def weak_dataset_from_ground_truth_data(
# ground_truth_data, random_seed):
# def _generator():
# def visualize_weakly_supervised_dataset(
# data, path, num_animations=10, num_frames=20, fps=10):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
, which may contain function names, class names, or code. Output only the next line. | ground_truth_data = dummy_data.DummyData() |
Continue the code snippet: <|code_start|> ["model.model = @mlvae_labels()",
"dynamics.k = 1", "mlvae.beta = 1."],
["model.model = @mlvae_argmax()",
"dynamics.k = 1", "mlvae.beta = 1."],
["model.model = @mlvae_labels()",
"dynamics.k = -1", "mlvae.beta = 1."],
["model.model = @mlvae_argmax()",
"dynamics.k = -1", "mlvae.beta = 1."],
["model.model = @mlvae_labels()",
"dynamics.k = 2", "mlvae.beta = 1."],
["model.model = @mlvae_argmax()",
"dynamics.k = 2", "mlvae.beta = 1."]]
def _config_generator():
"""Yields all model configurations that should be tested."""
model_config_path = resources.get_file(
"config/tests/methods/unsupervised/train_test.gin")
for model in MODELS_TEST:
yield [model_config_path], model
class TrainTest(parameterized.TestCase):
@parameterized.parameters(list(_config_generator()))
def test_train_model(self, gin_configs, gin_bindings):
# We clear the gin config before running. Otherwise, if a prior test fails,
# the gin config is locked and the current test fails.
gin.clear_config()
<|code_end|>
. Use current file imports:
from absl.testing import parameterized
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.methods.weak import train_weak_lib
from disentanglement_lib.utils import resources
import tensorflow as tf
import gin.tf
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/methods/weak/train_weak_lib.py
# def simple_dynamics(z, ground_truth_data, random_state,
# return_index=False, k=gin.REQUIRED):
# def train_with_gin(model_dir,
# overwrite=False,
# gin_config_files=None,
# gin_bindings=None):
# def train(model_dir,
# overwrite=False,
# model=gin.REQUIRED,
# training_steps=gin.REQUIRED,
# random_seed=gin.REQUIRED,
# batch_size=gin.REQUIRED,
# name=""):
# def _make_input_fn(ground_truth_data, seed, num_batches=None):
# def load_dataset(params):
# def weak_dataset_from_ground_truth_data(
# ground_truth_data, random_seed):
# def _generator():
# def visualize_weakly_supervised_dataset(
# data, path, num_animations=10, num_frames=20, fps=10):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
. Output only the next line. | train_weak_lib.train_with_gin( |
Given the code snippet: <|code_start|>
MODELS_TEST = [
["model.model = @group_vae_labels()",
"dynamics.k = 1", "group_vae.beta = 1."],
["model.model = @group_vae_argmax()",
"dynamics.k = 1", "group_vae.beta = 1."],
["model.model = @group_vae_labels()",
"dynamics.k = -1", "group_vae.beta = 1."],
["model.model = @group_vae_argmax()",
"dynamics.k = -1", "group_vae.beta = 1."],
["model.model = @group_vae_labels()",
"dynamics.k = 2", "group_vae.beta = 1."],
["model.model = @group_vae_argmax()",
"dynamics.k = 2", "group_vae.beta = 1."],
["model.model = @mlvae_labels()",
"dynamics.k = 1", "mlvae.beta = 1."],
["model.model = @mlvae_argmax()",
"dynamics.k = 1", "mlvae.beta = 1."],
["model.model = @mlvae_labels()",
"dynamics.k = -1", "mlvae.beta = 1."],
["model.model = @mlvae_argmax()",
"dynamics.k = -1", "mlvae.beta = 1."],
["model.model = @mlvae_labels()",
"dynamics.k = 2", "mlvae.beta = 1."],
["model.model = @mlvae_argmax()",
"dynamics.k = 2", "mlvae.beta = 1."]]
def _config_generator():
"""Yields all model configurations that should be tested."""
<|code_end|>
, generate the next line using the imports in this file:
from absl.testing import parameterized
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.methods.weak import train_weak_lib
from disentanglement_lib.utils import resources
import tensorflow as tf
import gin.tf
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/methods/weak/train_weak_lib.py
# def simple_dynamics(z, ground_truth_data, random_state,
# return_index=False, k=gin.REQUIRED):
# def train_with_gin(model_dir,
# overwrite=False,
# gin_config_files=None,
# gin_bindings=None):
# def train(model_dir,
# overwrite=False,
# model=gin.REQUIRED,
# training_steps=gin.REQUIRED,
# random_seed=gin.REQUIRED,
# batch_size=gin.REQUIRED,
# name=""):
# def _make_input_fn(ground_truth_data, seed, num_batches=None):
# def load_dataset(params):
# def weak_dataset_from_ground_truth_data(
# ground_truth_data, random_seed):
# def _generator():
# def visualize_weakly_supervised_dataset(
# data, path, num_animations=10, num_frames=20, fps=10):
#
# Path: disentanglement_lib/utils/resources.py
# def get_file(path):
# def get_files_in_folder(path):
. Output only the next line. | model_config_path = resources.get_file( |
Continue the code snippet: <|code_start|> """
# We do not use the variable 'name'. Instead, it can be used to name results
# as it will be part of the saved gin config.
del name
# Delete the output directory if it already exists.
if tf.gfile.IsDirectory(output_dir):
if overwrite:
tf.gfile.DeleteRecursively(output_dir)
else:
raise ValueError("Directory already exists and overwrite is False.")
# Create a numpy random state. We will sample the random seeds for training
# and evaluation from this.
random_state = np.random.RandomState(random_seed)
# Automatically set the proper data set if necessary. We replace the active
# gin config as this will lead to a valid gin config file where the data set
# is present.
if gin.query_parameter("dataset.name") == "auto":
if input_dir is None:
raise ValueError("Cannot automatically infer data set for methods with"
" no prior model directory.")
# Obtain the dataset name from the gin config of the previous step.
gin_config_file = os.path.join(input_dir, "results", "gin",
"postprocess.gin")
gin_dict = results.gin_dict(gin_config_file)
with gin.unlock_config():
gin.bind_parameter("dataset.name",
gin_dict["dataset.name"].replace("'", ""))
<|code_end|>
. Use current file imports:
import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
from disentanglement_lib.evaluation.abstract_reasoning import models # pylint: disable=unused-import
from disentanglement_lib.evaluation.abstract_reasoning import pgm_data
from disentanglement_lib.utils import results
from tensorflow.contrib import tpu as contrib_tpu
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/evaluation/abstract_reasoning/models.py
# class TwoStageModel(object):
# class BaselineCNNEmbedder(tf.keras.Model):
# class HubEmbedding(tf.keras.Model):
# class OptimizedWildRelNet(tf.keras.Model):
# def __init__(self,
# embedding_model_class=gin.REQUIRED,
# reasoning_model_class=gin.REQUIRED,
# optimizer_fn=None):
# def model_fn(self, features, labels, mode, params):
# def metric_fn(labels, logits):
# def __init__(self,
# num_latent=gin.REQUIRED,
# name="BaselineCNNEmbedder",
# **kwargs):
# def call(self, inputs, **kwargs):
# def __init__(self, hub_path=gin.REQUIRED, name="HubEmbedding", **kwargs):
# def _embedder(x):
# def call(self, inputs, **kwargs):
# def __init__(self,
# edge_mlp=gin.REQUIRED,
# graph_mlp=gin.REQUIRED,
# dropout_in_last_graph_layer=gin.REQUIRED,
# name="OptimizedWildRelNet",
# **kwargs):
# def call(self, inputs, **kwargs):
# def get_activation(activation=tf.keras.activations.relu):
# def get_kernel_initializer(kernel_initializer="lecun_normal"):
#
# Path: disentanglement_lib/evaluation/abstract_reasoning/pgm_data.py
# def get_pgm_dataset(pgm_type=gin.REQUIRED):
# def __init__(self, ground_truth_data, sampling_strategy, relations_dist):
# def sample(self, random_state):
# def tf_data_set(self, seed):
# def generator():
# def make_input_fn(self, seed, num_batches=None):
# def input_fn(params):
# def __init__(self,
# solution,
# alternatives,
# position,
# solution_factors=None,
# alternatives_factors=None,
# num_factor_values=None):
# def get_context(self):
# def get_answers(self):
# def get_context_factor_values(self):
# def get_answers_factor_values(self):
# def range_embed_factors(self, factors):
# def onehot_embed_factors(self, factors):
# def training_sample(self):
# def make_image(self, answer=False, padding_px=8, border_px=4):
# def __init__(self, wrapped_ground_truth_data, max_factors):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def _sample_factor(self, i, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def question_mark():
# def onehot(indices, num_atoms):
# class PGMDataset(object):
# class PGMInstance(object):
# class Quantizer(gtd.GroundTruthData):
# COLORS = {
# "blue": np.array([66., 103., 210.]) / 255.,
# "red": np.array([234., 67., 53.]) / 255.,
# "yellow": np.array([251., 188., 4.]) / 255.,
# "green": np.array([52., 168., 83.]) / 255.,
# "grey": np.array([154., 160., 166.]) / 255.,
# }
# QUESTION_MARK = [None]
# QUESTION_MARK[0] = np.array(Image.open(f).convert("RGB")) * 1.0 / 255.
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | dataset = pgm_data.get_pgm_dataset() |
Next line prediction: <|code_start|> per iteration.
random_seed: Integer with random seed used for training.
batch_size: Integer with the batch size.
name: Optional string with name of the model (can be used to name models).
"""
# We do not use the variable 'name'. Instead, it can be used to name results
# as it will be part of the saved gin config.
del name
# Delete the output directory if it already exists.
if tf.gfile.IsDirectory(output_dir):
if overwrite:
tf.gfile.DeleteRecursively(output_dir)
else:
raise ValueError("Directory already exists and overwrite is False.")
# Create a numpy random state. We will sample the random seeds for training
# and evaluation from this.
random_state = np.random.RandomState(random_seed)
# Automatically set the proper data set if necessary. We replace the active
# gin config as this will lead to a valid gin config file where the data set
# is present.
if gin.query_parameter("dataset.name") == "auto":
if input_dir is None:
raise ValueError("Cannot automatically infer data set for methods with"
" no prior model directory.")
# Obtain the dataset name from the gin config of the previous step.
gin_config_file = os.path.join(input_dir, "results", "gin",
"postprocess.gin")
<|code_end|>
. Use current file imports:
(import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
from disentanglement_lib.evaluation.abstract_reasoning import models # pylint: disable=unused-import
from disentanglement_lib.evaluation.abstract_reasoning import pgm_data
from disentanglement_lib.utils import results
from tensorflow.contrib import tpu as contrib_tpu)
and context including class names, function names, or small code snippets from other files:
# Path: disentanglement_lib/evaluation/abstract_reasoning/models.py
# class TwoStageModel(object):
# class BaselineCNNEmbedder(tf.keras.Model):
# class HubEmbedding(tf.keras.Model):
# class OptimizedWildRelNet(tf.keras.Model):
# def __init__(self,
# embedding_model_class=gin.REQUIRED,
# reasoning_model_class=gin.REQUIRED,
# optimizer_fn=None):
# def model_fn(self, features, labels, mode, params):
# def metric_fn(labels, logits):
# def __init__(self,
# num_latent=gin.REQUIRED,
# name="BaselineCNNEmbedder",
# **kwargs):
# def call(self, inputs, **kwargs):
# def __init__(self, hub_path=gin.REQUIRED, name="HubEmbedding", **kwargs):
# def _embedder(x):
# def call(self, inputs, **kwargs):
# def __init__(self,
# edge_mlp=gin.REQUIRED,
# graph_mlp=gin.REQUIRED,
# dropout_in_last_graph_layer=gin.REQUIRED,
# name="OptimizedWildRelNet",
# **kwargs):
# def call(self, inputs, **kwargs):
# def get_activation(activation=tf.keras.activations.relu):
# def get_kernel_initializer(kernel_initializer="lecun_normal"):
#
# Path: disentanglement_lib/evaluation/abstract_reasoning/pgm_data.py
# def get_pgm_dataset(pgm_type=gin.REQUIRED):
# def __init__(self, ground_truth_data, sampling_strategy, relations_dist):
# def sample(self, random_state):
# def tf_data_set(self, seed):
# def generator():
# def make_input_fn(self, seed, num_batches=None):
# def input_fn(params):
# def __init__(self,
# solution,
# alternatives,
# position,
# solution_factors=None,
# alternatives_factors=None,
# num_factor_values=None):
# def get_context(self):
# def get_answers(self):
# def get_context_factor_values(self):
# def get_answers_factor_values(self):
# def range_embed_factors(self, factors):
# def onehot_embed_factors(self, factors):
# def training_sample(self):
# def make_image(self, answer=False, padding_px=8, border_px=4):
# def __init__(self, wrapped_ground_truth_data, max_factors):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def _sample_factor(self, i, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def question_mark():
# def onehot(indices, num_atoms):
# class PGMDataset(object):
# class PGMInstance(object):
# class Quantizer(gtd.GroundTruthData):
# COLORS = {
# "blue": np.array([66., 103., 210.]) / 255.,
# "red": np.array([234., 67., 53.]) / 255.,
# "yellow": np.array([251., 188., 4.]) / 255.,
# "green": np.array([52., 168., 83.]) / 255.,
# "grey": np.array([154., 160., 166.]) / 255.,
# }
# QUESTION_MARK = [None]
# QUESTION_MARK[0] = np.array(Image.open(f).convert("RGB")) * 1.0 / 255.
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | gin_dict = results.gin_dict(gin_config_file) |
Based on the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for irs.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def _identity_discretizer(target, num_bins):
del num_bins
return target
class IrsTest(absltest.TestCase):
def test_metric(self):
gin.bind_parameter("discretizer.discretizer_fn", _identity_discretizer)
gin.bind_parameter("discretizer.num_bins", 10)
<|code_end|>
, predict the immediate next line with the help of imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import irs
import numpy as np
import gin.tf
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/irs.py
# def compute_irs(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# diff_quantile=0.99,
# num_train=gin.REQUIRED,
# batch_size=gin.REQUIRED):
# def _drop_constant_dims(ys):
# def scalable_disentanglement_score(gen_factors, latents, diff_quantile=0.99):
. Output only the next line. | ground_truth_data = dummy_data.IdentityObservationsData() |
Here is a snippet: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for irs.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def _identity_discretizer(target, num_bins):
del num_bins
return target
class IrsTest(absltest.TestCase):
def test_metric(self):
gin.bind_parameter("discretizer.discretizer_fn", _identity_discretizer)
gin.bind_parameter("discretizer.num_bins", 10)
ground_truth_data = dummy_data.IdentityObservationsData()
representation_function = lambda x: np.array(x, dtype=np.float64)
random_state = np.random.RandomState(0)
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import irs
import numpy as np
import gin.tf
and context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/irs.py
# def compute_irs(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# diff_quantile=0.99,
# num_train=gin.REQUIRED,
# batch_size=gin.REQUIRED):
# def _drop_constant_dims(ys):
# def scalable_disentanglement_score(gen_factors, latents, diff_quantile=0.99):
, which may include functions, classes, or code. Output only the next line. | scores = irs.compute_irs(ground_truth_data, representation_function, |
Predict the next line for this snippet: <|code_start|> precisions = [visualize_scores.precision(matrix, x) for x in thresholds]
area = 0.
for i in range(len(precisions)-1):
area += (
precisions[i] + precisions[i+1])*(thresholds[i] - thresholds[i+1])*0.5
scores["area_precision"] = area
scores["max_precision"] = max(precisions)
return scores
@gin.configurable(
"importance_gbt_matrix",
blacklist=["mus_train", "ys_train", "mus_test", "ys_test"])
def importance_gbt_matrix(mus_train, ys_train, mus_test, ys_test):
"""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 representations
in mus_train.
mus_test: Batch of learned representations to be used for testing.
ys_test: Observed factors of variation corresponding to the representations
in mus_test.
Returns:
Importance matrix as computed for the DCI Disentanglement score.
"""
<|code_end|>
with the help of current file imports:
import os
import numpy as np
import gin.tf
from absl import logging
from disentanglement_lib.evaluation.metrics import dci
from disentanglement_lib.evaluation.metrics import modularity_explicitness
from disentanglement_lib.evaluation.metrics import sap_score
from disentanglement_lib.evaluation.metrics import utils
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import dendrogram
from disentanglement_lib.visualize import visualize_scores
and context from other files:
# Path: disentanglement_lib/evaluation/metrics/dci.py
# def compute_dci(ground_truth_data, representation_function, random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def _compute_dci(mus_train, ys_train, mus_test, ys_test):
# def compute_dci_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED, batch_size=100):
# def compute_importance_gbt(x_train, y_train, x_test, y_test):
# def disentanglement_per_code(importance_matrix):
# def disentanglement(importance_matrix):
# def completeness_per_factor(importance_matrix):
# def completeness(importance_matrix):
#
# Path: disentanglement_lib/evaluation/metrics/modularity_explicitness.py
# def compute_modularity_explicitness(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def explicitness_per_factor(mus_train, y_train, mus_test, y_test):
# def modularity(mutual_information):
#
# Path: disentanglement_lib/evaluation/metrics/sap_score.py
# def compute_sap(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16,
# continuous_factors=gin.REQUIRED):
# def _compute_sap(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_sap_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED,
# continuous_factors=gin.REQUIRED,
# batch_size=100):
# def compute_score_matrix(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_avg_diff_top_two(matrix):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/dendrogram.py
# def dendrogram_plot(matrix, output_dir, factor_names):
# def report_merges(z, num_factors):
# def _find(nodes, i):
# def _union(nodes, idx, idy, val, z, cluster_id, size, matrix, n_clusters,
# idx_found):
#
# Path: disentanglement_lib/visualize/visualize_scores.py
# def heat_square(matrix, output_dir, name, xlabel, ylabel, max_val=None,
# factor_names=None):
# def plot_matrix_squares(matrix, max_val, palette, size_scale, ax):
# def to_color(val):
# def plot_bar_palette(palette, max_val, ax):
# def plot_recovery_vs_independent(matrix, output_dir, name):
# def precision(matrix, th):
# def recall(matrix, th):
# def bfs(matrix, to_visit, factors, codes, size):
, which may contain function names, class names, or code. Output only the next line. | matrix_importance_gbt, _, _ = dci.compute_importance_gbt( |
Based on the snippet: <|code_start|> ys_test: Unused.
Returns:
Mutual information matrix as computed for the MIG and Modularity scores.
"""
del mus_test, ys_test
discretized_mus = utils.make_discretizer(mus_train)
m = utils.discrete_mutual_info(discretized_mus, ys_train)
return m
@gin.configurable(
"accuracy_svm_matrix",
blacklist=["mus_train", "ys_train", "mus_test", "ys_test"])
def accuracy_svm_matrix(mus_train, ys_train, mus_test, ys_test):
"""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 representations to be used for testing.
ys_test: Observed factors of variation corresponding to the representations
in mus_test.
Returns:
Accuracy matrix as computed for the SAP score.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import numpy as np
import gin.tf
from absl import logging
from disentanglement_lib.evaluation.metrics import dci
from disentanglement_lib.evaluation.metrics import modularity_explicitness
from disentanglement_lib.evaluation.metrics import sap_score
from disentanglement_lib.evaluation.metrics import utils
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import dendrogram
from disentanglement_lib.visualize import visualize_scores
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/evaluation/metrics/dci.py
# def compute_dci(ground_truth_data, representation_function, random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def _compute_dci(mus_train, ys_train, mus_test, ys_test):
# def compute_dci_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED, batch_size=100):
# def compute_importance_gbt(x_train, y_train, x_test, y_test):
# def disentanglement_per_code(importance_matrix):
# def disentanglement(importance_matrix):
# def completeness_per_factor(importance_matrix):
# def completeness(importance_matrix):
#
# Path: disentanglement_lib/evaluation/metrics/modularity_explicitness.py
# def compute_modularity_explicitness(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def explicitness_per_factor(mus_train, y_train, mus_test, y_test):
# def modularity(mutual_information):
#
# Path: disentanglement_lib/evaluation/metrics/sap_score.py
# def compute_sap(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16,
# continuous_factors=gin.REQUIRED):
# def _compute_sap(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_sap_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED,
# continuous_factors=gin.REQUIRED,
# batch_size=100):
# def compute_score_matrix(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_avg_diff_top_two(matrix):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/dendrogram.py
# def dendrogram_plot(matrix, output_dir, factor_names):
# def report_merges(z, num_factors):
# def _find(nodes, i):
# def _union(nodes, idx, idy, val, z, cluster_id, size, matrix, n_clusters,
# idx_found):
#
# Path: disentanglement_lib/visualize/visualize_scores.py
# def heat_square(matrix, output_dir, name, xlabel, ylabel, max_val=None,
# factor_names=None):
# def plot_matrix_squares(matrix, max_val, palette, size_scale, ax):
# def to_color(val):
# def plot_bar_palette(palette, max_val, ax):
# def plot_recovery_vs_independent(matrix, output_dir, name):
# def precision(matrix, th):
# def recall(matrix, th):
# def bfs(matrix, to_visit, factors, codes, size):
. Output only the next line. | return sap_score.compute_score_matrix( |
Predict the next line for this snippet: <|code_start|>@gin.configurable(
"unified_scores",
blacklist=["ground_truth_data", "representation_function", "random_state",
"artifact_dir"])
def compute_unified_scores(ground_truth_data, representation_function,
random_state,
artifact_dir=None,
num_train=gin.REQUIRED,
num_test=gin.REQUIRED,
matrix_fns=gin.REQUIRED,
batch_size=16):
"""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: Optional path to directory where artifacts can be saved.
num_train: Number of points used for training.
num_test: Number of points used for testing.
matrix_fns: List of functions to relate factors of variations and codes.
batch_size: Batch size for sampling.
Returns:
Unified scores.
"""
logging.info("Generating training set.")
# mus_train are of shape [num_codes, num_train], while ys_train are of shape
# [num_factors, num_train].
<|code_end|>
with the help of current file imports:
import os
import numpy as np
import gin.tf
from absl import logging
from disentanglement_lib.evaluation.metrics import dci
from disentanglement_lib.evaluation.metrics import modularity_explicitness
from disentanglement_lib.evaluation.metrics import sap_score
from disentanglement_lib.evaluation.metrics import utils
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import dendrogram
from disentanglement_lib.visualize import visualize_scores
and context from other files:
# Path: disentanglement_lib/evaluation/metrics/dci.py
# def compute_dci(ground_truth_data, representation_function, random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def _compute_dci(mus_train, ys_train, mus_test, ys_test):
# def compute_dci_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED, batch_size=100):
# def compute_importance_gbt(x_train, y_train, x_test, y_test):
# def disentanglement_per_code(importance_matrix):
# def disentanglement(importance_matrix):
# def completeness_per_factor(importance_matrix):
# def completeness(importance_matrix):
#
# Path: disentanglement_lib/evaluation/metrics/modularity_explicitness.py
# def compute_modularity_explicitness(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def explicitness_per_factor(mus_train, y_train, mus_test, y_test):
# def modularity(mutual_information):
#
# Path: disentanglement_lib/evaluation/metrics/sap_score.py
# def compute_sap(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16,
# continuous_factors=gin.REQUIRED):
# def _compute_sap(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_sap_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED,
# continuous_factors=gin.REQUIRED,
# batch_size=100):
# def compute_score_matrix(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_avg_diff_top_two(matrix):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/dendrogram.py
# def dendrogram_plot(matrix, output_dir, factor_names):
# def report_merges(z, num_factors):
# def _find(nodes, i):
# def _union(nodes, idx, idy, val, z, cluster_id, size, matrix, n_clusters,
# idx_found):
#
# Path: disentanglement_lib/visualize/visualize_scores.py
# def heat_square(matrix, output_dir, name, xlabel, ylabel, max_val=None,
# factor_names=None):
# def plot_matrix_squares(matrix, max_val, palette, size_scale, ax):
# def to_color(val):
# def plot_bar_palette(palette, max_val, ax):
# def plot_recovery_vs_independent(matrix, output_dir, name):
# def precision(matrix, th):
# def recall(matrix, th):
# def bfs(matrix, to_visit, factors, codes, size):
, which may contain function names, class names, or code. Output only the next line. | mus_train, ys_train = utils.generate_batch_factor_code( |
Next line prediction: <|code_start|> batch_size: Batch size used to compute the representation.
Returns:
Unified scores.
"""
mus = utils.obtain_representation(observations, representation_function,
batch_size)
assert labels.shape[1] == observations.shape[0], "Wrong labels shape."
assert mus.shape[1] == observations.shape[0], "Wrong representation shape."
mus_train, mus_test = utils.split_train_test(
mus,
train_percentage)
ys_train, ys_test = utils.split_train_test(
labels,
train_percentage)
return unified_scores(mus_train, ys_train, mus_test, ys_test, matrix_fns)
def unified_scores(mus_train, ys_train, mus_test, ys_test, matrix_fns,
artifact_dir=None, factor_names=None):
"""Computes unified scores."""
scores = {}
kws = {}
for matrix_fn in matrix_fns:
# Matrix should have shape [num_codes, num_factors].
matrix = matrix_fn(mus_train, ys_train, mus_test, ys_test)
matrix_name = matrix_fn.__name__
if artifact_dir is not None:
<|code_end|>
. Use current file imports:
(import os
import numpy as np
import gin.tf
from absl import logging
from disentanglement_lib.evaluation.metrics import dci
from disentanglement_lib.evaluation.metrics import modularity_explicitness
from disentanglement_lib.evaluation.metrics import sap_score
from disentanglement_lib.evaluation.metrics import utils
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import dendrogram
from disentanglement_lib.visualize import visualize_scores)
and context including class names, function names, or small code snippets from other files:
# Path: disentanglement_lib/evaluation/metrics/dci.py
# def compute_dci(ground_truth_data, representation_function, random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def _compute_dci(mus_train, ys_train, mus_test, ys_test):
# def compute_dci_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED, batch_size=100):
# def compute_importance_gbt(x_train, y_train, x_test, y_test):
# def disentanglement_per_code(importance_matrix):
# def disentanglement(importance_matrix):
# def completeness_per_factor(importance_matrix):
# def completeness(importance_matrix):
#
# Path: disentanglement_lib/evaluation/metrics/modularity_explicitness.py
# def compute_modularity_explicitness(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def explicitness_per_factor(mus_train, y_train, mus_test, y_test):
# def modularity(mutual_information):
#
# Path: disentanglement_lib/evaluation/metrics/sap_score.py
# def compute_sap(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16,
# continuous_factors=gin.REQUIRED):
# def _compute_sap(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_sap_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED,
# continuous_factors=gin.REQUIRED,
# batch_size=100):
# def compute_score_matrix(mus, ys, mus_test, ys_test, continuous_factors):
# def compute_avg_diff_top_two(matrix):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/dendrogram.py
# def dendrogram_plot(matrix, output_dir, factor_names):
# def report_merges(z, num_factors):
# def _find(nodes, i):
# def _union(nodes, idx, idy, val, z, cluster_id, size, matrix, n_clusters,
# idx_found):
#
# Path: disentanglement_lib/visualize/visualize_scores.py
# def heat_square(matrix, output_dir, name, xlabel, ylabel, max_val=None,
# factor_names=None):
# def plot_matrix_squares(matrix, max_val, palette, size_scale, ax):
# def to_color(val):
# def plot_bar_palette(palette, max_val, ax):
# def plot_recovery_vs_independent(matrix, output_dir, name):
# def precision(matrix, th):
# def recall(matrix, th):
# def bfs(matrix, to_visit, factors, codes, size):
. Output only the next line. | visualize_scores.heat_square(matrix.copy(), artifact_dir, matrix_name, |
Given the code snippet: <|code_start|> specified as that determines the data set used for training.
Args:
model_dir: String with path to directory where model output should be saved.
overwrite: Boolean indicating whether to overwrite output directory.
model: GaussianEncoderModel that should be trained and exported.
training_steps: Integer with number of training steps.
random_seed: Integer with random seed used for training.
batch_size: Integer with the batch size.
eval_steps: Optional integer with number of steps used for evaluation.
name: Optional string with name of the model (can be used to name models).
model_num: Optional integer with model number (can be used to identify
models).
"""
# We do not use the variables 'name' and 'model_num'. Instead, they can be
# used to name results as they will be part of the saved gin config.
del name, model_num
# Delete the output directory if it already exists.
if tf.gfile.IsDirectory(model_dir):
if overwrite:
tf.gfile.DeleteRecursively(model_dir)
else:
raise ValueError("Directory already exists and overwrite is False.")
# Create a numpy random state. We will sample the random seeds for training
# and evaluation from this.
random_state = np.random.RandomState(random_seed)
# Obtain the dataset.
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
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_model
from disentanglement_lib.methods.unsupervised import vae # pylint: disable=unused-import
from disentanglement_lib.utils import results
from tensorflow.contrib import tpu as contrib_tpu
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | dataset = named_data.get_named_ground_truth_data() |
Given the code snippet: <|code_start|> experiment_timer = time.time()
# Do the actual training.
tpu_estimator.train(
input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
steps=training_steps)
# Save model as a TFHub module.
output_shape = named_data.get_named_ground_truth_data().observation_shape
module_export_path = os.path.join(model_dir, "tfhub")
gaussian_encoder_model.export_as_tf_hub(model, output_shape,
tpu_estimator.latest_checkpoint(),
module_export_path)
# Save the results. The result dir will contain all the results and config
# files that we copied along, as we progress in the pipeline. The idea is that
# these files will be available for analysis at the end.
results_dict = tpu_estimator.evaluate(
input_fn=_make_input_fn(
dataset, random_state.randint(2**32), num_batches=eval_steps))
results_dir = os.path.join(model_dir, "results")
results_dict["elapsed_time"] = time.time() - experiment_timer
results.update_result_directory(results_dir, "train", results_dict)
def _make_input_fn(ground_truth_data, seed, num_batches=None):
"""Creates an input function for the experiments."""
def load_dataset(params):
"""TPUEstimator compatible input fuction."""
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
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_model
from disentanglement_lib.methods.unsupervised import vae # pylint: disable=unused-import
from disentanglement_lib.utils import results
from tensorflow.contrib import tpu as contrib_tpu
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | dataset = util.tf_data_set_from_ground_truth_data(ground_truth_data, seed) |
Predict the next line after this snippet: <|code_start|>
# Obtain the dataset.
dataset = named_data.get_named_ground_truth_data()
# We create a TPUEstimator based on the provided model. This is primarily so
# that we could switch to TPU training in the future. For now, we train
# locally on GPUs.
run_config = contrib_tpu.RunConfig(
tf_random_seed=random_seed,
keep_checkpoint_max=1,
tpu_config=contrib_tpu.TPUConfig(iterations_per_loop=500))
tpu_estimator = contrib_tpu.TPUEstimator(
use_tpu=False,
model_fn=model.model_fn,
model_dir=os.path.join(model_dir, "tf_checkpoint"),
train_batch_size=batch_size,
eval_batch_size=batch_size,
config=run_config)
# Set up time to keep track of elapsed time in results.
experiment_timer = time.time()
# Do the actual training.
tpu_estimator.train(
input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
steps=training_steps)
# Save model as a TFHub module.
output_shape = named_data.get_named_ground_truth_data().observation_shape
module_export_path = os.path.join(model_dir, "tfhub")
<|code_end|>
using the current file's imports:
import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
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_model
from disentanglement_lib.methods.unsupervised import vae # pylint: disable=unused-import
from disentanglement_lib.utils import results
from tensorflow.contrib import tpu as contrib_tpu
and any relevant context from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | gaussian_encoder_model.export_as_tf_hub(model, output_shape, |
Given the code snippet: <|code_start|> use_tpu=False,
model_fn=model.model_fn,
model_dir=os.path.join(model_dir, "tf_checkpoint"),
train_batch_size=batch_size,
eval_batch_size=batch_size,
config=run_config)
# Set up time to keep track of elapsed time in results.
experiment_timer = time.time()
# Do the actual training.
tpu_estimator.train(
input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
steps=training_steps)
# Save model as a TFHub module.
output_shape = named_data.get_named_ground_truth_data().observation_shape
module_export_path = os.path.join(model_dir, "tfhub")
gaussian_encoder_model.export_as_tf_hub(model, output_shape,
tpu_estimator.latest_checkpoint(),
module_export_path)
# Save the results. The result dir will contain all the results and config
# files that we copied along, as we progress in the pipeline. The idea is that
# these files will be available for analysis at the end.
results_dict = tpu_estimator.evaluate(
input_fn=_make_input_fn(
dataset, random_state.randint(2**32), num_batches=eval_steps))
results_dir = os.path.join(model_dir, "results")
results_dict["elapsed_time"] = time.time() - experiment_timer
<|code_end|>
, generate the next line using the imports in this file:
import os
import time
import numpy as np
import tensorflow.compat.v1 as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
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_model
from disentanglement_lib.methods.unsupervised import vae # pylint: disable=unused-import
from disentanglement_lib.utils import results
from tensorflow.contrib import tpu as contrib_tpu
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/data/ground_truth/util.py
# def tf_data_set_from_ground_truth_data(ground_truth_data, random_seed):
# def generator():
# def __init__(self, factor_sizes, latent_factor_indices):
# def num_latent_factors(self):
# def sample_latent_factors(self, num, random_state):
# def sample_all_factors(self, latent_factors, random_state):
# def _sample_factor(self, i, num, random_state):
# def __init__(self, factor_sizes, features):
# def features_to_index(self, features):
# def _features_to_state_space_index(self, features):
# class SplitDiscreteStateSpace(object):
# class StateSpaceAtomIndex(object):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
#
# Path: disentanglement_lib/methods/unsupervised/vae.py
# class BaseVAE(gaussian_encoder_model.GaussianEncoderModel):
# class BetaVAE(BaseVAE):
# class AnnealedVAE(BaseVAE):
# class FactorVAE(BaseVAE):
# class DIPVAE(BaseVAE):
# class BetaTCVAE(BaseVAE):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def shuffle_codes(z):
# def compute_gaussian_kl(z_mean, z_logvar):
# def make_metric_fn(*names):
# def metric_fn(*args):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def anneal(c_max, step, iteration_threshold):
# def __init__(self,
# gamma=gin.REQUIRED,
# c_max=gin.REQUIRED,
# iteration_threshold=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def __init__(self, gamma=gin.REQUIRED):
# def model_fn(self, features, labels, mode, params):
# def compute_covariance_z_mean(z_mean):
# def regularize_diag_off_diag_dip(covariance_matrix, lambda_od, lambda_d):
# def __init__(self,
# lambda_od=gin.REQUIRED,
# lambda_d_factor=gin.REQUIRED,
# dip_type="i"):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def gaussian_log_density(samples, mean, log_var):
# def total_correlation(z, z_mean, z_logvar):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
. Output only the next line. | results.update_result_directory(results_dir, "train", results_dict) |
Predict the next line for this snippet: <|code_start|> Returns:
Tuple with reduced representations for the training and test set.
"""
importance_matrix = correlation_measure(mus_train, ys_train, mus_test,
ys_test)
factor_of_interest_importance = importance_matrix[:, factor_of_interest]
factor_to_remove_index = np.argmax(factor_of_interest_importance)
# Remove the factor of variation above from the representation
reduced_representation_train = np.delete(
mus_train.copy(), factor_to_remove_index, axis=0)
reduced_representation_test = np.delete(
mus_test.copy(), factor_to_remove_index, axis=0)
return reduced_representation_train, reduced_representation_test
@gin.configurable(
"factorwise_dci",
blacklist=["mus_train", "ys_train", "mus_test", "ys_test"])
def compute_factorwise_dci(mus_train, ys_train, mus_test, ys_test):
"""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.
"""
<|code_end|>
with the help of current file imports:
from disentanglement_lib.evaluation.metrics import dci
from disentanglement_lib.evaluation.metrics import utils
from six.moves import range
import numpy as np
import gin.tf
and context from other files:
# Path: disentanglement_lib/evaluation/metrics/dci.py
# def compute_dci(ground_truth_data, representation_function, random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def _compute_dci(mus_train, ys_train, mus_test, ys_test):
# def compute_dci_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED, batch_size=100):
# def compute_importance_gbt(x_train, y_train, x_test, y_test):
# def disentanglement_per_code(importance_matrix):
# def disentanglement(importance_matrix):
# def completeness_per_factor(importance_matrix):
# def completeness(importance_matrix):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
, which may contain function names, class names, or code. Output only the next line. | importance_matrix, _, _ = dci.compute_importance_gbt(mus_train, ys_train, |
Using the snippet: <|code_start|> artifact_dir=None,
num_factors_to_remove=gin.REQUIRED,
num_train=gin.REQUIRED,
num_test=gin.REQUIRED,
batch_size=16):
"""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 input and
outputs a dim_representation sized representation for each observation.
random_state: Numpy random state used for randomness.
artifact_dir: Optional path to directory where artifacts can be saved.
num_factors_to_remove: Number of factors to remove from the latent
representation.
num_train: Number of points used for training.
num_test: Number of points used for testing.
batch_size: Batch size for sampling.
Returns:
Dictionary with scores.
"""
del artifact_dir
scores = {}
# Loop on different sizes of the training 'batch', as specified with gin.
for train_size in num_train:
size_string = str(train_size)
<|code_end|>
, determine the next line of code. You have imports:
from disentanglement_lib.evaluation.metrics import dci
from disentanglement_lib.evaluation.metrics import utils
from six.moves import range
import numpy as np
import gin.tf
and context (class names, function names, or code) available:
# Path: disentanglement_lib/evaluation/metrics/dci.py
# def compute_dci(ground_truth_data, representation_function, random_state,
# artifact_dir=None,
# num_train=gin.REQUIRED,
# num_test=gin.REQUIRED,
# batch_size=16):
# def _compute_dci(mus_train, ys_train, mus_test, ys_test):
# def compute_dci_on_fixed_data(observations, labels, representation_function,
# train_percentage=gin.REQUIRED, batch_size=100):
# def compute_importance_gbt(x_train, y_train, x_test, y_test):
# def disentanglement_per_code(importance_matrix):
# def disentanglement(importance_matrix):
# def completeness_per_factor(importance_matrix):
# def completeness(importance_matrix):
#
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | mus_train, ys_train = utils.generate_batch_factor_code( |
Here is a snippet: <|code_start|>
@gin.configurable(
"irs",
blacklist=["ground_truth_data", "representation_function", "random_state",
"artifact_dir"])
def compute_irs(ground_truth_data,
representation_function,
random_state,
artifact_dir=None,
diff_quantile=0.99,
num_train=gin.REQUIRED,
batch_size=gin.REQUIRED):
"""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: Optional path to directory where artifacts can be saved.
diff_quantile: Float value between 0 and 1 to decide what quantile of diffs
to select (use 1.0 for the version in the paper).
num_train: Number of points used for training.
batch_size: Batch size for sampling.
Returns:
Dict with IRS and number of active dimensions.
"""
del artifact_dir
logging.info("Generating training set.")
<|code_end|>
. Write the next line using the current file imports:
from absl import logging
from disentanglement_lib.evaluation.metrics import utils
import numpy as np
import gin.tf
and context from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
, which may include functions, classes, or code. Output only the next line. | mus, ys = utils.generate_batch_factor_code(ground_truth_data, |
Given the following code snippet before the placeholder: <|code_start|>
@gin.configurable(
"downstream_task",
blacklist=["ground_truth_data", "representation_function", "random_state",
"artifact_dir"])
def compute_downstream_task(ground_truth_data,
representation_function,
random_state,
artifact_dir=None,
num_train=gin.REQUIRED,
num_test=gin.REQUIRED,
batch_size=16):
"""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 to directory where artifacts can be saved.
num_train: Number of points used for training.
num_test: Number of points used for testing.
batch_size: Batch size for sampling.
Returns:
Dictionary with scores.
"""
del artifact_dir
scores = {}
for train_size in num_train:
<|code_end|>
, predict the next line using imports from the current file:
from disentanglement_lib.evaluation.metrics import utils
from six.moves import range
import numpy as np
import gin.tf
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/evaluation/metrics/utils.py
# def generate_batch_factor_code(ground_truth_data, representation_function,
# num_points, random_state, batch_size):
# def split_train_test(observations, train_percentage):
# def obtain_representation(observations, representation_function, batch_size):
# def discrete_mutual_info(mus, ys):
# def discrete_entropy(ys):
# def make_discretizer(target, num_bins=gin.REQUIRED,
# discretizer_fn=gin.REQUIRED):
# def _histogram_discretize(target, num_bins=gin.REQUIRED):
# def normalize_data(data, mean=None, stddev=None):
# def make_predictor_fn(predictor_fn=gin.REQUIRED):
# def logistic_regression_cv():
# def gradient_boosting_classifier():
. Output only the next line. | mus_train, ys_train = utils.generate_batch_factor_code( |
Given the code snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for factor_vae.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class FactorVaeTest(absltest.TestCase):
def test_metric(self):
<|code_end|>
, generate the next line using the imports in this file:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import factor_vae
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/factor_vae.py
# def compute_factor_vae(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# batch_size=gin.REQUIRED,
# num_train=gin.REQUIRED,
# num_eval=gin.REQUIRED,
# num_variance_estimate=gin.REQUIRED):
# def _prune_dims(variances, threshold=0.):
# def _compute_variances(ground_truth_data,
# representation_function,
# batch_size,
# random_state,
# eval_batch_size=64):
# def _generate_training_sample(ground_truth_data, representation_function,
# batch_size, random_state, global_variances,
# active_dims):
# def _generate_training_batch(ground_truth_data, representation_function,
# batch_size, num_points, random_state,
# global_variances, active_dims):
. Output only the next line. | ground_truth_data = dummy_data.IdentityObservationsData() |
Here is a snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for factor_vae.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class FactorVaeTest(absltest.TestCase):
def test_metric(self):
ground_truth_data = dummy_data.IdentityObservationsData()
representation_function = lambda x: x
random_state = np.random.RandomState(0)
<|code_end|>
. Write the next line using the current file imports:
from absl.testing import absltest
from disentanglement_lib.data.ground_truth import dummy_data
from disentanglement_lib.evaluation.metrics import factor_vae
import numpy as np
and context from other files:
# Path: disentanglement_lib/data/ground_truth/dummy_data.py
# class IdentityObservationsData(ground_truth_data.GroundTruthData):
# class DummyData(ground_truth_data.GroundTruthData):
# def num_factors(self):
# def observation_shape(self):
# def factors_num_values(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
# def factor_names(self):
# def num_factors(self):
# def factors_num_values(self):
# def observation_shape(self):
# def sample_factors(self, num, random_state):
# def sample_observations_from_factors(self, factors, random_state):
#
# Path: disentanglement_lib/evaluation/metrics/factor_vae.py
# def compute_factor_vae(ground_truth_data,
# representation_function,
# random_state,
# artifact_dir=None,
# batch_size=gin.REQUIRED,
# num_train=gin.REQUIRED,
# num_eval=gin.REQUIRED,
# num_variance_estimate=gin.REQUIRED):
# def _prune_dims(variances, threshold=0.):
# def _compute_variances(ground_truth_data,
# representation_function,
# batch_size,
# random_state,
# eval_batch_size=64):
# def _generate_training_sample(ground_truth_data, representation_function,
# batch_size, random_state, global_variances,
# active_dims):
# def _generate_training_batch(ground_truth_data, representation_function,
# batch_size, num_points, random_state,
# global_variances, active_dims):
, which may include functions, classes, or code. Output only the next line. | scores = factor_vae.compute_factor_vae( |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import division
from __future__ import print_function
class WeakVaeTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.parameters(
(np.zeros([64, 10]),
np.zeros([64, 10]),
np.ones([64, 10]),
np.ones([64, 10]),
np.concatenate((np.zeros([64, 5]), np.ones([64, 5])), axis=1),
np.concatenate((np.ones([64, 5]), np.zeros([64, 5])), axis=1)),
(np.array([[1, 1]]),
np.array([[1, 1]]),
np.array([[0, 0]]),
np.array([[0, 0]]),
np.array([[0, 0.1]]),
np.array([[0, 1]]))
)
def test_aggregate_argmax(self, z_mean, z_logvar, new_mean, new_log_var,
kl_per_point, target):
mean_tf = tf.convert_to_tensor(z_mean, dtype=np.float32)
logvar_tf = tf.convert_to_tensor(z_logvar, dtype=np.float32)
new_mean_tf = tf.convert_to_tensor(new_mean, dtype=np.float32)
new_log_var_tf = tf.convert_to_tensor(new_log_var, dtype=np.float32)
kl_per_point_tf = tf.convert_to_tensor(kl_per_point, dtype=np.float32)
with self.session() as sess:
<|code_end|>
, predict the next line using imports from the current file:
from absl.testing import parameterized
from disentanglement_lib.methods.weak import weak_vae # pylint: disable=unused-import
import numpy as np
import tensorflow as tf
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/methods/weak/weak_vae.py
# def make_weak_loss(z1, z2, labels, loss_fn=gin.REQUIRED):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_labels(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_argmax(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def discretize_in_bins(x):
# def compute_kl(z_1, z_2, logvar_1, logvar_2):
# def make_metric_fn(*names):
# def metric_fn(*args):
# class GroupVAEBase(vae.BaseVAE):
# class GroupVAELabels(GroupVAEBase):
# class GroupVAEArgmax(GroupVAEBase):
# class MLVae(vae.BaseVAE):
# class MLVaeLabels(MLVae):
# class MLVaeArgmax(MLVae):
. Output only the next line. | test_value = sess.run(weak_vae.aggregate_argmax( |
Continue the code snippet: <|code_start|># coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Visualization code for Interventional Robustness Score.
Based on the paper https://arxiv.org/abs/1811.00007.
"""
matplotlib.use("Agg") # Set headless-friendly backend.
def vis_all_interventional_effects(gen_factors, latents, output_dir):
"""Compute Matrix of all interventional effects."""
<|code_end|>
. Use current file imports:
import os
import matplotlib
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
import numpy as np
import tensorflow.compat.v1 as tf
from disentanglement_lib.evaluation.metrics.irs import scalable_disentanglement_score
and context (classes, functions, or code) from other files:
# Path: disentanglement_lib/evaluation/metrics/irs.py
# def scalable_disentanglement_score(gen_factors, latents, diff_quantile=0.99):
# """Computes IRS scores of a dataset.
#
# Assumes no noise in X and crossed generative factors (i.e. one sample per
# combination of gen_factors). Assumes each g_i is an equally probable
# realization of g_i and all g_i are independent.
#
# Args:
# gen_factors: Numpy array of shape (num samples, num generative factors),
# matrix of ground truth generative factors.
# latents: Numpy array of shape (num samples, num latent dimensions), matrix
# of latent variables.
# diff_quantile: Float value between 0 and 1 to decide what quantile of diffs
# to select (use 1.0 for the version in the paper).
#
# Returns:
# Dictionary with IRS scores.
# """
# num_gen = gen_factors.shape[1]
# num_lat = latents.shape[1]
#
# # Compute normalizer.
# max_deviations = np.max(np.abs(latents - latents.mean(axis=0)), axis=0)
# cum_deviations = np.zeros([num_lat, num_gen])
# for i in range(num_gen):
# unique_factors = np.unique(gen_factors[:, i], axis=0)
# assert unique_factors.ndim == 1
# num_distinct_factors = unique_factors.shape[0]
# for k in range(num_distinct_factors):
# # Compute E[Z | g_i].
# match = gen_factors[:, i] == unique_factors[k]
# e_loc = np.mean(latents[match, :], axis=0)
#
# # Difference of each value within that group of constant g_i to its mean.
# diffs = np.abs(latents[match, :] - e_loc)
# max_diffs = np.percentile(diffs, q=diff_quantile*100, axis=0)
# cum_deviations[:, i] += max_diffs
# cum_deviations[:, i] /= num_distinct_factors
# # Normalize value of each latent dimension with its maximal deviation.
# normalized_deviations = cum_deviations / max_deviations[:, np.newaxis]
# irs_matrix = 1.0 - normalized_deviations
# disentanglement_scores = irs_matrix.max(axis=1)
# if np.sum(max_deviations) > 0.0:
# avg_score = np.average(disentanglement_scores, weights=max_deviations)
# else:
# avg_score = np.mean(disentanglement_scores)
#
# parents = irs_matrix.argmax(axis=1)
# score_dict = {}
# score_dict["disentanglement_scores"] = disentanglement_scores
# score_dict["avg_score"] = avg_score
# score_dict["parents"] = parents
# score_dict["IRS_matrix"] = irs_matrix
# score_dict["max_deviations"] = max_deviations
# return score_dict
. Output only the next line. | res = scalable_disentanglement_score(gen_factors, latents) |
Predict the next line after this snippet: <|code_start|> """Trains the estimator and exports the snapshot and the gin config.
The use of this function requires the gin binding 'dataset.name' to be
specified as that determines the data set used for training.
Args:
model_dir: String with path to directory where model output should be saved.
overwrite: Boolean indicating whether to overwrite output directory.
model: GaussianEncoderModel that should be trained and exported.
training_steps: Integer with number of training steps.
random_seed: Integer with random seed used for training.
batch_size: Integer with the batch size.
name: Optional string with name of the model (can be used to name models).
"""
# We do not use the variable 'name'. Instead, it can be used to name results
# as it will be part of the saved gin config.
del name
# Delete the output directory if necessary.
if tf.compat.v1.gfile.IsDirectory(model_dir):
if overwrite:
tf.compat.v1.gfile.DeleteRecursively(model_dir)
else:
raise ValueError("Directory already exists and overwrite is False.")
# Create a numpy random state. We will sample the random seeds for training
# and evaluation from this.
random_state = np.random.RandomState(random_seed)
# Obtain the dataset.
<|code_end|>
using the current file's imports:
import os
import time
import numpy as np
import tensorflow as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.methods.unsupervised import gaussian_encoder_model
from disentanglement_lib.methods.weak import weak_vae # pylint: disable=unused-import
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import visualize_util
from tensorflow_estimator.python.estimator.tpu import tpu_config
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimator
and any relevant context from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
#
# Path: disentanglement_lib/methods/weak/weak_vae.py
# def make_weak_loss(z1, z2, labels, loss_fn=gin.REQUIRED):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_labels(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_argmax(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def discretize_in_bins(x):
# def compute_kl(z_1, z_2, logvar_1, logvar_2):
# def make_metric_fn(*names):
# def metric_fn(*args):
# class GroupVAEBase(vae.BaseVAE):
# class GroupVAELabels(GroupVAEBase):
# class GroupVAEArgmax(GroupVAEBase):
# class MLVae(vae.BaseVAE):
# class MLVaeLabels(MLVae):
# class MLVaeArgmax(MLVae):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
. Output only the next line. | dataset = named_data.get_named_ground_truth_data() |
Next line prediction: <|code_start|> # Create a numpy random state. We will sample the random seeds for training
# and evaluation from this.
random_state = np.random.RandomState(random_seed)
# Obtain the dataset.
dataset = named_data.get_named_ground_truth_data()
# We create a TPUEstimator based on the provided model. This is primarily so
# that we could switch to TPU training in the future. For now, we train
# locally on GPUs.
run_config = tpu_config.RunConfig(
tf_random_seed=random_seed,
keep_checkpoint_max=1,
tpu_config=tpu_config.TPUConfig(iterations_per_loop=500))
tpu_estimator = TPUEstimator(
use_tpu=False,
model_fn=model.model_fn,
model_dir=model_dir,
train_batch_size=batch_size,
eval_batch_size=batch_size,
config=run_config)
# Set up time to keep track of elapsed time in results.
experiment_timer = time.time()
# Do the actual training.
tpu_estimator.train(
input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
steps=training_steps)
# Save model as a TFHub module.
output_shape = named_data.get_named_ground_truth_data().observation_shape
module_export_path = os.path.join(model_dir, "tfhub")
<|code_end|>
. Use current file imports:
(import os
import time
import numpy as np
import tensorflow as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.methods.unsupervised import gaussian_encoder_model
from disentanglement_lib.methods.weak import weak_vae # pylint: disable=unused-import
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import visualize_util
from tensorflow_estimator.python.estimator.tpu import tpu_config
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimator)
and context including class names, function names, or small code snippets from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
#
# Path: disentanglement_lib/methods/weak/weak_vae.py
# def make_weak_loss(z1, z2, labels, loss_fn=gin.REQUIRED):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_labels(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_argmax(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def discretize_in_bins(x):
# def compute_kl(z_1, z_2, logvar_1, logvar_2):
# def make_metric_fn(*names):
# def metric_fn(*args):
# class GroupVAEBase(vae.BaseVAE):
# class GroupVAELabels(GroupVAEBase):
# class GroupVAEArgmax(GroupVAEBase):
# class MLVae(vae.BaseVAE):
# class MLVaeLabels(MLVae):
# class MLVaeArgmax(MLVae):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
. Output only the next line. | gaussian_encoder_model.export_as_tf_hub(model, output_shape, |
Given the following code snippet before the placeholder: <|code_start|> tpu_estimator = TPUEstimator(
use_tpu=False,
model_fn=model.model_fn,
model_dir=model_dir,
train_batch_size=batch_size,
eval_batch_size=batch_size,
config=run_config)
# Set up time to keep track of elapsed time in results.
experiment_timer = time.time()
# Do the actual training.
tpu_estimator.train(
input_fn=_make_input_fn(dataset, random_state.randint(2**32)),
steps=training_steps)
# Save model as a TFHub module.
output_shape = named_data.get_named_ground_truth_data().observation_shape
module_export_path = os.path.join(model_dir, "tfhub")
gaussian_encoder_model.export_as_tf_hub(model, output_shape,
tpu_estimator.latest_checkpoint(),
module_export_path)
# Save the results. The result dir will contain all the results and config
# files that we copied along, as we progress in the pipeline. The idea is that
# these files will be available for analysis at the end.
results_dict = tpu_estimator.evaluate(
input_fn=_make_input_fn(
dataset, random_state.randint(2**32), num_batches=1000
))
results_dir = os.path.join(model_dir, "results")
results_dict["elapsed_time"] = time.time() - experiment_timer
<|code_end|>
, predict the next line using imports from the current file:
import os
import time
import numpy as np
import tensorflow as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.methods.unsupervised import gaussian_encoder_model
from disentanglement_lib.methods.weak import weak_vae # pylint: disable=unused-import
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import visualize_util
from tensorflow_estimator.python.estimator.tpu import tpu_config
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimator
and context including class names, function names, and sometimes code from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
#
# Path: disentanglement_lib/methods/weak/weak_vae.py
# def make_weak_loss(z1, z2, labels, loss_fn=gin.REQUIRED):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_labels(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_argmax(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def discretize_in_bins(x):
# def compute_kl(z_1, z_2, logvar_1, logvar_2):
# def make_metric_fn(*names):
# def metric_fn(*args):
# class GroupVAEBase(vae.BaseVAE):
# class GroupVAELabels(GroupVAEBase):
# class GroupVAEArgmax(GroupVAEBase):
# class MLVae(vae.BaseVAE):
# class MLVaeLabels(MLVae):
# class MLVaeArgmax(MLVae):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
. Output only the next line. | results.update_result_directory(results_dir, "train", results_dict) |
Based on the snippet: <|code_start|> Args:
data: String with name of dataset as defined in named_data.py.
path: String with path in which to create the visualizations.
num_animations: Integer with number of distinct animations to create.
num_frames: Integer with number of frames in each animation.
fps: Integer with frame rate for the animation.
"""
random_state = np.random.RandomState(0)
# Create output folder if necessary.
if not tf.compat.v1.gfile.IsDirectory(path):
tf.compat.v1.gfile.MakeDirs(path)
# Create animations.
images = []
for i in range(num_animations):
images.append([])
factor = data.sample_factors(1, random_state)
images[i].append(
np.squeeze(
data.sample_observations_from_factors(factor, random_state),
axis=0))
for _ in range(num_frames):
factor, _ = simple_dynamics(factor, data, random_state)
images[i].append(
np.squeeze(
data.sample_observations_from_factors(factor, random_state),
axis=0))
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import time
import numpy as np
import tensorflow as tf
import gin.tf.external_configurables # pylint: disable=unused-import
import gin.tf
from disentanglement_lib.data.ground_truth import named_data
from disentanglement_lib.methods.unsupervised import gaussian_encoder_model
from disentanglement_lib.methods.weak import weak_vae # pylint: disable=unused-import
from disentanglement_lib.utils import results
from disentanglement_lib.visualize import visualize_util
from tensorflow_estimator.python.estimator.tpu import tpu_config
from tensorflow_estimator.python.estimator.tpu.tpu_estimator import TPUEstimator
and context (classes, functions, sometimes code) from other files:
# Path: disentanglement_lib/data/ground_truth/named_data.py
# def get_named_ground_truth_data(name):
#
# Path: disentanglement_lib/methods/unsupervised/gaussian_encoder_model.py
# class GaussianEncoderModel(object):
# def model_fn(self, features, labels, mode, params):
# def gaussian_encoder(self, input_tensor, is_training):
# def decode(self, latent_tensor, observation_shape, is_training):
# def sample_from_latent_distribution(self, z_mean, z_logvar):
# def export_as_tf_hub(gaussian_encoder_model,
# observation_shape,
# checkpoint_path,
# export_path,
# drop_collections=None):
# def module_fn(is_training):
#
# Path: disentanglement_lib/methods/weak/weak_vae.py
# def make_weak_loss(z1, z2, labels, loss_fn=gin.REQUIRED):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def __init__(self, beta=gin.REQUIRED):
# def regularizer(self, kl_loss, z_mean, z_logvar, z_sampled):
# def model_fn(self, features, labels, mode, params):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate(self, z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_labels(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def aggregate_argmax(z_mean, z_logvar, new_mean, new_log_var, labels,
# kl_per_point):
# def discretize_in_bins(x):
# def compute_kl(z_1, z_2, logvar_1, logvar_2):
# def make_metric_fn(*names):
# def metric_fn(*args):
# class GroupVAEBase(vae.BaseVAE):
# class GroupVAELabels(GroupVAEBase):
# class GroupVAEArgmax(GroupVAEBase):
# class MLVae(vae.BaseVAE):
# class MLVaeLabels(MLVae):
# class MLVaeArgmax(MLVae):
#
# Path: disentanglement_lib/utils/results.py
# def update_result_directory(result_directory,
# step_name,
# results_dict,
# old_result_directory=None):
# def _copy_recursively(path_to_old_dir, path_to_new_dir):
# def copydir(path_to_old_dir, path_to_new_dir):
# def save_gin(config_path):
# def default(self, obj):
# def save_dict(config_path, dict_with_info):
# def gin_dict(config_path=None):
# def namespaced_dict(base_dict=None, **named_dicts):
# def aggregate_json_results(base_path):
# class Encoder(json.JSONEncoder):
#
# Path: disentanglement_lib/visualize/visualize_util.py
# def save_image(image, image_path):
# def grid_save_images(images, image_path):
# def padded_grid(images, num_rows=None, padding_px=10, value=None):
# def padded_stack(images, padding_px=10, axis=0, value=None):
# def padding_array(image, padding_px, axis, value=None):
# def best_num_rows(num_elements, max_ratio=4):
# def pad_around(image, padding_px=10, axis=None, value=None):
# def add_below(image, padding_px=10, value=None):
# def save_animation(list_of_animated_images, image_path, fps):
# def cycle_factor(starting_index, num_indices, num_frames):
# def cycle_gaussian(starting_value, num_frames, loc=0., scale=1.):
# def cycle_interval(starting_value, num_frames, min_val, max_val):
. Output only the next line. | visualize_util.save_animation( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.