Python chainer.utils.force_array() Examples

The following are 30 code examples of chainer.utils.force_array(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module chainer.utils , or try the search function .
Example #1
Source File: test_binary_accuracy.py    From chainer with MIT License 6 votes vote down vote up
def forward_expected(self, inputs):
        x, t = inputs
        count = 0
        correct = 0
        x_flatten = x.ravel()
        t_flatten = t.ravel()
        for i in six.moves.range(t_flatten.size):
            if t_flatten[i] == -1:
                continue
            pred = int(x_flatten[i] >= 0)
            if pred == t_flatten[i]:
                correct += 1
            count += 1
        expected = float(correct) / count
        expected = force_array(expected, self.dtype)
        return expected, 
Example #2
Source File: test_normal.py    From chainer with MIT License 6 votes vote down vote up
def setUp_configure(self):
        from scipy import stats
        self.dist = distributions.Normal
        self.scipy_dist = stats.norm

        self.test_targets = set([
            'batch_shape', 'cdf', 'entropy', 'event_shape', 'icdf', 'log_cdf',
            'log_prob', 'log_survival', 'mean', 'prob', 'sample', 'stddev',
            'support', 'survival', 'variance'])

        loc = utils.force_array(
            numpy.random.uniform(-1, 1, self.shape).astype(numpy.float32))
        if self.log_scale_option:
            log_scale = utils.force_array(
                numpy.random.uniform(-1, 1, self.shape).astype(numpy.float32))
            scale = numpy.exp(log_scale)
            self.params = {'loc': loc, 'log_scale': log_scale}
            self.scipy_params = {'loc': loc, 'scale': scale}
        else:
            scale = utils.force_array(numpy.exp(
                numpy.random.uniform(-1, 1, self.shape)).astype(numpy.float32))
            self.params = {'loc': loc, 'scale': scale}
            self.scipy_params = {'loc': loc, 'scale': scale} 
Example #3
Source File: test_average.py    From chainer with MIT License 6 votes vote down vote up
def forward_expected(self, inputs):
        x, w = inputs
        if not self.use_weights:
            w = None
        y_expect = numpy.average(x, axis=self.axis, weights=w)
        if self.keepdims:
            # numpy.average does not support keepdims
            axis = self.axis
            if axis is None:
                axis = list(six.moves.range(x.ndim))
            elif isinstance(axis, int):
                axis = axis,
            shape = list(x.shape)
            for i in six.moves.range(len(shape)):
                if i in axis or i - len(shape) in axis:
                    shape[i] = 1
            y_expect = y_expect.reshape(shape)
        y_expect = utils.force_array(y_expect, dtype=self.dtype)
        return y_expect, 
Example #4
Source File: floor.py    From chainer with MIT License 6 votes vote down vote up
def floor(x):
    """Elementwise floor function.

    .. math::
       y_i = \\lfloor x_i \\rfloor

    Args:
        x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.

    Returns:
        ~chainer.Variable: Output variable.
    """
    if isinstance(x, chainer.variable.Variable):
        x = x.array
    xp = backend.get_array_module(x)
    return chainer.as_variable(utils.force_array(xp.floor(x), x.dtype)) 
Example #5
Source File: test_sigmoid_cross_entropy.py    From chainer with MIT License 6 votes vote down vote up
def check_double_backward(self, x_data, t_data, y_grad, gx_grad,
                              normalize=True, reduce='mean'):
        # Skip too large case. That requires a long time.
        if self.shape[0] == 65536:
            return

        if reduce == 'mean':
            y_grad = utils.force_array(y_grad.sum())

        def f(x, t):
            return chainer.functions.sigmoid_cross_entropy(
                x, t, normalize=normalize, reduce=reduce)

        gradient_check.check_double_backward(
            f, (x_data, t_data), y_grad, (gx_grad,),
            **self.check_double_backward_options) 
Example #6
Source File: bernoulli.py    From chainer with MIT License 6 votes vote down vote up
def forward(self, inputs):
        logit, x = inputs
        self.retain_inputs((0, 1))
        xp = backend.get_array_module(x)
        y = logit * (x - 1) - xp.log(xp.exp(-logit) + 1)
        y = utils.force_array(y)

        # extreme logit
        logit_isinf = xp.isinf(logit)
        self.logit_ispinf = xp.bitwise_and(logit_isinf, logit > 0)
        self.logit_isminf = xp.bitwise_and(logit_isinf, logit <= 0)
        with numpy.errstate(divide='ignore', invalid='raise'):
            y = xp.where(self.logit_ispinf, xp.log(x), y)
            y = xp.where(self.logit_isminf, xp.log(1 - x), y)

        if self.binary_check:
            self.invalid = utils.force_array(xp.bitwise_and(x != 0, x != 1))
            y[self.invalid] = -xp.inf

        return utils.force_array(y, logit.dtype), 
Example #7
Source File: test_gamma.py    From chainer with MIT License 6 votes vote down vote up
def setUp_configure(self):
        from scipy import stats
        self.dist = distributions.Gamma
        self.scipy_dist = stats.gamma

        self.test_targets = set(
            ['batch_shape', 'entropy', 'event_shape', 'log_prob', 'mean',
             'sample', 'support', 'variance'])

        k = utils.force_array(
            numpy.random.uniform(0, 5, self.shape).astype(numpy.float32))
        theta = utils.force_array(
            numpy.random.uniform(0, 5, self.shape).astype(numpy.float32))
        self.params = {'k': k, 'theta': theta}
        self.scipy_params = {'a': k, 'scale': theta}

        self.support = 'positive' 
Example #8
Source File: utils.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, inputs):
        x, = inputs
        self.x_zero = utils.force_array(x == 0)
        y = utils.force_array(x * self._logx.array)
        y[self.x_zero] = 0.
        return y, 
Example #9
Source File: test_function_link.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, inputs_and_grad_outputs):
        x1, x2, gy1, gy2 = inputs_and_grad_outputs
        self.retain_inputs((0, 1, 2, 3))

        ggx1, ggx2 = _backward_correct(x1, x2, gy1, gy2)
        return utils.force_array(ggx1), utils.force_array(ggx2) 
Example #10
Source File: utils.py    From chainer with MIT License 5 votes vote down vote up
def _modified_xlogx(x):
    x = chainer.as_variable(x)
    xp = x.xp
    return ModifiedXLogX(
        exponential.log(
            where.where(
                utils.force_array(x.array > 0),
                x,
                xp.ones_like(x.array)))).apply((x,))[0] 
Example #11
Source File: uniform.py    From chainer with MIT License 5 votes vote down vote up
def log_prob(self, x):
        if not isinstance(x, chainer.Variable):
            x = chainer.Variable(x)

        xp = backend.get_array_module(x)

        logp = broadcast.broadcast_to(
            -exponential.log(self.scale), x.shape)
        return where.where(
            utils.force_array(
                (x.data >= self.low.data) & (x.data <= self.high.data)),
            logp,
            xp.array(-xp.inf, logp.dtype)) 
Example #12
Source File: pareto.py    From chainer with MIT License 5 votes vote down vote up
def log_prob(self, x):
        x = chainer.as_variable(x)
        logp = (
            self._log_alpha
            + self.alpha * self._log_scale
            - (self.alpha + 1) * exponential.log(x))
        xp = logp.xp
        return where.where(
            utils.force_array(x.data >= self.scale.data),
            logp,
            xp.array(-xp.inf, logp.dtype)) 
Example #13
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward_cpu(self, inputs):
        self.retain_inputs((0, 1))
        x, gy = inputs
        gx = utils.force_array(numpy.square(x))
        numpy.negative(gx, out=gx)
        gx += 1
        numpy.sqrt(gx, out=gx)
        numpy.reciprocal(gx, out=gx)
        gx *= gy
        return gx, 
Example #14
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward_cpu(self, inputs):
        self.retain_inputs((0, 1))
        x, gy = inputs
        gx = utils.force_array(numpy.cos(x))
        gx *= gy
        return gx, 
Example #15
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward_cpu(self, inputs):
        self.retain_inputs((0, 1))
        x, gy = inputs
        gx = utils.force_array(numpy.sin(x))
        numpy.negative(gx, out=gx)
        gx *= gy
        return gx, 
Example #16
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, x):
        self.retain_inputs((0,))
        xp = backend.get_array_module(*x)
        return utils.force_array(xp.tan(x[0])), 
Example #17
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, x):
        self.retain_inputs((0,))
        xp = backend.get_array_module(*x)
        return utils.force_array(xp.arcsin(x[0])), 
Example #18
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, x):
        self.retain_inputs((0,))
        xp = backend.get_array_module(*x)
        return utils.force_array(xp.arctan(x[0])), 
Example #19
Source File: beta.py    From chainer with MIT License 5 votes vote down vote up
def log_prob(self, x):
        x = chainer.as_variable(x)
        logp = (
            (self.a - 1) * exponential.log(x)
            + (self.b - 1) * exponential.log(1 - x)
            - _lbeta(self.a, self.b))
        xp = logp.xp
        return where.where(
            utils.force_array((x.array >= 0) & (x.array <= 1)),
            logp,
            xp.array(-xp.inf, logp.dtype)) 
Example #20
Source File: test_activation.py    From chainer with MIT License 5 votes vote down vote up
def func(self, xp, a):
        dtype = self.out_dtype
        if xp is numpy:
            y = utils.force_array(a.clip(0, self.z))
            return numpy.asarray(y.astype(dtype))
        return xp.clipped_relu(a, self.z) 
Example #21
Source File: test_utils.py    From chainer with MIT License 5 votes vote down vote up
def test_0dim_array(self):
        x = utils.force_array(numpy.array(1, numpy.float32), dtype=self.dtype)
        self.assertIsInstance(x, numpy.ndarray)
        if self.dtype is None:
            self.assertEqual(x.dtype, numpy.float32)
        else:
            self.assertEqual(x.dtype, self.dtype) 
Example #22
Source File: test_function_link.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, inputs_and_grad_outputs):
        x1, x2, gy1, gy2 = inputs_and_grad_outputs
        self.retain_inputs((0, 1, 2, 3))

        ggx1, ggx2 = _backward_correct(
            x1, x2,
            0 if self.expect_grad_outputs_none[0] else gy1,
            0 if self.expect_grad_outputs_none[1] else gy2)
        return utils.force_array(ggx1), utils.force_array(ggx2) 
Example #23
Source File: test_function_link.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, inputs):
        x1, x2 = inputs
        y1, y2 = _forward_correct(x1, x2)
        self.retain_inputs((0, 1))
        return utils.force_array(y1), utils.force_array(y2) 
Example #24
Source File: test_function_link.py    From chainer with MIT License 5 votes vote down vote up
def backward(self, indexes, grad_outputs):
        gy1, gy2 = grad_outputs
        x1, x2 = self.get_retained_inputs()
        ggx1, ggx2 = _backward_correct(
            x1, x2,
            0 if self.expect_grad_outputs_none[0] else gy1,
            0 if self.expect_grad_outputs_none[1] else gy2)
        ggx1 = ggx1 + 100000
        ggx2 = ggx2 + 10000  # ! make incorrect
        return utils.force_array(ggx1), utils.force_array(ggx2) 
Example #25
Source File: test_function_link.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, inputs):
        x1, x2 = inputs
        y1, y2 = _forward_correct(x1, x2)
        self.retain_inputs((0, 1))
        return utils.force_array(y1), utils.force_array(y2) 
Example #26
Source File: test_function_link.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, inputs):
        x1, x2 = inputs
        y1, y2 = _forward_correct(x1, x2)
        y1, y2 = utils.force_array(y1), utils.force_array(y2)
        y2[...] += 1  # ! make incorrect
        return y1, y2 
Example #27
Source File: test_function_link.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, inputs):
        device = self.device
        x1, x2 = inputs
        if device.xp is chainerx:
            fallback_device = device.fallback_device
            assert isinstance(x1, fallback_device.supported_array_types)
            assert isinstance(x2, fallback_device.supported_array_types)

        self.retain_inputs((0, 1))
        y1, y2 = _forward_correct(x1, x2)
        return utils.force_array(y1), utils.force_array(y2) 
Example #28
Source File: test_function_link.py    From chainer with MIT License 5 votes vote down vote up
def _forward_correct(x1, x2):
    dt = x1.dtype.type
    y1 = (x1 + x2) ** dt(2)
    y2 = (x1 ** dt(2)) * (x2 ** dt(2))
    return utils.force_array(y1), utils.force_array(y2) 
Example #29
Source File: test_utils.py    From chainer with MIT License 5 votes vote down vote up
def test_array(self):
        x = utils.force_array(numpy.array([1], numpy.float32),
                              dtype=self.dtype)
        self.assertIsInstance(x, numpy.ndarray)
        if self.dtype is None:
            self.assertEqual(x.dtype, numpy.float32)
        else:
            self.assertEqual(x.dtype, self.dtype) 
Example #30
Source File: test_accuracy.py    From chainer with MIT License 5 votes vote down vote up
def forward_expected(self, inputs):
        x, t = inputs
        expected = accuracy(x, t, self.ignore_label)
        expected = force_array(expected, self.dtype)
        return expected,