Python numpy.cumprod() Examples
The following are 30 code examples for showing how to use numpy.cumprod(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example 1
Project: pyGSTi Author: pyGSTio File: slowreplib.py License: Apache License 2.0 | 6 votes |
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 2
Project: pyGSTi Author: pyGSTio File: slowreplib.py License: Apache License 2.0 | 6 votes |
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 3
Project: recruit Author: Frank-qlu File: test_function_base.py License: Apache License 2.0 | 6 votes |
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
Project: Counterfactual-StoryRW Author: qkaren File: rewards.py License: MIT License | 6 votes |
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 5
Project: lambda-packs Author: ryfeus File: radau.py License: MIT License | 6 votes |
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 6
Project: lambda-packs Author: ryfeus File: test_function_base.py License: MIT License | 6 votes |
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 7
Project: auto-alt-text-lambda-api Author: abhisuri97 File: test_function_base.py License: MIT License | 6 votes |
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
Project: D-VAE Author: muhanzhang File: extra_ops.py License: MIT License | 6 votes |
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
Project: vnpy_crypto Author: birforce File: test_function_base.py License: MIT License | 6 votes |
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
Project: ngraph-python Author: NervanaSystems File: axes.py License: Apache License 2.0 | 6 votes |
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
Project: Computable Author: ktraunmueller File: test_function_base.py License: MIT License | 6 votes |
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
Project: Mastering-Elasticsearch-7.0 Author: PacktPublishing File: test_function_base.py License: MIT License | 6 votes |
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
Project: neuron Author: adalca File: utils.py License: GNU General Public License v3.0 | 6 votes |
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
Project: ibeis Author: Erotemic File: clf_helpers.py License: Apache License 2.0 | 6 votes |
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
Project: trax Author: google File: array_ops_test.py License: Apache License 2.0 | 6 votes |
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
Project: GraphicDesignPatternByPython Author: Relph1119 File: test_function_base.py License: MIT License | 6 votes |
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
Project: highdimensional-decision-boundary-plot Author: tmadl File: utils.py License: MIT License | 5 votes |
def polar_to_cartesian(arr, r): a = np.concatenate((np.array([2 * np.pi]), arr)) si = np.sin(a) si[0] = 1 si = np.cumprod(si) co = np.cos(a) co = np.roll(co, -1) return si * co * r
Example 18
Project: recruit Author: Frank-qlu File: test_nanfunctions.py License: Apache License 2.0 | 5 votes |
def test_nancumprod(self): tgt = np.cumprod(self.mat) for mat in self.integer_arrays(): assert_equal(np.nancumprod(mat), tgt)
Example 19
Project: recruit Author: Frank-qlu File: test_nanfunctions.py License: Apache License 2.0 | 5 votes |
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 20
Project: recruit Author: Frank-qlu File: test_nanfunctions.py License: Apache License 2.0 | 5 votes |
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 21
Project: recruit Author: Frank-qlu File: fromnumeric.py License: Apache License 2.0 | 5 votes |
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 22
Project: recruit Author: Frank-qlu File: test_analytics.py License: Apache License 2.0 | 5 votes |
def test_cumprod(self, datetime_series): self._check_accum_op('cumprod', datetime_series)
Example 23
Project: recruit Author: Frank-qlu File: test_analytics.py License: Apache License 2.0 | 5 votes |
def test_cummethods_bool(self): # GH 6270 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': np.minimum.accumulate, 'cummax': np.maximum.accumulate} 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])
Example 24
Project: Counterfactual-StoryRW Author: qkaren File: rewards.py License: MIT License | 5 votes |
def _discount_reward_py_1d(reward, sequence_length, discount=1., dtype=None): if sequence_length is None: raise ValueError('sequence_length must not be `None` for 1D reward.') reward = np.array(reward) sequence_length = np.array(sequence_length) batch_size = reward.shape[0] max_seq_length = np.max(sequence_length) dtype = dtype or reward.dtype if discount == 1.: dmat = np.ones([batch_size, max_seq_length], dtype=dtype) else: steps = np.tile(np.arange(max_seq_length), [batch_size, 1]) mask = np.asarray(steps < (sequence_length-1)[:, None], dtype=dtype) # Make each row = [discount, ..., discount, 1, ..., 1] dmat = mask * discount + (1 - mask) dmat = np.cumprod(dmat[:, ::-1], axis=1)[:, ::-1] disc_reward = dmat * reward[:, None] disc_reward = mask_sequences(disc_reward, sequence_length, dtype=dtype) #mask = np.asarray(steps < sequence_length[:, None], dtype=dtype) #disc_reward = mask * disc_reward return disc_reward
Example 25
Project: dexplo Author: dexplo File: _date_funcs.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def cumprod_date(arr, axis, **kwargs): return np.cumprod(arr, axis=axis)
Example 26
Project: paramz Author: sods File: param.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
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 27
Project: ffn Author: pmorissette File: test_core.py License: MIT License | 5 votes |
def test_drawdown_details(): drawdown = ffn.to_drawdown_series(df['MSFT']) drawdown_details = ffn.drawdown_details(drawdown) assert (drawdown_details.loc[drawdown_details.index[1], 'Length'] == 18) num_years = 30 num_months = num_years * 12 np.random.seed(0) returns = np.random.normal(loc=0.06 / 12, scale=0.20 / np.sqrt(12), size=num_months) returns = pd.Series(np.cumprod(1 + returns)) drawdown = ffn.to_drawdown_series(returns) drawdown_details = ffn.drawdown_details(drawdown, index_type=drawdown.index)
Example 28
Project: lambda-packs Author: ryfeus File: fromnumeric.py License: MIT License | 5 votes |
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 29
Project: lambda-packs Author: ryfeus File: bdf.py License: MIT License | 5 votes |
def _call_impl(self, t): if t.ndim == 0: x = (t - self.t_shift) / self.denom p = np.cumprod(x) else: x = (t - self.t_shift[:, None]) / self.denom[:, None] p = np.cumprod(x, axis=0) y = np.dot(self.D[1:].T, p) if y.ndim == 1: y += self.D[0] else: y += self.D[0, :, None] return y
Example 30
Project: lambda-packs Author: ryfeus File: rk.py License: MIT License | 5 votes |
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) y = self.h * np.dot(self.Q, p) if y.ndim == 2: y += self.y_old[:, None] else: y += self.y_old return y