repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.database_admin_api
def database_admin_api(self): """Helper for session-related API calls.""" if self._database_admin_api is None: self._database_admin_api = DatabaseAdminClient( credentials=self.credentials, client_info=_CLIENT_INFO ) return self._database_admin_api
python
def database_admin_api(self): """Helper for session-related API calls.""" if self._database_admin_api is None: self._database_admin_api = DatabaseAdminClient( credentials=self.credentials, client_info=_CLIENT_INFO ) return self._database_admin_api
[ "def", "database_admin_api", "(", "self", ")", ":", "if", "self", ".", "_database_admin_api", "is", "None", ":", "self", ".", "_database_admin_api", "=", "DatabaseAdminClient", "(", "credentials", "=", "self", ".", "credentials", ",", "client_info", "=", "_CLIEN...
Helper for session-related API calls.
[ "Helper", "for", "session", "-", "related", "API", "calls", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L161-L167
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.copy
def copy(self): """Make a copy of this client. Copies the local data stored as simple types but does not copy the current state of any open connections with the Cloud Bigtable API. :rtype: :class:`.Client` :returns: A copy of the current client. """ return self....
python
def copy(self): """Make a copy of this client. Copies the local data stored as simple types but does not copy the current state of any open connections with the Cloud Bigtable API. :rtype: :class:`.Client` :returns: A copy of the current client. """ return self....
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "project", "=", "self", ".", "project", ",", "credentials", "=", "self", ".", "_credentials", ",", "user_agent", "=", "self", ".", "user_agent", ",", ")" ]
Make a copy of this client. Copies the local data stored as simple types but does not copy the current state of any open connections with the Cloud Bigtable API. :rtype: :class:`.Client` :returns: A copy of the current client.
[ "Make", "a", "copy", "of", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L169-L182
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.list_instance_configs
def list_instance_configs(self, page_size=None, page_token=None): """List available instance configurations for the client's project. .. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\ google.spanner.admin.instance.v1#google.spanner.admin.\ i...
python
def list_instance_configs(self, page_size=None, page_token=None): """List available instance configurations for the client's project. .. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\ google.spanner.admin.instance.v1#google.spanner.admin.\ i...
[ "def", "list_instance_configs", "(", "self", ",", "page_size", "=", "None", ",", "page_token", "=", "None", ")", ":", "metadata", "=", "_metadata_with_prefix", "(", "self", ".", "project_name", ")", "path", "=", "\"projects/%s\"", "%", "(", "self", ".", "pro...
List available instance configurations for the client's project. .. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\ google.spanner.admin.instance.v1#google.spanner.admin.\ instance.v1.InstanceAdmin.ListInstanceConfigs See `RPC docs`_. ...
[ "List", "available", "instance", "configurations", "for", "the", "client", "s", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L184-L220
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.instance
def instance( self, instance_id, configuration_name=None, display_name=None, node_count=DEFAULT_NODE_COUNT, ): """Factory to create a instance associated with this client. :type instance_id: str :param instance_id: The ID of the instance. :ty...
python
def instance( self, instance_id, configuration_name=None, display_name=None, node_count=DEFAULT_NODE_COUNT, ): """Factory to create a instance associated with this client. :type instance_id: str :param instance_id: The ID of the instance. :ty...
[ "def", "instance", "(", "self", ",", "instance_id", ",", "configuration_name", "=", "None", ",", "display_name", "=", "None", ",", "node_count", "=", "DEFAULT_NODE_COUNT", ",", ")", ":", "return", "Instance", "(", "instance_id", ",", "self", ",", "configuratio...
Factory to create a instance associated with this client. :type instance_id: str :param instance_id: The ID of the instance. :type configuration_name: string :param configuration_name: (Optional) Name of the instance configuration used to set up the instance's clu...
[ "Factory", "to", "create", "a", "instance", "associated", "with", "this", "client", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L222-L254
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/client.py
Client.list_instances
def list_instances(self, filter_="", page_size=None, page_token=None): """List instances for the client's project. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances :type filter_: string ...
python
def list_instances(self, filter_="", page_size=None, page_token=None): """List instances for the client's project. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances :type filter_: string ...
[ "def", "list_instances", "(", "self", ",", "filter_", "=", "\"\"", ",", "page_size", "=", "None", ",", "page_token", "=", "None", ")", ":", "metadata", "=", "_metadata_with_prefix", "(", "self", ".", "project_name", ")", "path", "=", "\"projects/%s\"", "%", ...
List instances for the client's project. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.InstanceAdmin.ListInstances :type filter_: string :param filter_: (Optional) Filter to select instances listed. See ...
[ "List", "instances", "for", "the", "client", "s", "project", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/client.py#L256-L292
train
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/retry.py
_should_retry
def _should_retry(exc): """Predicate for determining when to retry. We retry if and only if the 'reason' is 'backendError' or 'rateLimitExceeded'. """ if not hasattr(exc, "errors"): return False if len(exc.errors) == 0: # Check for unstructured error returns, e.g. from GFE ...
python
def _should_retry(exc): """Predicate for determining when to retry. We retry if and only if the 'reason' is 'backendError' or 'rateLimitExceeded'. """ if not hasattr(exc, "errors"): return False if len(exc.errors) == 0: # Check for unstructured error returns, e.g. from GFE ...
[ "def", "_should_retry", "(", "exc", ")", ":", "if", "not", "hasattr", "(", "exc", ",", "\"errors\"", ")", ":", "return", "False", "if", "len", "(", "exc", ".", "errors", ")", "==", "0", ":", "# Check for unstructured error returns, e.g. from GFE", "return", ...
Predicate for determining when to retry. We retry if and only if the 'reason' is 'backendError' or 'rateLimitExceeded'.
[ "Predicate", "for", "determining", "when", "to", "retry", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/retry.py#L30-L44
train
googleapis/google-cloud-python
logging/noxfile.py
default
def default(session, django_dep=('django',)): """Default unit test session. """ # Install all test dependencies, then install this package in-place. deps = UNIT_TEST_DEPS deps += django_dep session.install(*deps) for local_dep in LOCAL_DEPS: session.install('-e', local_dep) ses...
python
def default(session, django_dep=('django',)): """Default unit test session. """ # Install all test dependencies, then install this package in-place. deps = UNIT_TEST_DEPS deps += django_dep session.install(*deps) for local_dep in LOCAL_DEPS: session.install('-e', local_dep) ses...
[ "def", "default", "(", "session", ",", "django_dep", "=", "(", "'django'", ",", ")", ")", ":", "# Install all test dependencies, then install this package in-place.", "deps", "=", "UNIT_TEST_DEPS", "deps", "+=", "django_dep", "session", ".", "install", "(", "*", "de...
Default unit test session.
[ "Default", "unit", "test", "session", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/noxfile.py#L77-L102
train
googleapis/google-cloud-python
logging/noxfile.py
unit
def unit(session): """Run the unit test suite.""" # Testing multiple version of django # See https://www.djangoproject.com/download/ for supported version django_deps_27 = [ ('django==1.8.19',), ('django >= 1.11.0, < 2.0.0dev',), ] if session.virtualenv.interpreter == '2.7': ...
python
def unit(session): """Run the unit test suite.""" # Testing multiple version of django # See https://www.djangoproject.com/download/ for supported version django_deps_27 = [ ('django==1.8.19',), ('django >= 1.11.0, < 2.0.0dev',), ] if session.virtualenv.interpreter == '2.7': ...
[ "def", "unit", "(", "session", ")", ":", "# Testing multiple version of django", "# See https://www.djangoproject.com/download/ for supported version", "django_deps_27", "=", "[", "(", "'django==1.8.19'", ",", ")", ",", "(", "'django >= 1.11.0, < 2.0.0dev'", ",", ")", ",", ...
Run the unit test suite.
[ "Run", "the", "unit", "test", "suite", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/noxfile.py#L106-L119
train
googleapis/google-cloud-python
logging/noxfile.py
system
def system(session): """Run the system test suite.""" # Sanity check: Only run system tests if the environment variable is set. if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''): session.skip('Credentials must be set via environment variable.') # Use pre-release gRPC for system tests...
python
def system(session): """Run the system test suite.""" # Sanity check: Only run system tests if the environment variable is set. if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''): session.skip('Credentials must be set via environment variable.') # Use pre-release gRPC for system tests...
[ "def", "system", "(", "session", ")", ":", "# Sanity check: Only run system tests if the environment variable is set.", "if", "not", "os", ".", "environ", ".", "get", "(", "'GOOGLE_APPLICATION_CREDENTIALS'", ",", "''", ")", ":", "session", ".", "skip", "(", "'Credenti...
Run the system test suite.
[ "Run", "the", "system", "test", "suite", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/noxfile.py#L123-L154
train
googleapis/google-cloud-python
logging/google/cloud/logging/_helpers.py
entry_from_resource
def entry_from_resource(resource, client, loggers): """Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that owns the log entry. ...
python
def entry_from_resource(resource, client, loggers): """Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that owns the log entry. ...
[ "def", "entry_from_resource", "(", "resource", ",", "client", ",", "loggers", ")", ":", "if", "\"textPayload\"", "in", "resource", ":", "return", "TextEntry", ".", "from_api_repr", "(", "resource", ",", "client", ",", "loggers", ")", "if", "\"jsonPayload\"", "...
Detect correct entry type from resource and instantiate. :type resource: dict :param resource: One entry resource from API response. :type client: :class:`~google.cloud.logging.client.Client` :param client: Client that owns the log entry. :type loggers: dict :param loggers: A mapping ...
[ "Detect", "correct", "entry", "type", "from", "resource", "and", "instantiate", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_helpers.py#L28-L55
train
googleapis/google-cloud-python
logging/google/cloud/logging/_helpers.py
retrieve_metadata_server
def retrieve_metadata_server(metadata_key): """Retrieve the metadata key in the metadata server. See: https://cloud.google.com/compute/docs/storing-retrieving-metadata :type metadata_key: str :param metadata_key: Key of the metadata which will form the url. You can also supply...
python
def retrieve_metadata_server(metadata_key): """Retrieve the metadata key in the metadata server. See: https://cloud.google.com/compute/docs/storing-retrieving-metadata :type metadata_key: str :param metadata_key: Key of the metadata which will form the url. You can also supply...
[ "def", "retrieve_metadata_server", "(", "metadata_key", ")", ":", "url", "=", "METADATA_URL", "+", "metadata_key", "try", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "METADATA_HEADERS", ")", "if", "response", ".", "status_cod...
Retrieve the metadata key in the metadata server. See: https://cloud.google.com/compute/docs/storing-retrieving-metadata :type metadata_key: str :param metadata_key: Key of the metadata which will form the url. You can also supply query parameters after the metadata key. ...
[ "Retrieve", "the", "metadata", "key", "in", "the", "metadata", "server", "." ]
85e80125a59cb10f8cb105f25ecc099e4b940b50
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_helpers.py#L58-L84
train
tensorflow/cleverhans
cleverhans/utils_tf.py
model_loss
def model_loss(y, model, mean=True): """ Define loss of TF graph :param y: correct labels :param model: output of the model :param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch :return: return mean of loss if True, otherwise return...
python
def model_loss(y, model, mean=True): """ Define loss of TF graph :param y: correct labels :param model: output of the model :param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch :return: return mean of loss if True, otherwise return...
[ "def", "model_loss", "(", "y", ",", "model", ",", "mean", "=", "True", ")", ":", "warnings", ".", "warn", "(", "\"This function is deprecated and will be removed on or after\"", "\" 2019-04-05. Switch to cleverhans.train.train.\"", ")", "op", "=", "model", ".", "op", ...
Define loss of TF graph :param y: correct labels :param model: output of the model :param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch :return: return mean of loss if True, otherwise return vector with per sample loss
[ "Define", "loss", "of", "TF", "graph", ":", "param", "y", ":", "correct", "labels", ":", "param", "model", ":", "output", "of", "the", "model", ":", "param", "mean", ":", "boolean", "indicating", "whether", "should", "return", "mean", "of", "loss", "or",...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L28-L50
train
tensorflow/cleverhans
cleverhans/utils_tf.py
initialize_uninitialized_global_variables
def initialize_uninitialized_global_variables(sess): """ Only initializes the variables of a TensorFlow session that were not already initialized. :param sess: the TensorFlow session :return: """ # List all global variables global_vars = tf.global_variables() # Find initialized status for all variabl...
python
def initialize_uninitialized_global_variables(sess): """ Only initializes the variables of a TensorFlow session that were not already initialized. :param sess: the TensorFlow session :return: """ # List all global variables global_vars = tf.global_variables() # Find initialized status for all variabl...
[ "def", "initialize_uninitialized_global_variables", "(", "sess", ")", ":", "# List all global variables", "global_vars", "=", "tf", ".", "global_variables", "(", ")", "# Find initialized status for all variables", "is_var_init", "=", "[", "tf", ".", "is_variable_initialized",...
Only initializes the variables of a TensorFlow session that were not already initialized. :param sess: the TensorFlow session :return:
[ "Only", "initializes", "the", "variables", "of", "a", "TensorFlow", "session", "that", "were", "not", "already", "initialized", ".", ":", "param", "sess", ":", "the", "TensorFlow", "session", ":", "return", ":" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L53-L73
train
tensorflow/cleverhans
cleverhans/utils_tf.py
train
def train(sess, loss, x, y, X_train, Y_train, save=False, init_all=False, evaluate=None, feed=None, args=None, rng=None, var_list=None, fprop_args=None, optimizer=None): """ Train a TF graph. This function is deprecated. Prefer cleverhans.train.train when possible. cleverhans.train.train sup...
python
def train(sess, loss, x, y, X_train, Y_train, save=False, init_all=False, evaluate=None, feed=None, args=None, rng=None, var_list=None, fprop_args=None, optimizer=None): """ Train a TF graph. This function is deprecated. Prefer cleverhans.train.train when possible. cleverhans.train.train sup...
[ "def", "train", "(", "sess", ",", "loss", ",", "x", ",", "y", ",", "X_train", ",", "Y_train", ",", "save", "=", "False", ",", "init_all", "=", "False", ",", "evaluate", "=", "None", ",", "feed", "=", "None", ",", "args", "=", "None", ",", "rng", ...
Train a TF graph. This function is deprecated. Prefer cleverhans.train.train when possible. cleverhans.train.train supports multiple GPUs but this function is still needed to support legacy models that do not support calling fprop more than once. :param sess: TF session to use when training the graph :para...
[ "Train", "a", "TF", "graph", ".", "This", "function", "is", "deprecated", ".", "Prefer", "cleverhans", ".", "train", ".", "train", "when", "possible", ".", "cleverhans", ".", "train", ".", "train", "supports", "multiple", "GPUs", "but", "this", "function", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L76-L193
train
tensorflow/cleverhans
cleverhans/utils_tf.py
model_eval
def model_eval(sess, x, y, predictions, X_test=None, Y_test=None, feed=None, args=None): """ Compute the accuracy of a TF model on some data :param sess: TF session to use :param x: input placeholder :param y: output placeholder (for labels) :param predictions: model output predictions :par...
python
def model_eval(sess, x, y, predictions, X_test=None, Y_test=None, feed=None, args=None): """ Compute the accuracy of a TF model on some data :param sess: TF session to use :param x: input placeholder :param y: output placeholder (for labels) :param predictions: model output predictions :par...
[ "def", "model_eval", "(", "sess", ",", "x", ",", "y", ",", "predictions", ",", "X_test", "=", "None", ",", "Y_test", "=", "None", ",", "feed", "=", "None", ",", "args", "=", "None", ")", ":", "global", "_model_eval_cache", "args", "=", "_ArgsWrapper", ...
Compute the accuracy of a TF model on some data :param sess: TF session to use :param x: input placeholder :param y: output placeholder (for labels) :param predictions: model output predictions :param X_test: numpy array with training inputs :param Y_test: numpy array with training outputs :param feed: An...
[ "Compute", "the", "accuracy", "of", "a", "TF", "model", "on", "some", "data", ":", "param", "sess", ":", "TF", "session", "to", "use", ":", "param", "x", ":", "input", "placeholder", ":", "param", "y", ":", "output", "placeholder", "(", "for", "labels"...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L196-L269
train
tensorflow/cleverhans
cleverhans/utils_tf.py
batch_eval
def batch_eval(*args, **kwargs): """ Wrapper around deprecated function. """ # Inside function to avoid circular import from cleverhans.evaluation import batch_eval as new_batch_eval warnings.warn("batch_eval has moved to cleverhans.evaluation. " "batch_eval will be removed from utils_tf on ...
python
def batch_eval(*args, **kwargs): """ Wrapper around deprecated function. """ # Inside function to avoid circular import from cleverhans.evaluation import batch_eval as new_batch_eval warnings.warn("batch_eval has moved to cleverhans.evaluation. " "batch_eval will be removed from utils_tf on ...
[ "def", "batch_eval", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Inside function to avoid circular import", "from", "cleverhans", ".", "evaluation", "import", "batch_eval", "as", "new_batch_eval", "warnings", ".", "warn", "(", "\"batch_eval has moved to cl...
Wrapper around deprecated function.
[ "Wrapper", "around", "deprecated", "function", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L292-L301
train
tensorflow/cleverhans
cleverhans/utils_tf.py
model_argmax
def model_argmax(sess, x, predictions, samples, feed=None): """ Helper function that computes the current class prediction :param sess: TF session :param x: the input placeholder :param predictions: the model's symbolic output :param samples: numpy array with input samples (dims must match x) :param feed:...
python
def model_argmax(sess, x, predictions, samples, feed=None): """ Helper function that computes the current class prediction :param sess: TF session :param x: the input placeholder :param predictions: the model's symbolic output :param samples: numpy array with input samples (dims must match x) :param feed:...
[ "def", "model_argmax", "(", "sess", ",", "x", ",", "predictions", ",", "samples", ",", "feed", "=", "None", ")", ":", "feed_dict", "=", "{", "x", ":", "samples", "}", "if", "feed", "is", "not", "None", ":", "feed_dict", ".", "update", "(", "feed", ...
Helper function that computes the current class prediction :param sess: TF session :param x: the input placeholder :param predictions: the model's symbolic output :param samples: numpy array with input samples (dims must match x) :param feed: An optional dictionary that is appended to the feeding d...
[ "Helper", "function", "that", "computes", "the", "current", "class", "prediction", ":", "param", "sess", ":", "TF", "session", ":", "param", "x", ":", "the", "input", "placeholder", ":", "param", "predictions", ":", "the", "model", "s", "symbolic", "output",...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L304-L324
train
tensorflow/cleverhans
cleverhans/utils_tf.py
l2_batch_normalize
def l2_batch_normalize(x, epsilon=1e-12, scope=None): """ Helper function to normalize a batch of vectors. :param x: the input placeholder :param epsilon: stabilizes division :return: the batch of l2 normalized vector """ with tf.name_scope(scope, "l2_batch_normalize") as name_scope: x_shape = tf.shap...
python
def l2_batch_normalize(x, epsilon=1e-12, scope=None): """ Helper function to normalize a batch of vectors. :param x: the input placeholder :param epsilon: stabilizes division :return: the batch of l2 normalized vector """ with tf.name_scope(scope, "l2_batch_normalize") as name_scope: x_shape = tf.shap...
[ "def", "l2_batch_normalize", "(", "x", ",", "epsilon", "=", "1e-12", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "\"l2_batch_normalize\"", ")", "as", "name_scope", ":", "x_shape", "=", "tf", ".", "shape", "(",...
Helper function to normalize a batch of vectors. :param x: the input placeholder :param epsilon: stabilizes division :return: the batch of l2 normalized vector
[ "Helper", "function", "to", "normalize", "a", "batch", "of", "vectors", ".", ":", "param", "x", ":", "the", "input", "placeholder", ":", "param", "epsilon", ":", "stabilizes", "division", ":", "return", ":", "the", "batch", "of", "l2", "normalized", "vecto...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L327-L341
train
tensorflow/cleverhans
cleverhans/utils_tf.py
kl_with_logits
def kl_with_logits(p_logits, q_logits, scope=None, loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES): """Helper function to compute kl-divergence KL(p || q) """ with tf.name_scope(scope, "kl_divergence") as name: p = tf.nn.softmax(p_logits) p_log = tf.nn.log_softmax(p_logits) q_lo...
python
def kl_with_logits(p_logits, q_logits, scope=None, loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES): """Helper function to compute kl-divergence KL(p || q) """ with tf.name_scope(scope, "kl_divergence") as name: p = tf.nn.softmax(p_logits) p_log = tf.nn.log_softmax(p_logits) q_lo...
[ "def", "kl_with_logits", "(", "p_logits", ",", "q_logits", ",", "scope", "=", "None", ",", "loss_collection", "=", "tf", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "\"kl_divergence\"", ")", "...
Helper function to compute kl-divergence KL(p || q)
[ "Helper", "function", "to", "compute", "kl", "-", "divergence", "KL", "(", "p", "||", "q", ")" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L344-L355
train
tensorflow/cleverhans
cleverhans/utils_tf.py
clip_eta
def clip_eta(eta, ord, eps): """ Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param ord: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation. """ # Clipping p...
python
def clip_eta(eta, ord, eps): """ Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param ord: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation. """ # Clipping p...
[ "def", "clip_eta", "(", "eta", ",", "ord", ",", "eps", ")", ":", "# Clipping perturbation eta to self.ord norm ball", "if", "ord", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "'ord must be np.inf, 1, or 2.'", ...
Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param ord: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation.
[ "Helper", "function", "to", "clip", "the", "perturbation", "to", "epsilon", "norm", "ball", ".", ":", "param", "eta", ":", "A", "tensor", "with", "the", "current", "perturbation", ".", ":", "param", "ord", ":", "Order", "of", "the", "norm", "(", "mimics"...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L358-L392
train
tensorflow/cleverhans
cleverhans/utils_tf.py
infer_devices
def infer_devices(devices=None): """ Returns the list of devices that multi-replica code should use. :param devices: list of string device names, e.g. ["/GPU:0"] If the user specifies this, `infer_devices` checks that it is valid, and then uses this user-specified list. If the user does not spec...
python
def infer_devices(devices=None): """ Returns the list of devices that multi-replica code should use. :param devices: list of string device names, e.g. ["/GPU:0"] If the user specifies this, `infer_devices` checks that it is valid, and then uses this user-specified list. If the user does not spec...
[ "def", "infer_devices", "(", "devices", "=", "None", ")", ":", "if", "devices", "is", "None", ":", "devices", "=", "get_available_gpus", "(", ")", "if", "len", "(", "devices", ")", "==", "0", ":", "warnings", ".", "warn", "(", "\"No GPUS, running on CPU\""...
Returns the list of devices that multi-replica code should use. :param devices: list of string device names, e.g. ["/GPU:0"] If the user specifies this, `infer_devices` checks that it is valid, and then uses this user-specified list. If the user does not specify this, infer_devices uses: -...
[ "Returns", "the", "list", "of", "devices", "that", "multi", "-", "replica", "code", "should", "use", ".", ":", "param", "devices", ":", "list", "of", "string", "device", "names", "e", ".", "g", ".", "[", "/", "GPU", ":", "0", "]", "If", "the", "use...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L502-L523
train
tensorflow/cleverhans
cleverhans/utils_tf.py
get_available_gpus
def get_available_gpus(): """ Returns a list of string names of all available GPUs """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
python
def get_available_gpus(): """ Returns a list of string names of all available GPUs """ local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU']
[ "def", "get_available_gpus", "(", ")", ":", "local_device_protos", "=", "device_lib", ".", "list_local_devices", "(", ")", "return", "[", "x", ".", "name", "for", "x", "in", "local_device_protos", "if", "x", ".", "device_type", "==", "'GPU'", "]" ]
Returns a list of string names of all available GPUs
[ "Returns", "a", "list", "of", "string", "names", "of", "all", "available", "GPUs" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L526-L531
train
tensorflow/cleverhans
cleverhans/utils_tf.py
clip_by_value
def clip_by_value(t, clip_value_min, clip_value_max, name=None): """ A wrapper for clip_by_value that casts the clipping range if needed. """ def cast_clip(clip): """ Cast clipping range argument if needed. """ if t.dtype in (tf.float32, tf.float64): if hasattr(clip, 'dtype'): # Co...
python
def clip_by_value(t, clip_value_min, clip_value_max, name=None): """ A wrapper for clip_by_value that casts the clipping range if needed. """ def cast_clip(clip): """ Cast clipping range argument if needed. """ if t.dtype in (tf.float32, tf.float64): if hasattr(clip, 'dtype'): # Co...
[ "def", "clip_by_value", "(", "t", ",", "clip_value_min", ",", "clip_value_max", ",", "name", "=", "None", ")", ":", "def", "cast_clip", "(", "clip", ")", ":", "\"\"\"\n Cast clipping range argument if needed.\n \"\"\"", "if", "t", ".", "dtype", "in", "(", ...
A wrapper for clip_by_value that casts the clipping range if needed.
[ "A", "wrapper", "for", "clip_by_value", "that", "casts", "the", "clipping", "range", "if", "needed", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L540-L559
train
tensorflow/cleverhans
cleverhans/utils_tf.py
mul
def mul(a, b): """ A wrapper around tf multiplication that does more automatic casting of the input. """ def multiply(a, b): """Multiplication""" return a * b return op_with_scalar_cast(a, b, multiply)
python
def mul(a, b): """ A wrapper around tf multiplication that does more automatic casting of the input. """ def multiply(a, b): """Multiplication""" return a * b return op_with_scalar_cast(a, b, multiply)
[ "def", "mul", "(", "a", ",", "b", ")", ":", "def", "multiply", "(", "a", ",", "b", ")", ":", "\"\"\"Multiplication\"\"\"", "return", "a", "*", "b", "return", "op_with_scalar_cast", "(", "a", ",", "b", ",", "multiply", ")" ]
A wrapper around tf multiplication that does more automatic casting of the input.
[ "A", "wrapper", "around", "tf", "multiplication", "that", "does", "more", "automatic", "casting", "of", "the", "input", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L561-L569
train
tensorflow/cleverhans
cleverhans/utils_tf.py
div
def div(a, b): """ A wrapper around tf division that does more automatic casting of the input. """ def divide(a, b): """Division""" return a / b return op_with_scalar_cast(a, b, divide)
python
def div(a, b): """ A wrapper around tf division that does more automatic casting of the input. """ def divide(a, b): """Division""" return a / b return op_with_scalar_cast(a, b, divide)
[ "def", "div", "(", "a", ",", "b", ")", ":", "def", "divide", "(", "a", ",", "b", ")", ":", "\"\"\"Division\"\"\"", "return", "a", "/", "b", "return", "op_with_scalar_cast", "(", "a", ",", "b", ",", "divide", ")" ]
A wrapper around tf division that does more automatic casting of the input.
[ "A", "wrapper", "around", "tf", "division", "that", "does", "more", "automatic", "casting", "of", "the", "input", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L571-L579
train
tensorflow/cleverhans
cleverhans/utils_tf.py
op_with_scalar_cast
def op_with_scalar_cast(a, b, f): """ Builds the graph to compute f(a, b). If only one of the two arguments is a scalar and the operation would cause a type error without casting, casts the scalar to match the tensor. :param a: a tf-compatible array or scalar :param b: a tf-compatible array or scalar ""...
python
def op_with_scalar_cast(a, b, f): """ Builds the graph to compute f(a, b). If only one of the two arguments is a scalar and the operation would cause a type error without casting, casts the scalar to match the tensor. :param a: a tf-compatible array or scalar :param b: a tf-compatible array or scalar ""...
[ "def", "op_with_scalar_cast", "(", "a", ",", "b", ",", "f", ")", ":", "try", ":", "return", "f", "(", "a", ",", "b", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "def", "is_scalar", "(", "x", ")", ":", "\"\"\"Return True if `...
Builds the graph to compute f(a, b). If only one of the two arguments is a scalar and the operation would cause a type error without casting, casts the scalar to match the tensor. :param a: a tf-compatible array or scalar :param b: a tf-compatible array or scalar
[ "Builds", "the", "graph", "to", "compute", "f", "(", "a", "b", ")", ".", "If", "only", "one", "of", "the", "two", "arguments", "is", "a", "scalar", "and", "the", "operation", "would", "cause", "a", "type", "error", "without", "casting", "casts", "the",...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L581-L618
train
tensorflow/cleverhans
cleverhans/utils_tf.py
jacobian_graph
def jacobian_graph(predictions, x, nb_classes): """ Create the Jacobian graph to be ran later in a TF session :param predictions: the model's symbolic output (linear output, pre-softmax) :param x: the input placeholder :param nb_classes: the number of classes the model has :return: """ # This fun...
python
def jacobian_graph(predictions, x, nb_classes): """ Create the Jacobian graph to be ran later in a TF session :param predictions: the model's symbolic output (linear output, pre-softmax) :param x: the input placeholder :param nb_classes: the number of classes the model has :return: """ # This fun...
[ "def", "jacobian_graph", "(", "predictions", ",", "x", ",", "nb_classes", ")", ":", "# This function will return a list of TF gradients", "list_derivatives", "=", "[", "]", "# Define the TF graph elements to compute our derivatives for each class", "for", "class_ind", "in", "xr...
Create the Jacobian graph to be ran later in a TF session :param predictions: the model's symbolic output (linear output, pre-softmax) :param x: the input placeholder :param nb_classes: the number of classes the model has :return:
[ "Create", "the", "Jacobian", "graph", "to", "be", "ran", "later", "in", "a", "TF", "session", ":", "param", "predictions", ":", "the", "model", "s", "symbolic", "output", "(", "linear", "output", "pre", "-", "softmax", ")", ":", "param", "x", ":", "the...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L647-L665
train
tensorflow/cleverhans
cleverhans/utils_tf.py
jacobian_augmentation
def jacobian_augmentation(sess, x, X_sub_prev, Y_sub, grads, lmbda, aug_batch_size=512, feed=None): """ Augment an adversary's substit...
python
def jacobian_augmentation(sess, x, X_sub_prev, Y_sub, grads, lmbda, aug_batch_size=512, feed=None): """ Augment an adversary's substit...
[ "def", "jacobian_augmentation", "(", "sess", ",", "x", ",", "X_sub_prev", ",", "Y_sub", ",", "grads", ",", "lmbda", ",", "aug_batch_size", "=", "512", ",", "feed", "=", "None", ")", ":", "assert", "len", "(", "x", ".", "get_shape", "(", ")", ")", "==...
Augment an adversary's substitute training set using the Jacobian of a substitute model to generate new synthetic inputs. See https://arxiv.org/abs/1602.02697 for more details. See cleverhans_tutorials/mnist_blackbox.py for example use case :param sess: TF session in which the substitute model is defined :par...
[ "Augment", "an", "adversary", "s", "substitute", "training", "set", "using", "the", "Jacobian", "of", "a", "substitute", "model", "to", "generate", "new", "synthetic", "inputs", ".", "See", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1602", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tf.py#L667-L722
train
tensorflow/cleverhans
cleverhans_tutorials/evaluate_pickled_model.py
evaluate_model
def evaluate_model(filepath, train_start=0, train_end=60000, test_start=0, test_end=10000, batch_size=128, testing=False, num_threads=None): """ Run evaluation on a saved model :param filepath: path to model to evaluate :param train_start: index of first ...
python
def evaluate_model(filepath, train_start=0, train_end=60000, test_start=0, test_end=10000, batch_size=128, testing=False, num_threads=None): """ Run evaluation on a saved model :param filepath: path to model to evaluate :param train_start: index of first ...
[ "def", "evaluate_model", "(", "filepath", ",", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "batch_size", "=", "128", ",", "testing", "=", "False", ",", "num_threads", "=", "Non...
Run evaluation on a saved model :param filepath: path to model to evaluate :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param batch_size: size o...
[ "Run", "evaluation", "on", "a", "saved", "model", ":", "param", "filepath", ":", "path", "to", "model", "to", "evaluate", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of",...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/evaluate_pickled_model.py#L26-L99
train
tensorflow/cleverhans
examples/multigpu_advtrain/runner.py
RunnerMultiGPU.set_input
def set_input(self, X_batch=None): """ Preprocessing the inputs before calling session.run() :param X_batch: A dictionary of inputs to the first sub-graph :return: A tuple, `(fetches, fd)`, with `fetches` being a list of Tensors to be fetches and `fd` the feed dictionary. """ input...
python
def set_input(self, X_batch=None): """ Preprocessing the inputs before calling session.run() :param X_batch: A dictionary of inputs to the first sub-graph :return: A tuple, `(fetches, fd)`, with `fetches` being a list of Tensors to be fetches and `fd` the feed dictionary. """ input...
[ "def", "set_input", "(", "self", ",", "X_batch", "=", "None", ")", ":", "inputs", "=", "self", ".", "inputs", "outputs", "=", "self", ".", "outputs", "# data for first gpu", "fd", "=", "{", "}", "if", "X_batch", "is", "not", "None", ":", "self", ".", ...
Preprocessing the inputs before calling session.run() :param X_batch: A dictionary of inputs to the first sub-graph :return: A tuple, `(fetches, fd)`, with `fetches` being a list of Tensors to be fetches and `fd` the feed dictionary.
[ "Preprocessing", "the", "inputs", "before", "calling", "session", ".", "run", "()" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/runner.py#L66-L106
train
tensorflow/cleverhans
examples/multigpu_advtrain/runner.py
RunnerMultiGPU.proc_fvals
def proc_fvals(self, fvals): """ Postprocess the outputs of the Session.run(). Move the outputs of sub-graphs to next ones and return the output of the last sub-graph. :param fvals: A list of fetched values returned by Session.run() :return: A dictionary of fetched values returned by the last sub-g...
python
def proc_fvals(self, fvals): """ Postprocess the outputs of the Session.run(). Move the outputs of sub-graphs to next ones and return the output of the last sub-graph. :param fvals: A list of fetched values returned by Session.run() :return: A dictionary of fetched values returned by the last sub-g...
[ "def", "proc_fvals", "(", "self", ",", "fvals", ")", ":", "inputs", "=", "self", ".", "inputs", "outputs", "=", "self", ".", "outputs", "# Move data to the next sub-graph for the next step", "cur", "=", "0", "for", "i", "in", "range", "(", "len", "(", "input...
Postprocess the outputs of the Session.run(). Move the outputs of sub-graphs to next ones and return the output of the last sub-graph. :param fvals: A list of fetched values returned by Session.run() :return: A dictionary of fetched values returned by the last sub-graph.
[ "Postprocess", "the", "outputs", "of", "the", "Session", ".", "run", "()", ".", "Move", "the", "outputs", "of", "sub", "-", "graphs", "to", "next", "ones", "and", "return", "the", "output", "of", "the", "last", "sub", "-", "graph", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/runner.py#L108-L139
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase._write_single_batch_images_internal
def _write_single_batch_images_internal(self, batch_id, client_batch): """Helper method to write images from single batch into datastore.""" client = self._datastore_client batch_key = client.key(self._entity_kind_batches, batch_id) for img_id, img in iteritems(self._data[batch_id]['images']): img...
python
def _write_single_batch_images_internal(self, batch_id, client_batch): """Helper method to write images from single batch into datastore.""" client = self._datastore_client batch_key = client.key(self._entity_kind_batches, batch_id) for img_id, img in iteritems(self._data[batch_id]['images']): img...
[ "def", "_write_single_batch_images_internal", "(", "self", ",", "batch_id", ",", "client_batch", ")", ":", "client", "=", "self", ".", "_datastore_client", "batch_key", "=", "client", ".", "key", "(", "self", ".", "_entity_kind_batches", ",", "batch_id", ")", "f...
Helper method to write images from single batch into datastore.
[ "Helper", "method", "to", "write", "images", "from", "single", "batch", "into", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L72-L81
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.write_to_datastore
def write_to_datastore(self): """Writes all image batches to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: for batch_id, batch_data in iteritems(self._data): batch_key = client.key(self._entity_kind_batches, batch_id) batch_entity = ...
python
def write_to_datastore(self): """Writes all image batches to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: for batch_id, batch_data in iteritems(self._data): batch_key = client.key(self._entity_kind_batches, batch_id) batch_entity = ...
[ "def", "write_to_datastore", "(", "self", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "client_batch", ":", "for", "batch_id", ",", "batch_data", "in", "iteritems", "(", "self", ".", "...
Writes all image batches to the datastore.
[ "Writes", "all", "image", "batches", "to", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L83-L94
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.write_single_batch_images_to_datastore
def write_single_batch_images_to_datastore(self, batch_id): """Writes only images from one batch to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: self._write_single_batch_images_internal(batch_id, client_batch)
python
def write_single_batch_images_to_datastore(self, batch_id): """Writes only images from one batch to the datastore.""" client = self._datastore_client with client.no_transact_batch() as client_batch: self._write_single_batch_images_internal(batch_id, client_batch)
[ "def", "write_single_batch_images_to_datastore", "(", "self", ",", "batch_id", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "client_batch", ":", "self", ".", "_write_single_batch_images_internal...
Writes only images from one batch to the datastore.
[ "Writes", "only", "images", "from", "one", "batch", "to", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L96-L100
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.init_from_datastore
def init_from_datastore(self): """Initializes batches by reading from the datastore.""" self._data = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_batches): batch_id = entity.key.flat_path[-1] self._data[batch_id] = dict(entity) self._data[batch_id]['i...
python
def init_from_datastore(self): """Initializes batches by reading from the datastore.""" self._data = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_batches): batch_id = entity.key.flat_path[-1] self._data[batch_id] = dict(entity) self._data[batch_id]['i...
[ "def", "init_from_datastore", "(", "self", ")", ":", "self", ".", "_data", "=", "{", "}", "for", "entity", "in", "self", ".", "_datastore_client", ".", "query_fetch", "(", "kind", "=", "self", ".", "_entity_kind_batches", ")", ":", "batch_id", "=", "entity...
Initializes batches by reading from the datastore.
[ "Initializes", "batches", "by", "reading", "from", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L102-L114
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.add_batch
def add_batch(self, batch_id, batch_properties=None): """Adds batch with give ID and list of properties.""" if batch_properties is None: batch_properties = {} if not isinstance(batch_properties, dict): raise ValueError('batch_properties has to be dict, however it was: ' + ...
python
def add_batch(self, batch_id, batch_properties=None): """Adds batch with give ID and list of properties.""" if batch_properties is None: batch_properties = {} if not isinstance(batch_properties, dict): raise ValueError('batch_properties has to be dict, however it was: ' + ...
[ "def", "add_batch", "(", "self", ",", "batch_id", ",", "batch_properties", "=", "None", ")", ":", "if", "batch_properties", "is", "None", ":", "batch_properties", "=", "{", "}", "if", "not", "isinstance", "(", "batch_properties", ",", "dict", ")", ":", "ra...
Adds batch with give ID and list of properties.
[ "Adds", "batch", "with", "give", "ID", "and", "list", "of", "properties", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L125-L133
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
ImageBatchesBase.add_image
def add_image(self, batch_id, image_id, image_properties=None): """Adds image to given batch.""" if batch_id not in self._data: raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id)) if image_properties is None: image_properties = {} if not isinstance(image_properties, dict): ...
python
def add_image(self, batch_id, image_id, image_properties=None): """Adds image to given batch.""" if batch_id not in self._data: raise KeyError('Batch with ID "{0}" does not exist'.format(batch_id)) if image_properties is None: image_properties = {} if not isinstance(image_properties, dict): ...
[ "def", "add_image", "(", "self", ",", "batch_id", ",", "image_id", ",", "image_properties", "=", "None", ")", ":", "if", "batch_id", "not", "in", "self", ".", "_data", ":", "raise", "KeyError", "(", "'Batch with ID \"{0}\" does not exist'", ".", "format", "(",...
Adds image to given batch.
[ "Adds", "image", "to", "given", "batch", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L135-L144
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
DatasetBatches._read_image_list
def _read_image_list(self, skip_image_ids=None): """Reads list of dataset images from the datastore.""" if skip_image_ids is None: skip_image_ids = [] images = self._storage_client.list_blobs( prefix=os.path.join('dataset', self._dataset_name) + '/') zip_files = [i for i in images if i.end...
python
def _read_image_list(self, skip_image_ids=None): """Reads list of dataset images from the datastore.""" if skip_image_ids is None: skip_image_ids = [] images = self._storage_client.list_blobs( prefix=os.path.join('dataset', self._dataset_name) + '/') zip_files = [i for i in images if i.end...
[ "def", "_read_image_list", "(", "self", ",", "skip_image_ids", "=", "None", ")", ":", "if", "skip_image_ids", "is", "None", ":", "skip_image_ids", "=", "[", "]", "images", "=", "self", ".", "_storage_client", ".", "list_blobs", "(", "prefix", "=", "os", "....
Reads list of dataset images from the datastore.
[ "Reads", "list", "of", "dataset", "images", "from", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L189-L222
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
DatasetBatches.init_from_storage_write_to_datastore
def init_from_storage_write_to_datastore(self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None): """Initializes d...
python
def init_from_storage_write_to_datastore(self, batch_size=100, allowed_epsilon=None, skip_image_ids=None, max_num_images=None): """Initializes d...
[ "def", "init_from_storage_write_to_datastore", "(", "self", ",", "batch_size", "=", "100", ",", "allowed_epsilon", "=", "None", ",", "skip_image_ids", "=", "None", ",", "max_num_images", "=", "None", ")", ":", "if", "allowed_epsilon", "is", "None", ":", "allowed...
Initializes dataset batches from the list of images in the datastore. Args: batch_size: batch size allowed_epsilon: list of allowed epsilon or None to use default skip_image_ids: list of image ids to skip max_num_images: maximum number of images to read
[ "Initializes", "dataset", "batches", "from", "the", "list", "of", "images", "in", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L224-L255
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
AversarialBatches.init_from_dataset_and_submissions_write_to_datastore
def init_from_dataset_and_submissions_write_to_datastore( self, dataset_batches, attack_submission_ids): """Init list of adversarial batches from dataset batches and submissions. Args: dataset_batches: instances of DatasetBatches attack_submission_ids: iterable with IDs of all (targeted and n...
python
def init_from_dataset_and_submissions_write_to_datastore( self, dataset_batches, attack_submission_ids): """Init list of adversarial batches from dataset batches and submissions. Args: dataset_batches: instances of DatasetBatches attack_submission_ids: iterable with IDs of all (targeted and n...
[ "def", "init_from_dataset_and_submissions_write_to_datastore", "(", "self", ",", "dataset_batches", ",", "attack_submission_ids", ")", ":", "batches_x_attacks", "=", "itertools", ".", "product", "(", "dataset_batches", ".", "data", ".", "keys", "(", ")", ",", "attack_...
Init list of adversarial batches from dataset batches and submissions. Args: dataset_batches: instances of DatasetBatches attack_submission_ids: iterable with IDs of all (targeted and nontargeted) attack submissions, could be obtains as CompetitionSubmissions.get_all_attack_ids()
[ "Init", "list", "of", "adversarial", "batches", "from", "dataset", "batches", "and", "submissions", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L272-L289
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py
AversarialBatches.count_generated_adv_examples
def count_generated_adv_examples(self): """Returns total number of all generated adversarial examples.""" result = {} for v in itervalues(self.data): s_id = v['submission_id'] result[s_id] = result.get(s_id, 0) + len(v['images']) return result
python
def count_generated_adv_examples(self): """Returns total number of all generated adversarial examples.""" result = {} for v in itervalues(self.data): s_id = v['submission_id'] result[s_id] = result.get(s_id, 0) + len(v['images']) return result
[ "def", "count_generated_adv_examples", "(", "self", ")", ":", "result", "=", "{", "}", "for", "v", "in", "itervalues", "(", "self", ".", "data", ")", ":", "s_id", "=", "v", "[", "'submission_id'", "]", "result", "[", "s_id", "]", "=", "result", ".", ...
Returns total number of all generated adversarial examples.
[ "Returns", "total", "number", "of", "all", "generated", "adversarial", "examples", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/image_batches.py#L291-L297
train
tensorflow/cleverhans
cleverhans/confidence_report.py
make_confidence_report_bundled
def make_confidence_report_bundled(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, which_set=WHICH_SET, recipe=RECIPE, report_path=REPORT_PATH, ...
python
def make_confidence_report_bundled(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, which_set=WHICH_SET, recipe=RECIPE, report_path=REPORT_PATH, ...
[ "def", "make_confidence_report_bundled", "(", "filepath", ",", "train_start", "=", "TRAIN_START", ",", "train_end", "=", "TRAIN_END", ",", "test_start", "=", "TEST_START", ",", "test_end", "=", "TEST_END", ",", "which_set", "=", "WHICH_SET", ",", "recipe", "=", ...
Load a saved model, gather its predictions, and save a confidence report. :param filepath: path to model to evaluate :param train_start: index of first training set example to use :param train_end: index of last training set example to use :param test_start: index of first test set example to use :param test_...
[ "Load", "a", "saved", "model", "gather", "its", "predictions", "and", "save", "a", "confidence", "report", ".", ":", "param", "filepath", ":", "path", "to", "model", "to", "evaluate", ":", "param", "train_start", ":", "index", "of", "first", "training", "s...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/confidence_report.py#L124-L235
train
tensorflow/cleverhans
cleverhans/confidence_report.py
print_stats
def print_stats(correctness, confidence, name): """ Prints out accuracy, coverage, etc. statistics :param correctness: ndarray One bool per example specifying whether it was correctly classified :param confidence: ndarray The probability associated with each prediction :param name: str The name of...
python
def print_stats(correctness, confidence, name): """ Prints out accuracy, coverage, etc. statistics :param correctness: ndarray One bool per example specifying whether it was correctly classified :param confidence: ndarray The probability associated with each prediction :param name: str The name of...
[ "def", "print_stats", "(", "correctness", ",", "confidence", ",", "name", ")", ":", "accuracy", "=", "correctness", ".", "mean", "(", ")", "wrongness", "=", "1", "-", "correctness", "denom1", "=", "np", ".", "maximum", "(", "1", ",", "wrongness", ".", ...
Prints out accuracy, coverage, etc. statistics :param correctness: ndarray One bool per example specifying whether it was correctly classified :param confidence: ndarray The probability associated with each prediction :param name: str The name of this type of data (e.g. "clean", "MaxConfidence")
[ "Prints", "out", "accuracy", "coverage", "etc", ".", "statistics", ":", "param", "correctness", ":", "ndarray", "One", "bool", "per", "example", "specifying", "whether", "it", "was", "correctly", "classified", ":", "param", "confidence", ":", "ndarray", "The", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/confidence_report.py#L238-L270
train
tensorflow/cleverhans
cleverhans/confidence_report.py
make_confidence_report
def make_confidence_report(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, mc_batch_size=MC_BATCH_SIZE, ...
python
def make_confidence_report(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, mc_batch_size=MC_BATCH_SIZE, ...
[ "def", "make_confidence_report", "(", "filepath", ",", "train_start", "=", "TRAIN_START", ",", "train_end", "=", "TRAIN_END", ",", "test_start", "=", "TEST_START", ",", "test_end", "=", "TEST_END", ",", "batch_size", "=", "BATCH_SIZE", ",", "which_set", "=", "WH...
Load a saved model, gather its predictions, and save a confidence report. This function works by running a single MaxConfidence attack on each example. This provides a reasonable estimate of the true failure rate quickly, so long as the model does not suffer from gradient masking. However, this estimate is mo...
[ "Load", "a", "saved", "model", "gather", "its", "predictions", "and", "save", "a", "confidence", "report", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/confidence_report.py#L273-L404
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_tutorial_keras_tf.py
mnist_tutorial
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, train_dir=TRAIN_DIR, filename=FILENAME, load_model=LOAD_MODEL, testing=False, label_smooth...
python
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, train_dir=TRAIN_DIR, filename=FILENAME, load_model=LOAD_MODEL, testing=False, label_smooth...
[ "def", "mnist_tutorial", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_...
MNIST CleverHans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size ...
[ "MNIST", "CleverHans", "tutorial", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ":", "param", "test_start", ":", "index", "of", "f...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_keras_tf.py#L41-L209
train
tensorflow/cleverhans
cleverhans/attacks/max_confidence.py
MaxConfidence.generate
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments for the base attacker """ assert self.parse_params(**kwargs) labels, _nb_classes = self.get_or_guess_labels(x, kwargs) ...
python
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments for the base attacker """ assert self.parse_params(**kwargs) labels, _nb_classes = self.get_or_guess_labels(x, kwargs) ...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ",", "_nb_classes", "=", "self", ".", "get_or_guess_labels", "(", "x", ",", "kwargs", ")", "ad...
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments for the base attacker
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/max_confidence.py#L41-L53
train
tensorflow/cleverhans
cleverhans/attacks/max_confidence.py
MaxConfidence.attack
def attack(self, x, true_y): """ Runs the untargeted attack. :param x: The input :param true_y: The correct label for `x`. This attack aims to produce misclassification. """ adv_x_cls = [] prob_cls = [] m = tf.shape(x)[0] true_y_idx = tf.argmax(true_y, axis=1) expanded_x = tf.co...
python
def attack(self, x, true_y): """ Runs the untargeted attack. :param x: The input :param true_y: The correct label for `x`. This attack aims to produce misclassification. """ adv_x_cls = [] prob_cls = [] m = tf.shape(x)[0] true_y_idx = tf.argmax(true_y, axis=1) expanded_x = tf.co...
[ "def", "attack", "(", "self", ",", "x", ",", "true_y", ")", ":", "adv_x_cls", "=", "[", "]", "prob_cls", "=", "[", "]", "m", "=", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", "true_y_idx", "=", "tf", ".", "argmax", "(", "true_y", ",", "a...
Runs the untargeted attack. :param x: The input :param true_y: The correct label for `x`. This attack aims to produce misclassification.
[ "Runs", "the", "untargeted", "attack", ".", ":", "param", "x", ":", "The", "input", ":", "param", "true_y", ":", "The", "correct", "label", "for", "x", ".", "This", "attack", "aims", "to", "produce", "misclassification", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/max_confidence.py#L64-L110
train
tensorflow/cleverhans
cleverhans/attacks/max_confidence.py
MaxConfidence.attack_class
def attack_class(self, x, target_y): """ Run the attack on a specific target class. :param x: tf Tensor. The input example. :param target_y: tf Tensor. The attacker's desired target class. Returns: A targeted adversarial example, intended to be classified as the target class. """ adv =...
python
def attack_class(self, x, target_y): """ Run the attack on a specific target class. :param x: tf Tensor. The input example. :param target_y: tf Tensor. The attacker's desired target class. Returns: A targeted adversarial example, intended to be classified as the target class. """ adv =...
[ "def", "attack_class", "(", "self", ",", "x", ",", "target_y", ")", ":", "adv", "=", "self", ".", "base_attacker", ".", "generate", "(", "x", ",", "y_target", "=", "target_y", ",", "*", "*", "self", ".", "params", ")", "return", "adv" ]
Run the attack on a specific target class. :param x: tf Tensor. The input example. :param target_y: tf Tensor. The attacker's desired target class. Returns: A targeted adversarial example, intended to be classified as the target class.
[ "Run", "the", "attack", "on", "a", "specific", "target", "class", ".", ":", "param", "x", ":", "tf", "Tensor", ".", "The", "input", "example", ".", ":", "param", "target_y", ":", "tf", "Tensor", ".", "The", "attacker", "s", "desired", "target", "class"...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/max_confidence.py#L112-L121
train
tensorflow/cleverhans
cleverhans/utils.py
batch_indices
def batch_indices(batch_nb, data_length, batch_size): """ This helper function computes a batch start and end index :param batch_nb: the batch number :param data_length: the total length of the data being parsed by batches :param batch_size: the number of inputs in each batch :return: pair of (start, end) i...
python
def batch_indices(batch_nb, data_length, batch_size): """ This helper function computes a batch start and end index :param batch_nb: the batch number :param data_length: the total length of the data being parsed by batches :param batch_size: the number of inputs in each batch :return: pair of (start, end) i...
[ "def", "batch_indices", "(", "batch_nb", ",", "data_length", ",", "batch_size", ")", ":", "# Batch start and end index", "start", "=", "int", "(", "batch_nb", "*", "batch_size", ")", "end", "=", "int", "(", "(", "batch_nb", "+", "1", ")", "*", "batch_size", ...
This helper function computes a batch start and end index :param batch_nb: the batch number :param data_length: the total length of the data being parsed by batches :param batch_size: the number of inputs in each batch :return: pair of (start, end) indices
[ "This", "helper", "function", "computes", "a", "batch", "start", "and", "end", "index", ":", "param", "batch_nb", ":", "the", "batch", "number", ":", "param", "data_length", ":", "the", "total", "length", "of", "the", "data", "being", "parsed", "by", "batc...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L63-L82
train
tensorflow/cleverhans
cleverhans/utils.py
other_classes
def other_classes(nb_classes, class_ind): """ Returns a list of class indices excluding the class indexed by class_ind :param nb_classes: number of classes in the task :param class_ind: the class index to be omitted :return: list of class indices excluding the class indexed by class_ind """ if class_ind <...
python
def other_classes(nb_classes, class_ind): """ Returns a list of class indices excluding the class indexed by class_ind :param nb_classes: number of classes in the task :param class_ind: the class index to be omitted :return: list of class indices excluding the class indexed by class_ind """ if class_ind <...
[ "def", "other_classes", "(", "nb_classes", ",", "class_ind", ")", ":", "if", "class_ind", "<", "0", "or", "class_ind", ">=", "nb_classes", ":", "error_str", "=", "\"class_ind must be within the range (0, nb_classes - 1)\"", "raise", "ValueError", "(", "error_str", ")"...
Returns a list of class indices excluding the class indexed by class_ind :param nb_classes: number of classes in the task :param class_ind: the class index to be omitted :return: list of class indices excluding the class indexed by class_ind
[ "Returns", "a", "list", "of", "class", "indices", "excluding", "the", "class", "indexed", "by", "class_ind", ":", "param", "nb_classes", ":", "number", "of", "classes", "in", "the", "task", ":", "param", "class_ind", ":", "the", "class", "index", "to", "be...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L85-L99
train
tensorflow/cleverhans
cleverhans/utils.py
to_categorical
def to_categorical(y, nb_classes, num_classes=None): """ Converts a class vector (integers) to binary class matrix. This is adapted from the Keras function with the same name. :param y: class vector to be converted into a matrix (integers from 0 to nb_classes). :param nb_classes: nb_classes: total...
python
def to_categorical(y, nb_classes, num_classes=None): """ Converts a class vector (integers) to binary class matrix. This is adapted from the Keras function with the same name. :param y: class vector to be converted into a matrix (integers from 0 to nb_classes). :param nb_classes: nb_classes: total...
[ "def", "to_categorical", "(", "y", ",", "nb_classes", ",", "num_classes", "=", "None", ")", ":", "if", "num_classes", "is", "not", "None", ":", "if", "nb_classes", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Should not specify both nb_classes and it...
Converts a class vector (integers) to binary class matrix. This is adapted from the Keras function with the same name. :param y: class vector to be converted into a matrix (integers from 0 to nb_classes). :param nb_classes: nb_classes: total number of classes. :param num_classses: depricated version...
[ "Converts", "a", "class", "vector", "(", "integers", ")", "to", "binary", "class", "matrix", ".", "This", "is", "adapted", "from", "the", "Keras", "function", "with", "the", "same", "name", ".", ":", "param", "y", ":", "class", "vector", "to", "be", "c...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L102-L124
train
tensorflow/cleverhans
cleverhans/utils.py
random_targets
def random_targets(gt, nb_classes): """ Take in an array of correct labels and randomly select a different label for each label in the array. This is typically used to randomly select a target class in targeted adversarial examples attacks (i.e., when the search algorithm takes in both a source class and targ...
python
def random_targets(gt, nb_classes): """ Take in an array of correct labels and randomly select a different label for each label in the array. This is typically used to randomly select a target class in targeted adversarial examples attacks (i.e., when the search algorithm takes in both a source class and targ...
[ "def", "random_targets", "(", "gt", ",", "nb_classes", ")", ":", "# If the ground truth labels are encoded as one-hot, convert to labels.", "if", "len", "(", "gt", ".", "shape", ")", "==", "2", ":", "gt", "=", "np", ".", "argmax", "(", "gt", ",", "axis", "=", ...
Take in an array of correct labels and randomly select a different label for each label in the array. This is typically used to randomly select a target class in targeted adversarial examples attacks (i.e., when the search algorithm takes in both a source class and target class to compute the adversarial exampl...
[ "Take", "in", "an", "array", "of", "correct", "labels", "and", "randomly", "select", "a", "different", "label", "for", "each", "label", "in", "the", "array", ".", "This", "is", "typically", "used", "to", "randomly", "select", "a", "target", "class", "in", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L127-L164
train
tensorflow/cleverhans
cleverhans/utils.py
pair_visual
def pair_visual(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`pair_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.pair_visual may be removed on or after " "2019-04-24.") from cleverhans.plot.pyplot_image import pair_visual as new_pair_visual ...
python
def pair_visual(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`pair_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.pair_visual may be removed on or after " "2019-04-24.") from cleverhans.plot.pyplot_image import pair_visual as new_pair_visual ...
[ "def", "pair_visual", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"`pair_visual` has moved to `cleverhans.plot.pyplot_image`. \"", "\"cleverhans.utils.pair_visual may be removed on or after \"", "\"2019-04-24.\"", ")", "from", "cleverh...
Deprecation wrapper
[ "Deprecation", "wrapper" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L167-L173
train
tensorflow/cleverhans
cleverhans/utils.py
grid_visual
def grid_visual(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`grid_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.grid_visual may be removed on or after " "2019-04-24.") from cleverhans.plot.pyplot_image import grid_visual as new_grid_visual ...
python
def grid_visual(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`grid_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.grid_visual may be removed on or after " "2019-04-24.") from cleverhans.plot.pyplot_image import grid_visual as new_grid_visual ...
[ "def", "grid_visual", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"`grid_visual` has moved to `cleverhans.plot.pyplot_image`. \"", "\"cleverhans.utils.grid_visual may be removed on or after \"", "\"2019-04-24.\"", ")", "from", "cleverh...
Deprecation wrapper
[ "Deprecation", "wrapper" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L176-L182
train
tensorflow/cleverhans
cleverhans/utils.py
get_logits_over_interval
def get_logits_over_interval(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`get_logits_over_interval` has moved to " "`cleverhans.plot.pyplot_image`. " "cleverhans.utils.get_logits_over_interval may be removed on " "or after 2019-04-24.") # pylint:disab...
python
def get_logits_over_interval(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`get_logits_over_interval` has moved to " "`cleverhans.plot.pyplot_image`. " "cleverhans.utils.get_logits_over_interval may be removed on " "or after 2019-04-24.") # pylint:disab...
[ "def", "get_logits_over_interval", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"`get_logits_over_interval` has moved to \"", "\"`cleverhans.plot.pyplot_image`. \"", "\"cleverhans.utils.get_logits_over_interval may be removed on \"", "\"or ...
Deprecation wrapper
[ "Deprecation", "wrapper" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L185-L193
train
tensorflow/cleverhans
cleverhans/utils.py
linear_extrapolation_plot
def linear_extrapolation_plot(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`linear_extrapolation_plot` has moved to " "`cleverhans.plot.pyplot_image`. " "cleverhans.utils.linear_extrapolation_plot may be removed on " "or after 2019-04-24.") # pylint:di...
python
def linear_extrapolation_plot(*args, **kwargs): """Deprecation wrapper""" warnings.warn("`linear_extrapolation_plot` has moved to " "`cleverhans.plot.pyplot_image`. " "cleverhans.utils.linear_extrapolation_plot may be removed on " "or after 2019-04-24.") # pylint:di...
[ "def", "linear_extrapolation_plot", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"`linear_extrapolation_plot` has moved to \"", "\"`cleverhans.plot.pyplot_image`. \"", "\"cleverhans.utils.linear_extrapolation_plot may be removed on \"", "\"...
Deprecation wrapper
[ "Deprecation", "wrapper" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L196-L204
train
tensorflow/cleverhans
cleverhans/utils.py
create_logger
def create_logger(name): """ Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter. """ base = logging.getLogger("cleverhans") if len(base.handlers) == 0: ch = logging.StreamHandler() formatter = logging.Formatter('[%(levelna...
python
def create_logger(name): """ Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter. """ base = logging.getLogger("cleverhans") if len(base.handlers) == 0: ch = logging.StreamHandler() formatter = logging.Formatter('[%(levelna...
[ "def", "create_logger", "(", "name", ")", ":", "base", "=", "logging", ".", "getLogger", "(", "\"cleverhans\"", ")", "if", "len", "(", "base", ".", "handlers", ")", "==", "0", ":", "ch", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=",...
Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter.
[ "Create", "a", "logger", "object", "with", "the", "given", "name", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L247-L262
train
tensorflow/cleverhans
cleverhans/utils.py
deterministic_dict
def deterministic_dict(normal_dict): """ Returns a version of `normal_dict` whose iteration order is always the same """ out = OrderedDict() for key in sorted(normal_dict.keys()): out[key] = normal_dict[key] return out
python
def deterministic_dict(normal_dict): """ Returns a version of `normal_dict` whose iteration order is always the same """ out = OrderedDict() for key in sorted(normal_dict.keys()): out[key] = normal_dict[key] return out
[ "def", "deterministic_dict", "(", "normal_dict", ")", ":", "out", "=", "OrderedDict", "(", ")", "for", "key", "in", "sorted", "(", "normal_dict", ".", "keys", "(", ")", ")", ":", "out", "[", "key", "]", "=", "normal_dict", "[", "key", "]", "return", ...
Returns a version of `normal_dict` whose iteration order is always the same
[ "Returns", "a", "version", "of", "normal_dict", "whose", "iteration", "order", "is", "always", "the", "same" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L265-L272
train
tensorflow/cleverhans
cleverhans/utils.py
ordered_union
def ordered_union(l1, l2): """ Return the union of l1 and l2, with a deterministic ordering. (Union of python sets does not necessarily have a consisten iteration order) :param l1: list of items :param l2: list of items :returns: list containing one copy of each item that is in l1 or in l2 """ out = [...
python
def ordered_union(l1, l2): """ Return the union of l1 and l2, with a deterministic ordering. (Union of python sets does not necessarily have a consisten iteration order) :param l1: list of items :param l2: list of items :returns: list containing one copy of each item that is in l1 or in l2 """ out = [...
[ "def", "ordered_union", "(", "l1", ",", "l2", ")", ":", "out", "=", "[", "]", "for", "e", "in", "l1", "+", "l2", ":", "if", "e", "not", "in", "out", ":", "out", ".", "append", "(", "e", ")", "return", "out" ]
Return the union of l1 and l2, with a deterministic ordering. (Union of python sets does not necessarily have a consisten iteration order) :param l1: list of items :param l2: list of items :returns: list containing one copy of each item that is in l1 or in l2
[ "Return", "the", "union", "of", "l1", "and", "l2", "with", "a", "deterministic", "ordering", ".", "(", "Union", "of", "python", "sets", "does", "not", "necessarily", "have", "a", "consisten", "iteration", "order", ")", ":", "param", "l1", ":", "list", "o...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L275-L288
train
tensorflow/cleverhans
cleverhans/utils.py
safe_zip
def safe_zip(*args): """like zip but with these properties: - returns a list, rather than an iterator. This is the old Python2 zip behavior. - a guarantee that all arguments are the same length. (normal zip silently drops entries to make them the same length) """ length = len(args[0]) if not all(len(arg) ...
python
def safe_zip(*args): """like zip but with these properties: - returns a list, rather than an iterator. This is the old Python2 zip behavior. - a guarantee that all arguments are the same length. (normal zip silently drops entries to make them the same length) """ length = len(args[0]) if not all(len(arg) ...
[ "def", "safe_zip", "(", "*", "args", ")", ":", "length", "=", "len", "(", "args", "[", "0", "]", ")", "if", "not", "all", "(", "len", "(", "arg", ")", "==", "length", "for", "arg", "in", "args", ")", ":", "raise", "ValueError", "(", "\"Lengths of...
like zip but with these properties: - returns a list, rather than an iterator. This is the old Python2 zip behavior. - a guarantee that all arguments are the same length. (normal zip silently drops entries to make them the same length)
[ "like", "zip", "but", "with", "these", "properties", ":", "-", "returns", "a", "list", "rather", "than", "an", "iterator", ".", "This", "is", "the", "old", "Python2", "zip", "behavior", ".", "-", "a", "guarantee", "that", "all", "arguments", "are", "the"...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L291-L301
train
tensorflow/cleverhans
cleverhans/utils.py
shell_call
def shell_call(command, **kwargs): """Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is one token of the command. For example "cp a b" becomes ['cp', 'a', 'b'] If any element of the list looks like '${NAME}' then it will be rep...
python
def shell_call(command, **kwargs): """Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is one token of the command. For example "cp a b" becomes ['cp', 'a', 'b'] If any element of the list looks like '${NAME}' then it will be rep...
[ "def", "shell_call", "(", "command", ",", "*", "*", "kwargs", ")", ":", "# Regular expression to find instances of '${NAME}' in a string", "CMD_VARIABLE_RE", "=", "re", ".", "compile", "(", "'^\\\\$\\\\{(\\\\w+)\\\\}$'", ")", "command", "=", "list", "(", "command", ")...
Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is one token of the command. For example "cp a b" becomes ['cp', 'a', 'b'] If any element of the list looks like '${NAME}' then it will be replaced by value from **kwargs with ...
[ "Calls", "shell", "command", "with", "argument", "substitution", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L304-L339
train
tensorflow/cleverhans
cleverhans/utils.py
deep_copy
def deep_copy(numpy_dict): """ Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them. """ out = {} for key in numpy_dict: out[key] = numpy_dict[key].copy() return out
python
def deep_copy(numpy_dict): """ Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them. """ out = {} for key in numpy_dict: out[key] = numpy_dict[key].copy() return out
[ "def", "deep_copy", "(", "numpy_dict", ")", ":", "out", "=", "{", "}", "for", "key", "in", "numpy_dict", ":", "out", "[", "key", "]", "=", "numpy_dict", "[", "key", "]", ".", "copy", "(", ")", "return", "out" ]
Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them.
[ "Returns", "a", "copy", "of", "a", "dictionary", "whose", "values", "are", "numpy", "arrays", ".", "Copies", "their", "values", "rather", "than", "copying", "references", "to", "them", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils.py#L341-L349
train
tensorflow/cleverhans
cleverhans/dataset.py
data_mnist
def data_mnist(datadir=tempfile.gettempdir(), train_start=0, train_end=60000, test_start=0, test_end=10000): """ Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :param train_start: index of first training set example :param train_end: index of last t...
python
def data_mnist(datadir=tempfile.gettempdir(), train_start=0, train_end=60000, test_start=0, test_end=10000): """ Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :param train_start: index of first training set example :param train_end: index of last t...
[ "def", "data_mnist", "(", "datadir", "=", "tempfile", ".", "gettempdir", "(", ")", ",", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ")", ":", "assert", "isinstance", "(", "train_sta...
Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :return...
[ "Load", "and", "preprocess", "MNIST", "dataset", ":", "param", "datadir", ":", "path", "to", "folder", "where", "data", "should", "be", "stored", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/dataset.py#L230-L266
train
tensorflow/cleverhans
cleverhans/dataset.py
data_cifar10
def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000): """ Preprocess CIFAR10 dataset :return: """ # These values are specific to CIFAR10 img_rows = 32 img_cols = 32 nb_classes = 10 # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_...
python
def data_cifar10(train_start=0, train_end=50000, test_start=0, test_end=10000): """ Preprocess CIFAR10 dataset :return: """ # These values are specific to CIFAR10 img_rows = 32 img_cols = 32 nb_classes = 10 # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_...
[ "def", "data_cifar10", "(", "train_start", "=", "0", ",", "train_end", "=", "50000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ")", ":", "# These values are specific to CIFAR10", "img_rows", "=", "32", "img_cols", "=", "32", "nb_classes", "="...
Preprocess CIFAR10 dataset :return:
[ "Preprocess", "CIFAR10", "dataset", ":", "return", ":" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/dataset.py#L269-L307
train
tensorflow/cleverhans
scripts/compute_accuracy.py
print_accuracies
def print_accuracies(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER): """ Load a saved model...
python
def print_accuracies(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER): """ Load a saved model...
[ "def", "print_accuracies", "(", "filepath", ",", "train_start", "=", "TRAIN_START", ",", "train_end", "=", "TRAIN_END", ",", "test_start", "=", "TEST_START", ",", "test_end", "=", "TEST_END", ",", "batch_size", "=", "BATCH_SIZE", ",", "which_set", "=", "WHICH_SE...
Load a saved model and print out its accuracy on different data distributions This function works by running a single attack on each example. This provides a reasonable estimate of the true failure rate quickly, so long as the model does not suffer from gradient masking. However, this estimate is mostly intend...
[ "Load", "a", "saved", "model", "and", "print", "out", "its", "accuracy", "on", "different", "data", "distributions" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/compute_accuracy.py#L53-L98
train
tensorflow/cleverhans
scripts/compute_accuracy.py
impl
def impl(sess, model, dataset, factory, x_data, y_data, base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER, batch_size=BATCH_SIZE): """ The actual implementation of the evaluation. :param sess: tf.Session :param model: cleverhans.model.Model :param dataset: cleverhans.dataset.Dataset :param fact...
python
def impl(sess, model, dataset, factory, x_data, y_data, base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER, batch_size=BATCH_SIZE): """ The actual implementation of the evaluation. :param sess: tf.Session :param model: cleverhans.model.Model :param dataset: cleverhans.dataset.Dataset :param fact...
[ "def", "impl", "(", "sess", ",", "model", ",", "dataset", ",", "factory", ",", "x_data", ",", "y_data", ",", "base_eps_iter", "=", "BASE_EPS_ITER", ",", "nb_iter", "=", "NB_ITER", ",", "batch_size", "=", "BATCH_SIZE", ")", ":", "center", "=", "dataset", ...
The actual implementation of the evaluation. :param sess: tf.Session :param model: cleverhans.model.Model :param dataset: cleverhans.dataset.Dataset :param factory: the dataset factory corresponding to `dataset` :param x_data: numpy array of input examples :param y_data: numpy array of class labels :param...
[ "The", "actual", "implementation", "of", "the", "evaluation", ".", ":", "param", "sess", ":", "tf", ".", "Session", ":", "param", "model", ":", "cleverhans", ".", "model", ".", "Model", ":", "param", "dataset", ":", "cleverhans", ".", "dataset", ".", "Da...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/compute_accuracy.py#L100-L159
train
tensorflow/cleverhans
scripts/compute_accuracy.py
main
def main(argv=None): """ Print accuracies """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print_accuracies(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_set, nb_iter=FLAGS.nb_it...
python
def main(argv=None): """ Print accuracies """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) print_accuracies(filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end, which_set=FLAGS.which_set, nb_iter=FLAGS.nb_it...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "try", ":", "_name_of_script", ",", "filepath", "=", "argv", "except", "ValueError", ":", "raise", "ValueError", "(", "argv", ")", "print_accuracies", "(", "filepath", "=", "filepath", ",", "test_start", "...
Print accuracies
[ "Print", "accuracies" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/compute_accuracy.py#L162-L173
train
tensorflow/cleverhans
cleverhans/future/torch/attacks/fast_gradient_method.py
fast_gradient_method
def fast_gradient_method(model_fn, x, eps, ord, clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False): """ PyTorch implementation of the Fast Gradient Method. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor...
python
def fast_gradient_method(model_fn, x, eps, ord, clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False): """ PyTorch implementation of the Fast Gradient Method. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor...
[ "def", "fast_gradient_method", "(", "model_fn", ",", "x", ",", "eps", ",", "ord", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "sanity_checks", "=", "False", ")", ":", "if", "o...
PyTorch implementation of the Fast Gradient Method. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param ord: Order of the norm (mimics NumPy). Possible values: np...
[ "PyTorch", "implementation", "of", "the", "Fast", "Gradient", "Method", ".", ":", "param", "model_fn", ":", "a", "callable", "that", "takes", "an", "input", "tensor", "and", "returns", "the", "model", "logits", ".", ":", "param", "x", ":", "input", "tensor...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/torch/attacks/fast_gradient_method.py#L8-L73
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py
load_images
def load_images(input_dir, batch_shape): """Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be le...
python
def load_images(input_dir, batch_shape): """Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be le...
[ "def", "load_images", "(", "input_dir", ",", "batch_shape", ")", ":", "images", "=", "np", ".", "zeros", "(", "batch_shape", ")", "filenames", "=", "[", "]", "idx", "=", "0", "batch_size", "=", "batch_shape", "[", "0", "]", "for", "filepath", "in", "tf...
Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be less than batch_size, in this case only fi...
[ "Read", "png", "images", "from", "input", "directory", "in", "batches", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py#L47-L77
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py
save_images
def save_images(images, filenames, output_dir): """Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filenames) images ...
python
def save_images(images, filenames, output_dir): """Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filenames) images ...
[ "def", "save_images", "(", "images", ",", "filenames", ",", "output_dir", ")", ":", "for", "i", ",", "filename", "in", "enumerate", "(", "filenames", ")", ":", "# Images for inception classifier are normalized to be in [-1, 1] interval,", "# so rescale them back to [0, 1]."...
Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filenames) images will be saved. output_dir: directory where to sav...
[ "Saves", "images", "to", "the", "output", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py#L80-L95
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py
main
def main(_): """Run the sample attack""" # Images for inception classifier are normalized to be in [-1, 1] interval, # eps is a difference between pixels so it should be in [0, 2] interval. # Renormalizing epsilon from [0, 255] to [0, 2]. eps = 2.0 * FLAGS.max_epsilon / 255.0 batch_shape = [FLAGS.batch_size...
python
def main(_): """Run the sample attack""" # Images for inception classifier are normalized to be in [-1, 1] interval, # eps is a difference between pixels so it should be in [0, 2] interval. # Renormalizing epsilon from [0, 255] to [0, 2]. eps = 2.0 * FLAGS.max_epsilon / 255.0 batch_shape = [FLAGS.batch_size...
[ "def", "main", "(", "_", ")", ":", "# Images for inception classifier are normalized to be in [-1, 1] interval,", "# eps is a difference between pixels so it should be in [0, 2] interval.", "# Renormalizing epsilon from [0, 255] to [0, 2].", "eps", "=", "2.0", "*", "FLAGS", ".", "max_e...
Run the sample attack
[ "Run", "the", "sample", "attack" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_attacks/fgsm/attack_fgsm.py#L127-L157
train
tensorflow/cleverhans
tutorials/future/torch/cifar10_tutorial.py
ld_cifar10
def ld_cifar10(): """Load training and test data.""" train_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) test_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) train_dataset = torchvision.datasets.CIFAR10(root='/tmp/data', train=True, transform=t...
python
def ld_cifar10(): """Load training and test data.""" train_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) test_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) train_dataset = torchvision.datasets.CIFAR10(root='/tmp/data', train=True, transform=t...
[ "def", "ld_cifar10", "(", ")", ":", "train_transforms", "=", "torchvision", ".", "transforms", ".", "Compose", "(", "[", "torchvision", ".", "transforms", ".", "ToTensor", "(", ")", "]", ")", "test_transforms", "=", "torchvision", ".", "transforms", ".", "Co...
Load training and test data.
[ "Load", "training", "and", "test", "data", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/tutorials/future/torch/cifar10_tutorial.py#L33-L41
train
tensorflow/cleverhans
cleverhans/plot/success_fail.py
plot_report_from_path
def plot_report_from_path(path, success_name=DEFAULT_SUCCESS_NAME, fail_names=DEFAULT_FAIL_NAMES, label=None, is_max_confidence=True, linewidth=LINEWIDTH, plot_upper_bound=True): """ Plots a success-fail curve fr...
python
def plot_report_from_path(path, success_name=DEFAULT_SUCCESS_NAME, fail_names=DEFAULT_FAIL_NAMES, label=None, is_max_confidence=True, linewidth=LINEWIDTH, plot_upper_bound=True): """ Plots a success-fail curve fr...
[ "def", "plot_report_from_path", "(", "path", ",", "success_name", "=", "DEFAULT_SUCCESS_NAME", ",", "fail_names", "=", "DEFAULT_FAIL_NAMES", ",", "label", "=", "None", ",", "is_max_confidence", "=", "True", ",", "linewidth", "=", "LINEWIDTH", ",", "plot_upper_bound"...
Plots a success-fail curve from a confidence report stored on disk, :param path: string filepath for the stored report. (Should be the output of make_confidence_report*.py) :param success_name: The name (confidence report key) of the data that should be used to measure success rate :param fail_names: A li...
[ "Plots", "a", "success", "-", "fail", "curve", "from", "a", "confidence", "report", "stored", "on", "disk", ":", "param", "path", ":", "string", "filepath", "for", "the", "stored", "report", ".", "(", "Should", "be", "the", "output", "of", "make_confidence...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/success_fail.py#L18-L54
train
tensorflow/cleverhans
cleverhans/plot/success_fail.py
plot_report
def plot_report(report, success_name, fail_names, label=None, is_max_confidence=True, linewidth=LINEWIDTH, plot_upper_bound=True): """ Plot a success fail curve from a confidence report :param report: A confidence report (the type of object saved by make_confide...
python
def plot_report(report, success_name, fail_names, label=None, is_max_confidence=True, linewidth=LINEWIDTH, plot_upper_bound=True): """ Plot a success fail curve from a confidence report :param report: A confidence report (the type of object saved by make_confide...
[ "def", "plot_report", "(", "report", ",", "success_name", ",", "fail_names", ",", "label", "=", "None", ",", "is_max_confidence", "=", "True", ",", "linewidth", "=", "LINEWIDTH", ",", "plot_upper_bound", "=", "True", ")", ":", "(", "fail_optimal", ",", "succ...
Plot a success fail curve from a confidence report :param report: A confidence report (the type of object saved by make_confidence_report.py) :param success_name: see plot_report_from_path :param fail_names: see plot_report_from_path :param label: see plot_report_from_path :param is_max_confidence: see pl...
[ "Plot", "a", "success", "fail", "curve", "from", "a", "confidence", "report", ":", "param", "report", ":", "A", "confidence", "report", "(", "the", "type", "of", "object", "saved", "by", "make_confidence_report", ".", "py", ")", ":", "param", "success_name",...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/success_fail.py#L57-L97
train
tensorflow/cleverhans
cleverhans/plot/success_fail.py
make_curve
def make_curve(report, success_name, fail_names): """ Make a success-failure curve. :param report: A confidence report (the type of object saved by make_confidence_report.py) :param success_name: see plot_report_from_path :param fail_names: see plot_report_from_path :returns: fail_optimal: list of f...
python
def make_curve(report, success_name, fail_names): """ Make a success-failure curve. :param report: A confidence report (the type of object saved by make_confidence_report.py) :param success_name: see plot_report_from_path :param fail_names: see plot_report_from_path :returns: fail_optimal: list of f...
[ "def", "make_curve", "(", "report", ",", "success_name", ",", "fail_names", ")", ":", "success_results", "=", "report", "[", "success_name", "]", "fail_name", "=", "None", "# pacify pylint", "found", "=", "False", "for", "fail_name", "in", "fail_names", ":", "...
Make a success-failure curve. :param report: A confidence report (the type of object saved by make_confidence_report.py) :param success_name: see plot_report_from_path :param fail_names: see plot_report_from_path :returns: fail_optimal: list of failure rates on adversarial data for the optimal (t ...
[ "Make", "a", "success", "-", "failure", "curve", ".", ":", "param", "report", ":", "A", "confidence", "report", "(", "the", "type", "of", "object", "saved", "by", "make_confidence_report", ".", "py", ")", ":", "param", "success_name", ":", "see", "plot_rep...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/success_fail.py#L100-L274
train
tensorflow/cleverhans
examples/multigpu_advtrain/trainer.py
TrainManager.model_train
def model_train(self): """ Train a TF graph :param sess: TF session to use when training the graph :param x: input placeholder :param y: output placeholder (for labels) :param predictions: model output predictions :param X_train: numpy array with training inputs :param Y_train: numpy arr...
python
def model_train(self): """ Train a TF graph :param sess: TF session to use when training the graph :param x: input placeholder :param y: output placeholder (for labels) :param predictions: model output predictions :param X_train: numpy array with training inputs :param Y_train: numpy arr...
[ "def", "model_train", "(", "self", ")", ":", "assert", "self", ".", "runner", "is", "not", "None", ",", "(", "\"\"\"Runner is not initialized. TrainerSingleGPU or TrainerMultiGPU\n instantiate a Runner object at initialization time.\"\"\"", ")", "hparams", "=", "self...
Train a TF graph :param sess: TF session to use when training the graph :param x: input placeholder :param y: output placeholder (for labels) :param predictions: model output predictions :param X_train: numpy array with training inputs :param Y_train: numpy array with training outputs :param...
[ "Train", "a", "TF", "graph", ":", "param", "sess", ":", "TF", "session", "to", "use", "when", "training", "the", "graph", ":", "param", "x", ":", "input", "placeholder", ":", "param", "y", ":", "output", "placeholder", "(", "for", "labels", ")", ":", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/trainer.py#L191-L274
train
tensorflow/cleverhans
examples/multigpu_advtrain/trainer.py
TrainerMultiGPU.clone_g0_inputs_on_ngpus
def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs): """ Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dic...
python
def clone_g0_inputs_on_ngpus(self, inputs, outputs, g0_inputs): """ Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dic...
[ "def", "clone_g0_inputs_on_ngpus", "(", "self", ",", "inputs", ",", "outputs", ",", "g0_inputs", ")", ":", "assert", "len", "(", "inputs", ")", "==", "len", "(", "outputs", ")", ",", "(", "'Inputs and outputs should have the same number of elements.'", ")", "input...
Clone variables unused by the attack on all GPUs. Specifically, the ground-truth label, y, has to be preserved until the training step. :param inputs: A list of dictionaries as the inputs to each step. :param outputs: A list of dictionaries as the outputs of each step. :param g0_inputs: Initial variabl...
[ "Clone", "variables", "unused", "by", "the", "attack", "on", "all", "GPUs", ".", "Specifically", "the", "ground", "-", "truth", "label", "y", "has", "to", "be", "preserved", "until", "the", "training", "step", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/trainer.py#L313-L341
train
tensorflow/cleverhans
cleverhans/attacks/lbfgs.py
LBFGS.generate
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: (required) A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ ...
python
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: (required) A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ ...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "sess", "is", "not", "None", ",", "'Cannot use `generate` when no `sess` was provided'", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "if", "s...
Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: (required) A tensor with the inputs. :param kwargs: See `parse_params`
[ "Return", "a", "tensor", "that", "constructs", "adversarial", "examples", "for", "the", "given", "input", ".", "Generate", "uses", "tf", ".", "py_func", "in", "order", "to", "operate", "over", "tensors", ".", ":", "param", "x", ":", "(", "required", ")", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/lbfgs.py#L41-L74
train
tensorflow/cleverhans
cleverhans/attacks/lbfgs.py
LBFGS.parse_params
def parse_params(self, y_target=None, batch_size=1, binary_search_steps=5, max_iterations=1000, initial_const=1e-2, clip_min=0, clip_max=1): """ :param y_target: (optional) A tens...
python
def parse_params(self, y_target=None, batch_size=1, binary_search_steps=5, max_iterations=1000, initial_const=1e-2, clip_min=0, clip_max=1): """ :param y_target: (optional) A tens...
[ "def", "parse_params", "(", "self", ",", "y_target", "=", "None", ",", "batch_size", "=", "1", ",", "binary_search_steps", "=", "5", ",", "max_iterations", "=", "1000", ",", "initial_const", "=", "1e-2", ",", "clip_min", "=", "0", ",", "clip_max", "=", "...
:param y_target: (optional) A tensor with the one-hot target labels. :param batch_size: The number of inputs to include in a batch and process simultaneously. :param binary_search_steps: The number of times we perform binary search to find the optimal trade...
[ ":", "param", "y_target", ":", "(", "optional", ")", "A", "tensor", "with", "the", "one", "-", "hot", "target", "labels", ".", ":", "param", "batch_size", ":", "The", "number", "of", "inputs", "to", "include", "in", "a", "batch", "and", "process", "sim...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/lbfgs.py#L76-L105
train
tensorflow/cleverhans
cleverhans/attacks/lbfgs.py
LBFGS_impl.attack
def attack(self, x_val, targets): """ Perform the attack on the given instance for the given targets. """ def lbfgs_objective(adv_x, self, targets, oimgs, CONST): """ returns the function value and the gradient for fmin_l_bfgs_b """ loss = self.sess.run( self.loss, feed_...
python
def attack(self, x_val, targets): """ Perform the attack on the given instance for the given targets. """ def lbfgs_objective(adv_x, self, targets, oimgs, CONST): """ returns the function value and the gradient for fmin_l_bfgs_b """ loss = self.sess.run( self.loss, feed_...
[ "def", "attack", "(", "self", ",", "x_val", ",", "targets", ")", ":", "def", "lbfgs_objective", "(", "adv_x", ",", "self", ",", "targets", ",", "oimgs", ",", "CONST", ")", ":", "\"\"\" returns the function value and the gradient for fmin_l_bfgs_b \"\"\"", "loss", ...
Perform the attack on the given instance for the given targets.
[ "Perform", "the", "attack", "on", "the", "given", "instance", "for", "the", "given", "targets", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/lbfgs.py#L166-L281
train
tensorflow/cleverhans
examples/multigpu_advtrain/model.py
MLPnGPU.set_device
def set_device(self, device_name): """ Set the device before the next fprop to create a new graph on the specified device. """ device_name = unify_device_name(device_name) self.device_name = device_name for layer in self.layers: layer.device_name = device_name
python
def set_device(self, device_name): """ Set the device before the next fprop to create a new graph on the specified device. """ device_name = unify_device_name(device_name) self.device_name = device_name for layer in self.layers: layer.device_name = device_name
[ "def", "set_device", "(", "self", ",", "device_name", ")", ":", "device_name", "=", "unify_device_name", "(", "device_name", ")", "self", ".", "device_name", "=", "device_name", "for", "layer", "in", "self", ".", "layers", ":", "layer", ".", "device_name", "...
Set the device before the next fprop to create a new graph on the specified device.
[ "Set", "the", "device", "before", "the", "next", "fprop", "to", "create", "a", "new", "graph", "on", "the", "specified", "device", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L206-L214
train
tensorflow/cleverhans
examples/multigpu_advtrain/model.py
MLPnGPU.create_sync_ops
def create_sync_ops(self, host_device): """ Return a list of assignment operations that syncs the parameters of all model copies with the one on host_device. :param host_device: (required str) the name of the device with latest parameters """ host_device = unify_device_na...
python
def create_sync_ops(self, host_device): """ Return a list of assignment operations that syncs the parameters of all model copies with the one on host_device. :param host_device: (required str) the name of the device with latest parameters """ host_device = unify_device_na...
[ "def", "create_sync_ops", "(", "self", ",", "host_device", ")", ":", "host_device", "=", "unify_device_name", "(", "host_device", ")", "sync_ops", "=", "[", "]", "for", "layer", "in", "self", ".", "layers", ":", "if", "isinstance", "(", "layer", ",", "Laye...
Return a list of assignment operations that syncs the parameters of all model copies with the one on host_device. :param host_device: (required str) the name of the device with latest parameters
[ "Return", "a", "list", "of", "assignment", "operations", "that", "syncs", "the", "parameters", "of", "all", "model", "copies", "with", "the", "one", "on", "host_device", ".", ":", "param", "host_device", ":", "(", "required", "str", ")", "the", "name", "of...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L216-L228
train
tensorflow/cleverhans
examples/multigpu_advtrain/model.py
LayernGPU.get_variable
def get_variable(self, name, initializer): """ Create and initialize a variable using a numpy array and set trainable. :param name: (required str) name of the variable :param initializer: a numpy array or a tensor """ v = tf.get_variable(name, shape=initializer.shape, ini...
python
def get_variable(self, name, initializer): """ Create and initialize a variable using a numpy array and set trainable. :param name: (required str) name of the variable :param initializer: a numpy array or a tensor """ v = tf.get_variable(name, shape=initializer.shape, ini...
[ "def", "get_variable", "(", "self", ",", "name", ",", "initializer", ")", ":", "v", "=", "tf", ".", "get_variable", "(", "name", ",", "shape", "=", "initializer", ".", "shape", ",", "initializer", "=", "(", "lambda", "shape", ",", "dtype", ",", "partit...
Create and initialize a variable using a numpy array and set trainable. :param name: (required str) name of the variable :param initializer: a numpy array or a tensor
[ "Create", "and", "initialize", "a", "variable", "using", "a", "numpy", "array", "and", "set", "trainable", ".", ":", "param", "name", ":", "(", "required", "str", ")", "name", "of", "the", "variable", ":", "param", "initializer", ":", "a", "numpy", "arra...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L254-L264
train
tensorflow/cleverhans
examples/multigpu_advtrain/model.py
LayernGPU.set_input_shape_ngpu
def set_input_shape_ngpu(self, new_input_shape): """ Create and initialize layer parameters on the device previously set in self.device_name. :param new_input_shape: a list or tuple for the shape of the input. """ assert self.device_name, "Device name has not been set." device_name = self....
python
def set_input_shape_ngpu(self, new_input_shape): """ Create and initialize layer parameters on the device previously set in self.device_name. :param new_input_shape: a list or tuple for the shape of the input. """ assert self.device_name, "Device name has not been set." device_name = self....
[ "def", "set_input_shape_ngpu", "(", "self", ",", "new_input_shape", ")", ":", "assert", "self", ".", "device_name", ",", "\"Device name has not been set.\"", "device_name", "=", "self", ".", "device_name", "if", "self", ".", "input_shape", "is", "None", ":", "# Fi...
Create and initialize layer parameters on the device previously set in self.device_name. :param new_input_shape: a list or tuple for the shape of the input.
[ "Create", "and", "initialize", "layer", "parameters", "on", "the", "device", "previously", "set", "in", "self", ".", "device_name", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L266-L297
train
tensorflow/cleverhans
examples/multigpu_advtrain/model.py
LayernGPU.create_sync_ops
def create_sync_ops(self, host_device): """Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the `host_device'. """ sync_ops = [] host_params = self.params_device[host_device] for device, params in (self.params_device).iteritems(): ...
python
def create_sync_ops(self, host_device): """Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the `host_device'. """ sync_ops = [] host_params = self.params_device[host_device] for device, params in (self.params_device).iteritems(): ...
[ "def", "create_sync_ops", "(", "self", ",", "host_device", ")", ":", "sync_ops", "=", "[", "]", "host_params", "=", "self", ".", "params_device", "[", "host_device", "]", "for", "device", ",", "params", "in", "(", "self", ".", "params_device", ")", ".", ...
Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the `host_device'.
[ "Create", "an", "assignment", "operation", "for", "each", "weight", "on", "all", "devices", ".", "The", "weight", "is", "assigned", "the", "value", "of", "the", "copy", "on", "the", "host_device", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/multigpu_advtrain/model.py#L299-L311
train
tensorflow/cleverhans
cleverhans/attacks/virtual_adversarial_method.py
vatm
def vatm(model, x, logits, eps, num_iterations=1, xi=1e-6, clip_min=None, clip_max=None, scope=None): """ Tensorflow implementation of the perturbation method used for virtual adversarial training: https://arxiv.org/abs/1507.00677 :param mo...
python
def vatm(model, x, logits, eps, num_iterations=1, xi=1e-6, clip_min=None, clip_max=None, scope=None): """ Tensorflow implementation of the perturbation method used for virtual adversarial training: https://arxiv.org/abs/1507.00677 :param mo...
[ "def", "vatm", "(", "model", ",", "x", ",", "logits", ",", "eps", ",", "num_iterations", "=", "1", ",", "xi", "=", "1e-6", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_s...
Tensorflow implementation of the perturbation method used for virtual adversarial training: https://arxiv.org/abs/1507.00677 :param model: the model which returns the network unnormalized logits :param x: the input placeholder :param logits: the model's unnormalized output tensor (the input to ...
[ "Tensorflow", "implementation", "of", "the", "perturbation", "method", "used", "for", "virtual", "adversarial", "training", ":", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1507", ".", "00677", ":", "param", "model", ":", "the", "model", "wh...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/virtual_adversarial_method.py#L107-L145
train
tensorflow/cleverhans
cleverhans/attacks/virtual_adversarial_method.py
VirtualAdversarialMethod.generate
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) return vatm( self.model,...
python
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) return vatm( self.model,...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "return", "vatm", "(", "self", ".", "model", ",", "x", ",", "...
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/virtual_adversarial_method.py#L43-L61
train
tensorflow/cleverhans
cleverhans/attacks/virtual_adversarial_method.py
VirtualAdversarialMethod.parse_params
def parse_params(self, eps=2.0, nb_iter=None, xi=1e-6, clip_min=None, clip_max=None, num_iterations=None, **kwargs): """ Take in a dictionary of parameters and applies attack-spec...
python
def parse_params(self, eps=2.0, nb_iter=None, xi=1e-6, clip_min=None, clip_max=None, num_iterations=None, **kwargs): """ Take in a dictionary of parameters and applies attack-spec...
[ "def", "parse_params", "(", "self", ",", "eps", "=", "2.0", ",", "nb_iter", "=", "None", ",", "xi", "=", "1e-6", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "num_iterations", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# S...
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. Attack-specific parameters: :param eps: (optional float )the epsilon (input variation parameter) :param nb_iter: (optional) the number of iterations Defaults to 1 if not specified :param x...
[ "Take", "in", "a", "dictionary", "of", "parameters", "and", "applies", "attack", "-", "specific", "checks", "before", "saving", "them", "as", "attributes", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/virtual_adversarial_method.py#L63-L104
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
iterate_with_exp_backoff
def iterate_with_exp_backoff(base_iter, max_num_tries=6, max_backoff=300.0, start_backoff=4.0, backoff_multiplier=2.0, frac_random_backoff=0.25): """Iterate with exponential...
python
def iterate_with_exp_backoff(base_iter, max_num_tries=6, max_backoff=300.0, start_backoff=4.0, backoff_multiplier=2.0, frac_random_backoff=0.25): """Iterate with exponential...
[ "def", "iterate_with_exp_backoff", "(", "base_iter", ",", "max_num_tries", "=", "6", ",", "max_backoff", "=", "300.0", ",", "start_backoff", "=", "4.0", ",", "backoff_multiplier", "=", "2.0", ",", "frac_random_backoff", "=", "0.25", ")", ":", "try_number", "=", ...
Iterate with exponential backoff on failures. Useful to wrap results of datastore Query.fetch to avoid 429 error. Args: base_iter: basic iterator of generator object max_num_tries: maximum number of tries for each request max_backoff: maximum backoff, in seconds start_backoff: initial value of bac...
[ "Iterate", "with", "exponential", "backoff", "on", "failures", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L167-L209
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
CompetitionStorageClient.list_blobs
def list_blobs(self, prefix=''): """Lists names of all blobs by their prefix.""" return [b.name for b in self.bucket.list_blobs(prefix=prefix)]
python
def list_blobs(self, prefix=''): """Lists names of all blobs by their prefix.""" return [b.name for b in self.bucket.list_blobs(prefix=prefix)]
[ "def", "list_blobs", "(", "self", ",", "prefix", "=", "''", ")", ":", "return", "[", "b", ".", "name", "for", "b", "in", "self", ".", "bucket", ".", "list_blobs", "(", "prefix", "=", "prefix", ")", "]" ]
Lists names of all blobs by their prefix.
[ "Lists", "names", "of", "all", "blobs", "by", "their", "prefix", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L43-L45
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
NoTransactionBatch.begin
def begin(self): """Begins a batch.""" if self._cur_batch: raise ValueError('Previous batch is not committed.') self._cur_batch = self._client.batch() self._cur_batch.begin() self._num_mutations = 0
python
def begin(self): """Begins a batch.""" if self._cur_batch: raise ValueError('Previous batch is not committed.') self._cur_batch = self._client.batch() self._cur_batch.begin() self._num_mutations = 0
[ "def", "begin", "(", "self", ")", ":", "if", "self", ".", "_cur_batch", ":", "raise", "ValueError", "(", "'Previous batch is not committed.'", ")", "self", ".", "_cur_batch", "=", "self", ".", "_client", ".", "batch", "(", ")", "self", ".", "_cur_batch", "...
Begins a batch.
[ "Begins", "a", "batch", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L93-L99
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
NoTransactionBatch.rollback
def rollback(self): """Rolls back pending mutations. Keep in mind that NoTransactionBatch splits all mutations into smaller batches and commit them as soon as mutation buffer reaches maximum length. That's why rollback method will only roll back pending mutations from the buffer, but won't be able ...
python
def rollback(self): """Rolls back pending mutations. Keep in mind that NoTransactionBatch splits all mutations into smaller batches and commit them as soon as mutation buffer reaches maximum length. That's why rollback method will only roll back pending mutations from the buffer, but won't be able ...
[ "def", "rollback", "(", "self", ")", ":", "try", ":", "if", "self", ".", "_cur_batch", ":", "self", ".", "_cur_batch", ".", "rollback", "(", ")", "except", "ValueError", ":", "# ignore \"Batch must be in progress to rollback\" error", "pass", "self", ".", "_cur_...
Rolls back pending mutations. Keep in mind that NoTransactionBatch splits all mutations into smaller batches and commit them as soon as mutation buffer reaches maximum length. That's why rollback method will only roll back pending mutations from the buffer, but won't be able to rollback already committ...
[ "Rolls", "back", "pending", "mutations", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L107-L122
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
NoTransactionBatch.put
def put(self, entity): """Adds mutation of the entity to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: entity: entity which should be put into the datastore """ self._cur_batch.put(entity) ...
python
def put(self, entity): """Adds mutation of the entity to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: entity: entity which should be put into the datastore """ self._cur_batch.put(entity) ...
[ "def", "put", "(", "self", ",", "entity", ")", ":", "self", ".", "_cur_batch", ".", "put", "(", "entity", ")", "self", ".", "_num_mutations", "+=", "1", "if", "self", ".", "_num_mutations", ">=", "MAX_MUTATIONS_IN_BATCH", ":", "self", ".", "commit", "(",...
Adds mutation of the entity to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: entity: entity which should be put into the datastore
[ "Adds", "mutation", "of", "the", "entity", "to", "the", "mutation", "buffer", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L124-L137
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
NoTransactionBatch.delete
def delete(self, key): """Adds deletion of the entity with given key to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: key: key of the entity which should be deleted """ self._cur_batch.delet...
python
def delete(self, key): """Adds deletion of the entity with given key to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: key: key of the entity which should be deleted """ self._cur_batch.delet...
[ "def", "delete", "(", "self", ",", "key", ")", ":", "self", ".", "_cur_batch", ".", "delete", "(", "key", ")", "self", ".", "_num_mutations", "+=", "1", "if", "self", ".", "_num_mutations", ">=", "MAX_MUTATIONS_IN_BATCH", ":", "self", ".", "commit", "(",...
Adds deletion of the entity with given key to the mutation buffer. If mutation buffer reaches its capacity then this method commit all pending mutations from the buffer and emties it. Args: key: key of the entity which should be deleted
[ "Adds", "deletion", "of", "the", "entity", "with", "given", "key", "to", "the", "mutation", "buffer", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L139-L152
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py
CompetitionDatastoreClient.get
def get(self, key, transaction=None): """Retrieves an entity given its key.""" return self._client.get(key, transaction=transaction)
python
def get(self, key, transaction=None): """Retrieves an entity given its key.""" return self._client.get(key, transaction=transaction)
[ "def", "get", "(", "self", ",", "key", ",", "transaction", "=", "None", ")", ":", "return", "self", ".", "_client", ".", "get", "(", "key", ",", "transaction", "=", "transaction", ")" ]
Retrieves an entity given its key.
[ "Retrieves", "an", "entity", "given", "its", "key", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/cloud_client.py#L239-L241
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_tutorial_cw.py
mnist_tutorial_cw
def mnist_tutorial_cw(train_start=0, train_end=60000, test_start=0, test_end=10000, viz_enabled=VIZ_ENABLED, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, source_samples=SOURCE_SAMPLES, learning_rate=LEARNING_RATE, ...
python
def mnist_tutorial_cw(train_start=0, train_end=60000, test_start=0, test_end=10000, viz_enabled=VIZ_ENABLED, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, source_samples=SOURCE_SAMPLES, learning_rate=LEARNING_RATE, ...
[ "def", "mnist_tutorial_cw", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "viz_enabled", "=", "VIZ_ENABLED", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_S...
MNIST tutorial for Carlini and Wagner's attack :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param viz_enabled: (boolean) activate plots of adversa...
[ "MNIST", "tutorial", "for", "Carlini", "and", "Wagner", "s", "attack", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ":", "param", ...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_cw.py#L41-L235
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_tutorial_tfe.py
attack_selection
def attack_selection(attack_string): """ Selects the Attack Class using string input. :param attack_string: adversarial attack name in string format :return: attack class defined in cleverhans.attacks_eager """ # List of Implemented attacks attacks_list = AVAILABLE_ATTACKS.keys() # Checking for reque...
python
def attack_selection(attack_string): """ Selects the Attack Class using string input. :param attack_string: adversarial attack name in string format :return: attack class defined in cleverhans.attacks_eager """ # List of Implemented attacks attacks_list = AVAILABLE_ATTACKS.keys() # Checking for reque...
[ "def", "attack_selection", "(", "attack_string", ")", ":", "# List of Implemented attacks", "attacks_list", "=", "AVAILABLE_ATTACKS", ".", "keys", "(", ")", "# Checking for requested attack in list of available attacks.", "if", "attack_string", "is", "None", ":", "raise", ...
Selects the Attack Class using string input. :param attack_string: adversarial attack name in string format :return: attack class defined in cleverhans.attacks_eager
[ "Selects", "the", "Attack", "Class", "using", "string", "input", ".", ":", "param", "attack_string", ":", "adversarial", "attack", "name", "in", "string", "format", ":", "return", ":", "attack", "class", "defined", "in", "cleverhans", ".", "attacks_eager" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_tfe.py#L54-L73
train
tensorflow/cleverhans
cleverhans_tutorials/mnist_tutorial_tfe.py
mnist_tutorial
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, clean_train=True, testing=False, backprop_through_attack=False, ...
python
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, clean_train=True, testing=False, backprop_through_attack=False, ...
[ "def", "mnist_tutorial", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_...
MNIST cleverhans tutorial :param train_start: index of first training set example. :param train_end: index of last training set example. :param test_start: index of first test set example. :param test_end: index of last test set example. :param nb_epochs: number of epochs to train model. :param batch_size: ...
[ "MNIST", "cleverhans", "tutorial", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ".", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ".", ":", "param", "test_start", ":", "index"...
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_tfe.py#L76-L219
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
sudo_remove_dirtree
def sudo_remove_dirtree(dir_name): """Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root. """ try: subproce...
python
def sudo_remove_dirtree(dir_name): """Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root. """ try: subproce...
[ "def", "sudo_remove_dirtree", "(", "dir_name", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "[", "'sudo'", ",", "'rm'", ",", "'-rf'", ",", "dir_name", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "raise", "W...
Removes directory tree as a superuser. Args: dir_name: name of the directory to remove. This function is necessary to cleanup directories created from inside a Docker, since they usually written as a root, thus have to be removed as a root.
[ "Removes", "directory", "tree", "as", "a", "superuser", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L116-L129
train
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/worker.py
main
def main(args): """Main function which runs worker.""" title = '## Starting evaluation of round {0} ##'.format(args.round_name) logging.info('\n' + '#' * len(title) + '\n' + '#' * len(title) + '\n' + '##' + ' ' * (len(title)-2) + '##' + '\n' + title + '\...
python
def main(args): """Main function which runs worker.""" title = '## Starting evaluation of round {0} ##'.format(args.round_name) logging.info('\n' + '#' * len(title) + '\n' + '#' * len(title) + '\n' + '##' + ' ' * (len(title)-2) + '##' + '\n' + title + '\...
[ "def", "main", "(", "args", ")", ":", "title", "=", "'## Starting evaluation of round {0} ##'", ".", "format", "(", "args", ".", "round_name", ")", "logging", ".", "info", "(", "'\\n'", "+", "'#'", "*", "len", "(", "title", ")", "+", "'\\n'", "+", "'#'",...
Main function which runs worker.
[ "Main", "function", "which", "runs", "worker", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/worker.py#L900-L929
train