本文整理汇总了Python中mxnet.gluon.Block方法的典型用法代码示例。如果您正苦于以下问题:Python gluon.Block方法的具体用法?Python gluon.Block怎么用?Python gluon.Block使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mxnet.gluon
的用法示例。
在下文中一共展示了gluon.Block方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def create(prefix, params, hint):
"""Creates prefix and params for new `Block`."""
current = getattr(_BlockScope._current, "value", None)
if current is None:
if prefix is None:
if not hasattr(_name.NameManager._current, "value"):
_name.NameManager._current.value = _name.NameManager()
prefix = _name.NameManager._current.value.get(None, hint) + '_'
if params is None:
params = ParameterDict(prefix)
else:
params = ParameterDict(params.prefix, params)
return prefix, params
if prefix is None:
count = current._counter.get(hint, 0)
prefix = '%s%d_'%(hint, count)
current._counter[hint] = count + 1
if params is None:
parent = current._block.params
params = ParameterDict(parent.prefix+prefix, parent._shared)
else:
params = ParameterDict(params.prefix, params)
return current._block.prefix+prefix, params
示例2: __setattr__
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def __setattr__(self, name, value):
"""Registers parameters."""
if hasattr(self, name):
existing = getattr(self, name)
if isinstance(existing, (Parameter, Block)) and not isinstance(value, type(existing)):
raise TypeError('Changing attribute type for {name} from {type1} to {type2}' \
'is not allowed.'.format(
name=name, type1=type(existing), type2=type(value)))
if isinstance(value, Block):
self.register_child(value, name)
elif isinstance(value, Parameter):
assert name not in self._reg_params, \
"Overriding Parameter attribute %s is not allowed. " \
"If you want to share parameters between blocks, please set " \
"'params' at Block construction instead."
self._reg_params[name] = value
super(Block, self).__setattr__(name, value)
示例3: load_params
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def load_params(self, filename, ctx=None, allow_missing=False,
ignore_extra=False):
"""[Deprecated] Please use load_parameters.
Load parameters from file.
filename : str
Path to parameter file.
ctx : Context or list of Context, default cpu()
Context(s) to initialize loaded parameters on.
allow_missing : bool, default False
Whether to silently skip loading parameters not represents in the file.
ignore_extra : bool, default False
Whether to silently ignore parameters from the file that are not
present in this Block.
"""
warnings.warn("load_params is deprecated. Please use load_parameters.")
self.load_parameters(filename, ctx, allow_missing, ignore_extra)
示例4: initialize
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def initialize(self, init=initializer.Uniform(), ctx=None, verbose=False,
force_reinit=False):
"""Initializes :py:class:`Parameter` s of this :py:class:`Block` and its children.
Equivalent to ``block.collect_params().initialize(...)``
Parameters
----------
init : Initializer
Global default Initializer to be used when :py:meth:`Parameter.init` is ``None``.
Otherwise, :py:meth:`Parameter.init` takes precedence.
ctx : Context or list of Context
Keeps a copy of Parameters on one or many context(s).
verbose : bool, default False
Whether to verbosely print out details on initialization.
force_reinit : bool, default False
Whether to force re-initialization if parameter is already initialized.
"""
self.collect_params().initialize(init, ctx, verbose, force_reinit)
示例5: create
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def create(prefix, params, hint):
"""Creates prefix and params for new `Block`."""
current = _BlockScope._current
if current is None:
if prefix is None:
prefix = _name.NameManager.current.get(None, hint) + '_'
if params is None:
params = ParameterDict(prefix)
else:
params = ParameterDict(params.prefix, params)
return prefix, params
if prefix is None:
count = current._counter.get(hint, 0)
prefix = '%s%d_'%(hint, count)
current._counter[hint] = count + 1
if params is None:
parent = current._block.params
params = ParameterDict(parent.prefix+prefix, parent._shared)
else:
params = ParameterDict(params.prefix, params)
return current._block.prefix+prefix, params
示例6: __setattr__
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def __setattr__(self, name, value):
"""Registers parameters."""
if hasattr(self, name):
existing = getattr(self, name)
if isinstance(existing, (Parameter, Block)) and not isinstance(value, type(existing)):
raise TypeError('Changing attribute type for {name} from {type1} to {type2}' \
'is not allowed.'.format(name=name,
type1=type(existing),
type2=type(value)))
if isinstance(existing, Block):
for i, c in enumerate(self._children):
if c is existing:
self._children[i] = value
elif isinstance(value, Block):
self.register_child(value)
elif isinstance(value, Block):
self.register_child(value)
super(Block, self).__setattr__(name, value)
示例7: load_params
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def load_params(self, filename, ctx, allow_missing=False,
ignore_extra=False):
"""Load parameters from file.
filename : str
Path to parameter file.
ctx : Context or list of Context
Context(s) initialize loaded parameters on.
allow_missing : bool, default False
Whether to silently skip loading parameters not represents in the file.
ignore_extra : bool, default False
Whether to silently ignore parameters from the file that are not
present in this Block.
"""
self.collect_params().load(filename, ctx, allow_missing, ignore_extra,
self.prefix)
示例8: __repr__
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def __repr__(self):
s = '{name}(\n{modstr}\n)'
modstr = '\n'.join([' ({key}): {block}'.format(key=key,
block=_indent(block.__repr__(), 2))
for key, block in self.__dict__.items() if isinstance(block, Block)])
return s.format(name=self.__class__.__name__, modstr=modstr)
示例9: _check_container_with_block
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def _check_container_with_block(self):
children = set(self._children.values())
def _find_unregistered_block_in_container(data):
# Find whether a nested container structure contains Blocks
if isinstance(data, (list, tuple)):
for ele in data:
if _find_unregistered_block_in_container(ele):
return True
return False
elif isinstance(data, dict):
for _, v in data.items():
if _find_unregistered_block_in_container(v):
return True
return False
elif isinstance(data, Block):
return not data in children
else:
return False
for k, v in self.__dict__.items():
if isinstance(v, (list, tuple, dict)) and not (k.startswith('__') or k == '_children'):
if _find_unregistered_block_in_container(v):
warnings.warn('"{name}" is an unregistered container with Blocks. '
'Note that Blocks inside the list, tuple or dict will not be '
'registered automatically. Make sure to register them using '
'register_child() or switching to '
'nn.Sequential/nn.HybridSequential instead. '
.format(name=self.__class__.__name__ + "." + k), stacklevel=3)
示例10: prefix
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def prefix(self):
"""Prefix of this :py:class:`Block`."""
return self._prefix
示例11: name_scope
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def name_scope(self):
"""Returns a name space object managing a child :py:class:`Block` and parameter
names. Should be used within a ``with`` statement::
with self.name_scope():
self.dense = nn.Dense(20)
Please refer to
`naming tutorial <http://mxnet.incubator.apache.org/tutorials/gluon/naming.html>`_
for more info on prefix and naming.
"""
return self._scope
示例12: params
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def params(self):
"""Returns this :py:class:`Block`'s parameter dictionary (does not include its
children's parameters)."""
return self._params
示例13: collect_params
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def collect_params(self, select=None):
"""Returns a :py:class:`ParameterDict` containing this :py:class:`Block` and all of its
children's Parameters(default), also can returns the select :py:class:`ParameterDict`
which match some given regular expressions.
For example, collect the specified parameters in ['conv1_weight', 'conv1_bias', 'fc_weight',
'fc_bias']::
model.collect_params('conv1_weight|conv1_bias|fc_weight|fc_bias')
or collect all parameters whose names end with 'weight' or 'bias', this can be done
using regular expressions::
model.collect_params('.*weight|.*bias')
Parameters
----------
select : str
regular expressions
Returns
-------
The selected :py:class:`ParameterDict`
"""
# We need to check here because blocks inside containers are not supported.
self._check_container_with_block()
ret = ParameterDict(self._params.prefix)
if not select:
ret.update(self.params)
else:
pattern = re.compile(select)
ret.update({name:value for name, value in self.params.items() if pattern.match(name)})
for cld in self._children.values():
ret.update(cld.collect_params(select=select))
return ret
示例14: cast
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def cast(self, dtype):
"""Cast this Block to use another data type.
Parameters
----------
dtype : str or numpy.dtype
The new data type.
"""
for child in self._children.values():
child.cast(dtype)
for _, param in self.params.items():
param.cast(dtype)
示例15: hybrid_forward
# 需要导入模块: from mxnet import gluon [as 别名]
# 或者: from mxnet.gluon import Block [as 别名]
def hybrid_forward(self, F, x, *args, **kwargs):
"""Overrides to construct symbolic graph for this `Block`.
Parameters
----------
x : Symbol or NDArray
The first input tensor.
*args : list of Symbol or list of NDArray
Additional input tensors.
"""
# pylint: disable= invalid-name
raise NotImplementedError