Python numpy.cumprod() Examples

The following are 30 code examples of numpy.cumprod(). 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 numpy , or try the search function .
Example #1
Source File: test_function_base.py    From lambda-packs with MIT License 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                self.assertRaises(ArithmeticError, np.cumprod, a)
                self.assertRaises(ArithmeticError, np.cumprod, a2, 1)
                self.assertRaises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype)) 
Example #2
Source File: rewards.py    From Counterfactual-StoryRW with MIT License 6 votes vote down vote up
def _discount_reward_tensor_1d(reward, sequence_length,
                               discount=1., dtype=None):
    if sequence_length is None:
        raise ValueError('sequence_length must not be `None` for 1D reward.')

    batch_size = tf.shape(reward)[0]
    max_seq_length = tf.reduce_max(sequence_length)
    dtype = dtype or reward.dtype

    if discount == 1.:
        dmat = tf.ones(
            tf.concat([[batch_size], [max_seq_length]], 0), dtype=dtype)
    else:
        mask = tf.sequence_mask(sequence_length, dtype=dtype)
        mask = tf.concat([mask[:, 1:], tf.zeros_like(mask[:, -1:])], axis=1)
        # Make each row = [discount, ..., discount, 1, ..., 1]
        dmat = mask * discount + (1 - mask)
        dmat = tf.cumprod(dmat, axis=1, reverse=True)

    disc_reward = dmat * tf.expand_dims(reward, -1)
    disc_reward = mask_sequences(
        disc_reward, sequence_length, dtype=dtype, tensor_rank=2)

    return disc_reward 
Example #3
Source File: test_function_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                assert_raises(ArithmeticError, np.cumprod, a)
                assert_raises(ArithmeticError, np.cumprod, a2, 1)
                assert_raises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype)) 
Example #4
Source File: slowreplib.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def __init__(self, embedded_op, numBasisEls, actionInds,
                 blocksizes, embedded_dim, nComponentsInActiveBlock,
                 iActiveBlock, nBlocks, dim):

        self.embedded = embedded_op
        self.numBasisEls = numBasisEls
        self.actionInds = actionInds
        self.blocksizes = blocksizes

        numBasisEls_noop_blankaction = numBasisEls.copy()
        for i in actionInds: numBasisEls_noop_blankaction[i] = 1
        self.basisInds_noop_blankaction = [list(range(n)) for n in numBasisEls_noop_blankaction]

        # multipliers to go from per-label indices to tensor-product-block index
        # e.g. if map(len,basisInds) == [1,4,4] then multipliers == [ 16 4 1 ]
        self.multipliers = _np.array(_np.flipud(_np.cumprod([1] + list(
            reversed(list(numBasisEls[1:]))))), _np.int64)
        self.basisInds_action = [list(range(numBasisEls[i])) for i in actionInds]

        self.embeddedDim = embedded_dim
        self.nComponents = nComponentsInActiveBlock
        self.iActiveBlock = iActiveBlock
        self.nBlocks = nBlocks
        self.offset = sum(blocksizes[0:iActiveBlock])
        super(DMOpRep_Embedded, self).__init__(dim) 
Example #5
Source File: slowreplib.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def __init__(self, embedded_op, numBasisEls, actionInds,
                 blocksizes, embedded_dim, nComponentsInActiveBlock,
                 iActiveBlock, nBlocks, dim):

        self.embedded = embedded_op
        self.numBasisEls = numBasisEls
        self.actionInds = actionInds
        self.blocksizes = blocksizes

        numBasisEls_noop_blankaction = numBasisEls.copy()
        for i in actionInds: numBasisEls_noop_blankaction[i] = 1
        self.basisInds_noop_blankaction = [list(range(n)) for n in numBasisEls_noop_blankaction]

        # multipliers to go from per-label indices to tensor-product-block index
        # e.g. if map(len,basisInds) == [1,4,4] then multipliers == [ 16 4 1 ]
        self.multipliers = _np.array(_np.flipud(_np.cumprod([1] + list(
            reversed(list(numBasisEls[1:]))))), _np.int64)
        self.basisInds_action = [list(range(numBasisEls[i])) for i in actionInds]

        self.embeddedDim = embedded_dim
        self.nComponents = nComponentsInActiveBlock
        self.iActiveBlock = iActiveBlock
        self.nBlocks = nBlocks
        self.offset = sum(blocksizes[0:iActiveBlock])
        super(SVOpRep_Embedded, self).__init__(dim) 
Example #6
Source File: radau.py    From lambda-packs with MIT License 6 votes vote down vote up
def _call_impl(self, t):
        x = (t - self.t_old) / self.h
        if t.ndim == 0:
            p = np.tile(x, self.order + 1)
            p = np.cumprod(p)
        else:
            p = np.tile(x, (self.order + 1, 1))
            p = np.cumprod(p, axis=0)
        # Here we don't multiply by h, not a mistake.
        y = np.dot(self.Q, p)
        if y.ndim == 2:
            y += self.y_old[:, None]
        else:
            y += self.y_old

        return y 
Example #7
Source File: test_function_base.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                self.assertRaises(ArithmeticError, np.cumprod, a)
                self.assertRaises(ArithmeticError, np.cumprod, a2, 1)
                self.assertRaises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype)) 
Example #8
Source File: extra_ops.py    From D-VAE with MIT License 6 votes vote down vote up
def cumprod(x, axis=None):
    """Return the cumulative product of the elements along a given axis.

    Wraping of numpy.cumprod.

    Parameters
    ----------
    x
        Input tensor variable.

    axis
        The axis along which the cumulative product is computed.
        The default (None) is to compute the cumprod over the flattened array.

    .. versionadded:: 0.7

    """
    return CumprodOp(axis=axis)(x) 
Example #9
Source File: test_function_base.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                assert_raises(ArithmeticError, np.cumprod, a)
                assert_raises(ArithmeticError, np.cumprod, a2, 1)
                assert_raises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype)) 
Example #10
Source File: axes.py    From ngraph-python with Apache License 2.0 6 votes vote down vote up
def reshape_workaround(data, shape_out):  # type: (TensorOp, Sequence[int]) -> TensorOp
    """Limited workaround for tensor reshape operation."""
    shape_in = data.shape.lengths

    if np.prod(shape_in) != np.prod(shape_out):
        raise ValueError('Total size of input (%d) and output (%d) dimension mismatch.',
                         np.prod(shape_in), np.prod(shape_out))

    ndims_out = len(shape_out)
    if ndims_out == 1:
        tensor = ng.flatten(data)
    elif ndims_out == 2:
        cumprods = list(np.cumprod(shape_in))
        flatten_at_idx = cumprods.index(shape_out[0]) + 1
        tensor = ng.flatten_at(data, flatten_at_idx)
    else:
        raise NotImplementedError('Reshape can only support flatten to 1d or 2d.')

    return ng.cast_axes(tensor, make_pos_axes(shape_out)) 
Example #11
Source File: test_function_base.py    From Computable with MIT License 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                self.assertRaises(ArithmeticError, cumprod, a)
                self.assertRaises(ArithmeticError, cumprod, a2, 1)
                self.assertRaises(ArithmeticError, cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis= -1),
                        np.array([1, 2, 20, 220, 1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                        np.array([[ 1, 2, 3, 4], [ 5, 12, 21, 36],
                            [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis= -1),
                        np.array([[ 1, 2, 6, 24], [ 5, 30, 210, 1890],
                            [10, 30, 120, 600]], ctype)) 
Example #12
Source File: test_function_base.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                assert_raises(ArithmeticError, np.cumprod, a)
                assert_raises(ArithmeticError, np.cumprod, a2, 1)
                assert_raises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype)) 
Example #13
Source File: utils.py    From neuron with GNU General Public License v3.0 6 votes vote down vote up
def sub2ind(siz, subs, **kwargs):
    """
    assumes column-order major
    """
    # subs is a list
    assert len(siz) == len(subs), \
        'found inconsistent siz and subs: %d %d' % (len(siz), len(subs))

    k = np.cumprod(siz[::-1])

    ndx = subs[-1]
    for i, v in enumerate(subs[:-1][::-1]):
        ndx = ndx + v * k[i]

    return ndx





###############################################################################
# functions from some external source
############################################################################### 
Example #14
Source File: clf_helpers.py    From ibeis with Apache License 2.0 6 votes vote down vote up
def encoded_1d(samples):
        """ Returns a unique label for each combination of samples """
        # from sklearn.preprocessing import MultiLabelBinarizer
        encoded_2d = samples.encoded_2d()
        class_space = [v.n_classes for k, v in samples.items()]
        offsets = np.array([1] + np.cumprod(class_space).tolist()[:-1])[None, :]
        encoded_1d = (offsets * encoded_2d).sum(axis=1)
        # e = MultiLabelBinarizer()
        # bin_coeff = e.fit_transform(encoded_2d)
        # bin_basis = (2 ** np.arange(bin_coeff.shape[1]))[None, :]
        # # encoded_1d = (bin_coeff * bin_basis).sum(axis=1)
        # encoded_1d = (bin_coeff * bin_basis[::-1]).sum(axis=1)
        # # vt.unique_rows(sklearn.preprocessing.MultiLabelBinarizer().fit_transform(encoded_2d))
        # [v.encoded_df.values for k, v in samples.items()]
        # encoded_df_1d = pd.concat([v.encoded_df for k, v in samples.items()], axis=1)
        return encoded_1d 
Example #15
Source File: array_ops_test.py    From trax with Apache License 2.0 6 votes vote down vote up
def testCumProdAndSum(self):

    def run_test(arr, *args, **kwargs):
      for fn in self.array_transforms:
        arg = fn(arr)
        self.match(
            array_ops.cumprod(arg, *args, **kwargs),
            np.cumprod(arg, *args, **kwargs))
        self.match(
            array_ops.cumsum(arg, *args, **kwargs),
            np.cumsum(arg, *args, **kwargs))

    run_test([])
    run_test([1, 2, 3])
    run_test([1, 2, 3], dtype=float)
    run_test([1, 2, 3], dtype=np.float32)
    run_test([1, 2, 3], dtype=np.float64)
    run_test([1., 2., 3.])
    run_test([1., 2., 3.], dtype=int)
    run_test([1., 2., 3.], dtype=np.int32)
    run_test([1., 2., 3.], dtype=np.int64)
    run_test([[1, 2], [3, 4]], axis=1)
    run_test([[1, 2], [3, 4]], axis=0)
    run_test([[1, 2], [3, 4]], axis=-1)
    run_test([[1, 2], [3, 4]], axis=-2) 
Example #16
Source File: test_function_base.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                assert_raises(ArithmeticError, np.cumprod, a)
                assert_raises(ArithmeticError, np.cumprod, a2, 1)
                assert_raises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype)) 
Example #17
Source File: test_cumprod.py    From chainer with MIT License 5 votes vote down vote up
def forward(self, inputs, device):
        x, = inputs
        return functions.cumprod(x, axis=self.axis), 
Example #18
Source File: test_bayesian_mixture.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_bayesian_mixture_weights():
    rng = np.random.RandomState(0)
    n_samples, n_features = 10, 2

    X = rng.rand(n_samples, n_features)

    # Case Dirichlet distribution for the weight concentration prior type
    bgmm = BayesianGaussianMixture(
        weight_concentration_prior_type="dirichlet_distribution",
        n_components=3, random_state=rng).fit(X)

    expected_weights = (bgmm.weight_concentration_ /
                        np.sum(bgmm.weight_concentration_))
    assert_almost_equal(expected_weights, bgmm.weights_)
    assert_almost_equal(np.sum(bgmm.weights_), 1.0)

    # Case Dirichlet process for the weight concentration prior type
    dpgmm = BayesianGaussianMixture(
        weight_concentration_prior_type="dirichlet_process",
        n_components=3, random_state=rng).fit(X)
    weight_dirichlet_sum = (dpgmm.weight_concentration_[0] +
                            dpgmm.weight_concentration_[1])
    tmp = dpgmm.weight_concentration_[1] / weight_dirichlet_sum
    expected_weights = (dpgmm.weight_concentration_[0] / weight_dirichlet_sum *
                        np.hstack((1, np.cumprod(tmp[:-1]))))
    expected_weights /= np.sum(expected_weights)
    assert_almost_equal(expected_weights, dpgmm.weights_)
    assert_almost_equal(np.sum(dpgmm.weights_), 1.0) 
Example #19
Source File: bayesian_mixture.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _set_parameters(self, params):
        (self.weight_concentration_, self.mean_precision_, self.means_,
         self.degrees_of_freedom_, self.covariances_,
         self.precisions_cholesky_) = params

        # Weights computation
        if self.weight_concentration_prior_type == "dirichlet_process":
            weight_dirichlet_sum = (self.weight_concentration_[0] +
                                    self.weight_concentration_[1])
            tmp = self.weight_concentration_[1] / weight_dirichlet_sum
            self.weights_ = (
                self.weight_concentration_[0] / weight_dirichlet_sum *
                np.hstack((1, np.cumprod(tmp[:-1]))))
            self.weights_ /= np.sum(self.weights_)
        else:
            self. weights_ = (self.weight_concentration_ /
                              np.sum(self.weight_concentration_))

        # Precisions matrices computation
        if self.covariance_type == 'full':
            self.precisions_ = np.array([
                np.dot(prec_chol, prec_chol.T)
                for prec_chol in self.precisions_cholesky_])

        elif self.covariance_type == 'tied':
            self.precisions_ = np.dot(self.precisions_cholesky_,
                                      self.precisions_cholesky_.T)
        else:
            self.precisions_ = self.precisions_cholesky_ ** 2 
Example #20
Source File: fromnumeric.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def cumproduct(*args, **kwargs):
    """
    Return the cumulative product over the given axis.

    See Also
    --------
    cumprod : equivalent function; see for details.
    """
    return cumprod(*args, **kwargs) 
Example #21
Source File: test_nanfunctions.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_result_values(self):
        for axis in (-2, -1, 0, 1, None):
            tgt = np.cumprod(_ndat_ones, axis=axis)
            res = np.nancumprod(_ndat, axis=axis)
            assert_almost_equal(res, tgt)
            tgt = np.cumsum(_ndat_zeros,axis=axis)
            res = np.nancumsum(_ndat, axis=axis)
            assert_almost_equal(res, tgt) 
Example #22
Source File: test_nanfunctions.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_allnans(self):
        for f, tgt_value in zip(self.nanfuncs, [0, 1]):
            # Unlike other nan-functions, sum/prod/cumsum/cumprod don't warn on all nan input
            with assert_no_warnings():
                res = f([np.nan]*3, axis=None)
                tgt = tgt_value*np.ones((3))
                assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((3))' % (tgt_value))
                # Check scalar
                res = f(np.nan)
                tgt = tgt_value*np.ones((1))
                assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((1))' % (tgt_value))
                # Check there is no warning for not all-nan
                f([0]*3, axis=None) 
Example #23
Source File: test_nanfunctions.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_nancumprod(self):
        tgt = np.cumprod(self.mat)
        for mat in self.integer_arrays():
            assert_equal(np.nancumprod(mat), tgt) 
Example #24
Source File: test_nanfunctions.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_nancumprod(self):
        tgt = np.cumprod(self.mat)
        for mat in self.integer_arrays():
            assert_equal(np.nancumprod(mat), tgt) 
Example #25
Source File: representation.py    From Ensemble-Bayesian-Optimization with MIT License 5 votes vote down vote up
def __init__(self, dims, wrap=False):
        super(IdentityHash, self).__init__()
        self.memory = np.prod(dims)
        self.dims = dims.astype('int')
        self.wrap = wrap
        self.dim_offset = np.cumprod(np.vstack((np.ones((self.dims.shape[2], 1)), self.dims[0, :0:-1, :])),
                                     axis=0).astype('int')[None, ::-1, :] 
Example #26
Source File: test_nanfunctions.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_allnans(self):
        for f, tgt_value in zip(self.nanfuncs, [0, 1]):
            # Unlike other nan-functions, sum/prod/cumsum/cumprod don't warn on all nan input
            with assert_no_warnings():
                res = f([np.nan]*3, axis=None)
                tgt = tgt_value*np.ones((3))
                assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((3))' % (tgt_value))
                # Check scalar
                res = f(np.nan)
                tgt = tgt_value*np.ones((1))
                assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((1))' % (tgt_value))
                # Check there is no warning for not all-nan
                f([0]*3, axis=None) 
Example #27
Source File: separation_model.py    From nussl with MIT License 5 votes vote down vote up
def __repr__(self):
        output = super().__repr__()
        num_parameters = 0
        for p in self.parameters():
            if p.requires_grad:
                num_parameters += np.cumprod(p.size())[-1]
        output += '\nNumber of parameters: %d' % num_parameters
        return output 
Example #28
Source File: test_nanfunctions.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_result_values(self):
        for axis in (-2, -1, 0, 1, None):
            tgt = np.cumprod(_ndat_ones, axis=axis)
            res = np.nancumprod(_ndat, axis=axis)
            assert_almost_equal(res, tgt)
            tgt = np.cumsum(_ndat_zeros,axis=axis)
            res = np.nancumsum(_ndat, axis=axis)
            assert_almost_equal(res, tgt) 
Example #29
Source File: param.py    From paramz with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _raveled_index(self, slice_index=None):
        # return an index array on the raveled array, which is formed by the current_slice
        # of this object
        extended_realshape = np.cumprod((1,) + self._realshape_[:0:-1])[::-1]
        ind = self._indices(slice_index)
        if ind.ndim < 2: ind = ind[:, None]
        return np.asarray(np.apply_along_axis(lambda x: np.sum(extended_realshape * x), 1, ind), dtype=int) 
Example #30
Source File: test_analytics.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_cummethods_bool(self):
        # GH 6270
        # looks like a buggy np.maximum.accumulate for numpy 1.6.1, py 3.2
        def cummin(x):
            return np.minimum.accumulate(x)

        def cummax(x):
            return np.maximum.accumulate(x)

        a = pd.Series([False, False, False, True, True, False, False])
        b = ~a
        c = pd.Series([False] * len(b))
        d = ~c
        methods = {'cumsum': np.cumsum,
                   'cumprod': np.cumprod,
                   'cummin': cummin,
                   'cummax': cummax}
        args = product((a, b, c, d), methods)
        for s, method in args:
            expected = Series(methods[method](s.values))
            result = getattr(s, method)()
            assert_series_equal(result, expected)

        e = pd.Series([False, True, nan, False])
        cse = pd.Series([0, 1, nan, 1], dtype=object)
        cpe = pd.Series([False, 0, nan, 0])
        cmin = pd.Series([False, False, nan, False])
        cmax = pd.Series([False, True, nan, True])
        expecteds = {'cumsum': cse,
                     'cumprod': cpe,
                     'cummin': cmin,
                     'cummax': cmax}

        for method in methods:
            res = getattr(e, method)()
            assert_series_equal(res, expecteds[method])