本文整理汇总了Python中chainer.variable.Variable方法的典型用法代码示例。如果您正苦于以下问题:Python variable.Variable方法的具体用法?Python variable.Variable怎么用?Python variable.Variable使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类chainer.variable
的用法示例。
在下文中一共展示了variable.Variable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _forward_for_backward_gradients
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def _forward_for_backward_gradients(self):
func = self.func
xs = self.xs
params = self.params
xs = [
None if x is None
else variable.Variable(x, requires_grad=x.dtype.kind == 'f')
for x in xs]
if self.is_immutable_params:
params = tuple([chainer.Parameter(p) for p in params])
ys = func(xs, params)
else:
ys = func(*xs)
ys = _as_tuple(ys)
# Clear gradients which may exist if func calls backward inside of
# itself.
self._clear_grads(xs)
self._clear_grads(params)
return xs, ys, params
示例2: update_core
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def update_core(self, param):
"""Updates the parameter.
Implementation of UpdateRule should override this method or both of
:meth:`update_core_cpu` and :meth:`update_core_gpu`.
Args:
param (~chainer.Variable): Variable to be updated.
"""
device = param.device
with chainer.using_device(device):
if device.xp is chainerx:
self.update_core_chainerx(param)
elif device.xp is numpy:
self.update_core_cpu(param)
else:
self.update_core_gpu(param)
示例3: reallocate_cleared_grads
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def reallocate_cleared_grads(self):
"""Reallocate gradients cleared by :meth:`~chainer.Variable.cleargrad`.
This method allocates arrays for all gradients which have :obj:`None`.
This method is called before and after every optimizer hook.
If an inheriting optimizer does not require this allocation,
the optimizer can override this method with a blank function.
"""
for name, param in self.target.namedparams(False):
with variable._AllowArrayAccessWithNonstandardLayout():
has_grad = param.grad is not None
if not has_grad:
device = param.device
with chainer.using_device(device):
param._set_grad(
device.xp.zeros_like(param.raw_array),
layout_check=False)
示例4: add
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def add(self, d):
"""Adds a dictionary of scalars.
Args:
d (dict): Dictionary of scalars to accumulate. Only elements of
scalars, zero-dimensional arrays, and variables of
zero-dimensional arrays are accumulated. When the value
is a tuple, the second element is interpreted as a weight.
"""
summaries = self._summaries
for k, v in six.iteritems(d):
w = 1
if isinstance(v, tuple):
w = v[1]
v = v[0]
if isinstance(w, variable.Variable):
w = w.array
if not numpy.isscalar(w) and not getattr(w, 'ndim', -1) == 0:
raise ValueError(
'Given weight to {} was not scalar.'.format(k))
if isinstance(v, variable.Variable):
v = v.array
if numpy.isscalar(v) or getattr(v, 'ndim', -1) == 0:
summaries[k].add(v, weight=w)
示例5: set_state
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def set_state(self, c, h):
"""Sets the internal state.
It sets the :attr:`c` and :attr:`h` attributes.
Args:
c (~chainer.Variable): A new cell states of LSTM units.
h (~chainer.Variable): A new output at the previous time step.
"""
assert isinstance(c, variable.Variable)
assert isinstance(h, variable.Variable)
c.to_device(self.device)
h.to_device(self.device)
self.c = c
self.h = h
示例6: forward
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def forward(self, x, t):
"""Computes the loss value for given input and ground truth labels.
Args:
x (~chainer.Variable): Input of the weight matrix multiplication.
t (~chainer.Variable): Batch of ground truth labels.
Returns:
~chainer.Variable: Loss value.
"""
batch_size = x.shape[0]
if self.sample_data is not None:
# for test
sample_data = self.sample_data
else:
shape = (batch_size, self.sample_size)
sample_data = self.sampler.sample(shape)
samples = variable.Variable(sample_data, requires_grad=False)
return black_out.black_out(x, t, self.W, samples)
示例7: from_params
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def from_params(cls, W, b=None, nobias=False):
"""Initialize a :class:`~chainer.links.Linear` with given parameters.
This method uses ``W`` and optional ``b`` to initialize a linear layer.
Args:
W (:class:`~chainer.Variable` or :ref:`ndarray`):
The weight parameter.
b (:class:`~chainer.Variable`, :ref:`ndarray`, or ``None``):
The bias parameter.
nobias (bool): If ``True``, the argument of ``b`` is ignored
in spite of whether it's given or not.
"""
out_size, in_size = W.shape
if b is not None:
if out_size != b.size:
raise ValueError('`out_size` does not match the size of `b`')
link = cls(
in_size, out_size, nobias,
initialW=variable.as_array(W), initial_bias=variable.as_array(b))
return link
示例8: forward
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def forward(
self,
x: variable.Variable,
n_batch_axes: int = 1
) -> variable.Variable:
"""Applies the linear layer.
Args:
x (~chainer.Variable): Batch of input vectors.
n_batch_axes (int): The number of batch axes. The default is 1. The
input variable is reshaped into
(:math:`{\\rm n\\_batch\\_axes} + 1`)-dimensional tensor.
This should be greater than 0.
Returns:
~chainer.Variable: Output of the linear layer.
"""
if self.W.array is None:
in_size = utils.size_of_shape(x.shape[n_batch_axes:])
self._initialize_params(in_size)
return linear.linear(x, self.W, self.b, n_batch_axes=n_batch_axes)
示例9: _process
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def _process(self, function, in_data, out_grad=None):
self._print('function\t{}'.format(function.label))
self._print('input data')
for d in in_data:
if d is None:
# Some inputs can be removed with `retain_grad`.
self._print('(removed)')
continue
self._print(variable.Variable(d).debug_print())
if out_grad is not None:
self._print('output gradient')
for d in out_grad:
if d is None:
v = variable.Variable()
else:
xp = backend.get_array_module(d)
v = variable.Variable(xp.zeros_like(d, dtype=d.dtype))
v.grad = d
self._print(v.debug_print())
if self.flush and hasattr(self.file, 'flush'):
self.file.flush()
示例10: _convert_value_to_string
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def _convert_value_to_string(value):
if isinstance(value, variable.Variable):
value = value.data
if numpy.isscalar(value):
if value < 0:
return '({})'.format(value)
else:
return str(value)
array_types = chainer.get_array_types()
if isinstance(value, array_types):
return 'constant array'
else:
raise ValueError(
'Value must be a Variable, scalar, {} or {}. Actual: {}'.format(
', '.join([str(at) for at in array_types[:-1]]),
array_types[-1], type(value)))
示例11: __call__
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def __call__(self, c, h, x):
"""Returns new cell state and updated output of LSTM.
Args:
c (~chainer.Variable): Cell states of LSTM units.
h (~chainer.Variable): Output at the previous time step.
x (~chainer.Variable): A new batch from the input sequence.
Returns:
tuple of ~chainer.Variable: Returns ``(c_new, h_new)``, where
``c_new`` represents new cell state, and ``h_new`` is updated
output of LSTM units.
"""
if self.upward.has_uninitialized_params:
in_size = x.size // x.shape[0]
with cuda.get_device_from_id(self._device_id):
self.upward._initialize_params(in_size)
self._initialize_params()
lstm_in = self.upward_ln(self.upward(x))
if h is not None:
lstm_in += self.lateral_ln(self.lateral(h))
if c is None:
xp = self.xp
with cuda.get_device_from_id(self._device_id):
c = variable.Variable(
xp.zeros((x.shape[0], self.state_size), dtype=x.dtype),
volatile='auto')
c_next, ungated_h, o_gate = lstm_with_ungated_output(c, lstm_in)
h = o_gate * self.output_ln(ungated_h)
return c_next, h
示例12: __call__
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def __call__(self, x, layers=['prob'], **kwargs):
"""__call__(self, x, layers=['prob'])
Computes all the feature maps specified by ``layers``.
.. warning::
``test`` argument is not supported anymore since v2.
Instead, use ``chainer.using_config('train', train)``.
See :func:`chainer.using_config`.
Args:
x (~chainer.Variable): Input variable.
layers (list of str): The list of layer names you want to extract.
Returns:
Dictionary of ~chainer.Variable: A directory in which
the key contains the layer name and the value contains
the corresponding feature map variable.
"""
argument.check_unexpected_kwargs(
kwargs, test='test argument is not supported anymore. '
'Use chainer.using_config')
argument.assert_kwargs_empty(kwargs)
h = x
activations = {}
target_layers = set(layers)
for key, funcs in self.functions.items():
if len(target_layers) == 0:
break
for func in funcs:
h = func(h)
if key in target_layers:
activations[key] = h
target_layers.remove(key)
return activations
示例13: predict
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def predict(self, images, oversample=True):
"""Computes all the probabilities of given images.
Args:
images (iterable of PIL.Image or numpy.ndarray): Input images.
oversample (bool): If ``True``, it averages results across
center, corners, and mirrors. Otherwise, it uses only the
center.
Returns:
~chainer.Variable: Output that contains the class probabilities
of given images.
"""
x = concat_examples([prepare(img, size=(256, 256)) for img in images])
if oversample:
x = imgproc.oversample(x, crop_dims=(224, 224))
else:
x = x[:, :, 16:240, 16:240]
# Use no_backprop_mode to reduce memory consumption
with function.no_backprop_mode():
x = Variable(self.xp.asarray(x))
y = self(x, layers=['prob'])['prob']
if oversample:
n = y.data.shape[0] // 10
y_shape = y.data.shape[1:]
y = reshape(y, (n, 10) + y_shape)
y = sum(y, axis=1) / 10
return y
示例14: forward
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def forward(self, c, h, x):
"""Returns new cell state and updated output of LSTM.
Args:
c (~chainer.Variable): Cell states of LSTM units.
h (~chainer.Variable): Output at the previous time step.
x (~chainer.Variable): A new batch from the input sequence.
Returns:
tuple of ~chainer.Variable: Returns ``(c_new, h_new)``, where
``c_new`` represents new cell state, and ``h_new`` is updated
output of LSTM units.
"""
# EDIT(hamaji): No lazy initialization.
# if self.upward.W.data is None:
# in_size = x.size // x.shape[0]
# with cuda.get_device_from_id(self._device_id):
# self.upward._initialize_params(in_size)
# self._initialize_params()
lstm_in = self.upward(x)
if h is not None:
lstm_in += self.lateral(h)
if c is None:
# EDIT(hamaji): Use numpy and np.float32.
# xp = self.xp
# with cuda.get_device_from_id(self._device_id):
# c = variable.Variable(
# xp.zeros((x.shape[0], self.state_size), dtype=x.dtype))
c = variable.Variable(
self.xp.zeros((x.shape[0], self.state_size), dtype=self.xp.float32))
# EDIT(hamaji): Use lstm_forward.
return lstm_forward(c, lstm_in)
# return lstm.lstm(c, lstm_in)
示例15: original
# 需要导入模块: from chainer import variable [as 别名]
# 或者: from chainer.variable import Variable [as 别名]
def original(self, c, h, x):
"""Returns new cell state and updated output of LSTM.
Args:
c (~chainer.Variable): Cell states of LSTM units.
h (~chainer.Variable): Output at the previous time step.
x (~chainer.Variable): A new batch from the input sequence.
Returns:
tuple of ~chainer.Variable: Returns ``(c_new, h_new)``, where
``c_new`` represents new cell state, and ``h_new`` is updated
output of LSTM units.
"""
if self.upward.W.data is None:
in_size = x.size // x.shape[0]
with cuda.get_device_from_id(self._device_id):
self.upward._initialize_params(in_size)
self._initialize_params()
lstm_in = self.upward(x)
if h is not None:
lstm_in += self.lateral(h)
if c is None:
xp = self.xp
with cuda.get_device_from_id(self._device_id):
c = variable.Variable(
xp.zeros((x.shape[0], self.state_size), dtype=x.dtype))
return lstm.lstm(c, lstm_in)