本文整理匯總了Python中numpy.cumprod方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.cumprod方法的具體用法?Python numpy.cumprod怎麽用?Python numpy.cumprod使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.cumprod方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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)
示例2: test_basic
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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))
示例3: _discount_reward_tensor_1d
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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
示例4: _call_impl
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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
示例5: test_basic
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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))
示例6: cumprod
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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)
示例7: reshape_workaround
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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))
示例8: test_basic
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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))
示例9: sub2ind
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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
###############################################################################
示例10: encoded_1d
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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
示例11: testCumProdAndSum
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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)
示例12: polar_to_cartesian
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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
示例13: test_nancumprod
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
def test_nancumprod(self):
tgt = np.cumprod(self.mat)
for mat in self.integer_arrays():
assert_equal(np.nancumprod(mat), tgt)
示例14: test_allnans
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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)
示例15: test_result_values
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import cumprod [as 別名]
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)