How to use current_scope method in Slash

Best Python code snippet using slash

arg_scope.py

Source:arg_scope.py Github

copy

Full Screen

1# Copyright 2016 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Contains the arg_scope used for scoping layers arguments.16 Allows one to define models much more compactly by eliminating boilerplate17 code. This is accomplished through the use of argument scoping (arg_scope).18 Example of how to use tf.contrib.framework.arg_scope:19 ```20 from third_party.tensorflow.contrib.layers.python import layers21 arg_scope = tf.contrib.framework.arg_scope22 with arg_scope([layers.conv2d], padding='SAME',23 initializer=layers.variance_scaling_initializer(),24 regularizer=layers.l2_regularizer(0.05)):25 net = layers.conv2d(inputs, 64, [11, 11], 4, padding='VALID', scope='conv1')26 net = layers.conv2d(net, 256, [5, 5], scope='conv2')27 ```28 The first call to conv2d will behave as follows:29 layers.conv2d(inputs, 64, [11, 11], 4, padding='VALID',30 initializer=layers.variance_scaling_initializer(),31 regularizer=layers.l2_regularizer(0.05), scope='conv1')32 The second call to conv2d will also use the arg_scope's default for padding:33 layers.conv2d(inputs, 256, [5, 5], padding='SAME',34 initializer=layers.variance_scaling_initializer(),35 regularizer=layers.l2_regularizer(0.05), scope='conv2')36 Example of how to reuse an arg_scope:37 ```38 with arg_scope([layers.conv2d], padding='SAME',39 initializer=layers.variance_scaling_initializer(),40 regularizer=layers.l2_regularizer(0.05)) as sc:41 net = layers.conv2d(net, 256, [5, 5], scope='conv1')42 ....43 with arg_scope(sc):44 net = layers.conv2d(net, 256, [5, 5], scope='conv2')45 ```46 Example of how to use tf.contrib.framework.add_arg_scope to enable your47 function to be called within an arg_scope later:48 @tf.contrib.framework.add_arg_scope49 def conv2d(*args, **kwargs)50"""51from __future__ import absolute_import52from __future__ import division53from __future__ import print_function54from tensorflow.python.util import tf_contextlib55from tensorflow.python.util import tf_decorator56__all__ = [57 'arg_scope', 'add_arg_scope', 'current_arg_scope', 'has_arg_scope',58 'arg_scoped_arguments', 'arg_scope_func_key'59]60_ARGSTACK = [{}]61_DECORATED_OPS = {}62def _get_arg_stack():63 if _ARGSTACK:64 return _ARGSTACK65 else:66 _ARGSTACK.append({})67 return _ARGSTACK68def current_arg_scope():69 stack = _get_arg_stack()70 return stack[-1]71def arg_scope_func_key(op):72 return getattr(op, '_key_op', str(op))73def _name_op(op):74 return (op.__module__, op.__name__)75def _kwarg_names(func):76 kwargs_length = len(func.__defaults__) if func.__defaults__ else 077 return func.__code__.co_varnames[-kwargs_length:func.__code__.co_argcount]78def _add_op(op):79 key_op = arg_scope_func_key(op)80 _DECORATED_OPS[key_op] = _kwarg_names(op)81@tf_contextlib.contextmanager82def arg_scope(list_ops_or_scope, **kwargs):83 """Stores the default arguments for the given set of list_ops.84 For usage, please see examples at top of the file.85 Args:86 list_ops_or_scope: List or tuple of operations to set argument scope for or87 a dictionary containing the current scope. When list_ops_or_scope is a88 dict, kwargs must be empty. When list_ops_or_scope is a list or tuple,89 then every op in it need to be decorated with @add_arg_scope to work.90 **kwargs: keyword=value that will define the defaults for each op in91 list_ops. All the ops need to accept the given set of arguments.92 Yields:93 the current_scope, which is a dictionary of {op: {arg: value}}94 Raises:95 TypeError: if list_ops is not a list or a tuple.96 ValueError: if any op in list_ops has not be decorated with @add_arg_scope.97 """98 if isinstance(list_ops_or_scope, dict):99 # Assumes that list_ops_or_scope is a scope that is being reused.100 if kwargs:101 raise ValueError('When attempting to re-use a scope by suppling a'102 'dictionary, kwargs must be empty.')103 current_scope = list_ops_or_scope.copy()104 try:105 _get_arg_stack().append(current_scope)106 yield current_scope107 finally:108 _get_arg_stack().pop()109 else:110 # Assumes that list_ops_or_scope is a list/tuple of ops with kwargs.111 if not isinstance(list_ops_or_scope, (list, tuple)):112 raise TypeError('list_ops_or_scope must either be a list/tuple or reused '113 'scope (i.e. dict)')114 try:115 current_scope = current_arg_scope().copy()116 for op in list_ops_or_scope:117 key = arg_scope_func_key(op)118 if not has_arg_scope(op):119 raise ValueError('%s is not decorated with @add_arg_scope',120 _name_op(op))121 if key in current_scope:122 current_kwargs = current_scope[key].copy()123 current_kwargs.update(kwargs)124 current_scope[key] = current_kwargs125 else:126 current_scope[key] = kwargs.copy()127 _get_arg_stack().append(current_scope)128 yield current_scope129 finally:130 _get_arg_stack().pop()131def add_arg_scope(func):132 """Decorates a function with args so it can be used within an arg_scope.133 Args:134 func: function to decorate.135 Returns:136 A tuple with the decorated function func_with_args().137 """138 def func_with_args(*args, **kwargs):139 current_scope = current_arg_scope()140 current_args = kwargs141 key_func = arg_scope_func_key(func)142 if key_func in current_scope:143 current_args = current_scope[key_func].copy()144 current_args.update(kwargs)145 return func(*args, **current_args)146 _add_op(func)147 setattr(func_with_args, '_key_op', arg_scope_func_key(func))148 return tf_decorator.make_decorator(func, func_with_args)149def has_arg_scope(func):150 """Checks whether a func has been decorated with @add_arg_scope or not.151 Args:152 func: function to check.153 Returns:154 a boolean.155 """156 return arg_scope_func_key(func) in _DECORATED_OPS157def arg_scoped_arguments(func):158 """Returns the list kwargs that arg_scope can set for a func.159 Args:160 func: function which has been decorated with @add_arg_scope.161 Returns:162 a list of kwargs names.163 """164 assert has_arg_scope(func)...

Full Screen

Full Screen

scopes.py

Source:scopes.py Github

copy

Full Screen

1# Copyright 2016 Google Inc. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Contains the new arg_scope used for TF-Slim ops.16 Allows one to define models much more compactly by eliminating boilerplate17 code. This is accomplished through the use of argument scoping (arg_scope).18 Example of how to use scopes.arg_scope:19 with scopes.arg_scope(ops.conv2d, padding='SAME',20 stddev=0.01, weight_decay=0.0005):21 net = ops.conv2d(inputs, 64, [11, 11], 4, padding='VALID', scope='conv1')22 net = ops.conv2d(net, 256, [5, 5], scope='conv2')23 The first call to conv2d will overwrite padding:24 ops.conv2d(inputs, 64, [11, 11], 4, padding='VALID',25 stddev=0.01, weight_decay=0.0005, scope='conv1')26 The second call to Conv will use predefined args:27 ops.conv2d(inputs, 256, [5, 5], padding='SAME',28 stddev=0.01, weight_decay=0.0005, scope='conv2')29 Example of how to reuse an arg_scope:30 with scopes.arg_scope(ops.conv2d, padding='SAME',31 stddev=0.01, weight_decay=0.0005) as conv2d_arg_scope:32 net = ops.conv2d(net, 256, [5, 5], scope='conv1')33 ....34 with scopes.arg_scope(conv2d_arg_scope):35 net = ops.conv2d(net, 256, [5, 5], scope='conv2')36 Example of how to use scopes.add_arg_scope:37 @scopes.add_arg_scope38 def conv2d(*args, **kwargs)39"""40from __future__ import absolute_import41from __future__ import division42from __future__ import print_function43import contextlib44import functools45from tensorflow.python.framework import ops46_ARGSTACK_KEY = ("__arg_stack",)47_DECORATED_OPS = set()48def _get_arg_stack():49 stack = ops.get_collection(_ARGSTACK_KEY)50 if stack:51 return stack[0]52 else:53 stack = [{}]54 ops.add_to_collection(_ARGSTACK_KEY, stack)55 return stack56def _current_arg_scope():57 stack = _get_arg_stack()58 return stack[-1]59def _add_op(op):60 key_op = (op.__module__, op.__name__)61 if key_op not in _DECORATED_OPS:62 _DECORATED_OPS.add(key_op)63@contextlib.contextmanager64def arg_scope(list_ops_or_scope, **kwargs):65 """Stores the default arguments for the given set of list_ops.66 For usage, please see examples at top of the file.67 Args:68 list_ops_or_scope: List or tuple of operations to set argument scope for or69 a dictionary containg the current scope. When list_ops_or_scope is a dict,70 kwargs must be empty. When list_ops_or_scope is a list or tuple, then71 every op in it need to be decorated with @add_arg_scope to work.72 **kwargs: keyword=value that will define the defaults for each op in73 list_ops. All the ops need to accept the given set of arguments.74 Yields:75 the current_scope, which is a dictionary of {op: {arg: value}}76 Raises:77 TypeError: if list_ops is not a list or a tuple.78 ValueError: if any op in list_ops has not be decorated with @add_arg_scope.79 """80 if isinstance(list_ops_or_scope, dict):81 # Assumes that list_ops_or_scope is a scope that is being reused.82 if kwargs:83 raise ValueError("When attempting to re-use a scope by suppling a"84 "dictionary, kwargs must be empty.")85 current_scope = list_ops_or_scope.copy()86 try:87 _get_arg_stack().append(current_scope)88 yield current_scope89 finally:90 _get_arg_stack().pop()91 else:92 # Assumes that list_ops_or_scope is a list/tuple of ops with kwargs.93 if not isinstance(list_ops_or_scope, (list, tuple)):94 raise TypeError("list_ops_or_scope must either be a list/tuple or reused"95 "scope (i.e. dict)")96 try:97 current_scope = _current_arg_scope().copy()98 for op in list_ops_or_scope:99 key_op = (op.__module__, op.__name__)100 if not has_arg_scope(op):101 raise ValueError("%s is not decorated with @add_arg_scope", key_op)102 if key_op in current_scope:103 current_kwargs = current_scope[key_op].copy()104 current_kwargs.update(kwargs)105 current_scope[key_op] = current_kwargs106 else:107 current_scope[key_op] = kwargs.copy()108 _get_arg_stack().append(current_scope)109 yield current_scope110 finally:111 _get_arg_stack().pop()112def add_arg_scope(func):113 """Decorates a function with args so it can be used within an arg_scope.114 Args:115 func: function to decorate.116 Returns:117 A tuple with the decorated function func_with_args().118 """119 @functools.wraps(func)120 def func_with_args(*args, **kwargs):121 current_scope = _current_arg_scope()122 current_args = kwargs123 key_func = (func.__module__, func.__name__)124 if key_func in current_scope:125 current_args = current_scope[key_func].copy()126 current_args.update(kwargs)127 return func(*args, **current_args)128 _add_op(func)129 return func_with_args130def has_arg_scope(func):131 """Checks whether a func has been decorated with @add_arg_scope or not.132 Args:133 func: function to check.134 Returns:135 a boolean.136 """137 key_op = (func.__module__, func.__name__)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful