Python numpy.cumproduct() Examples

The following are 18 code examples for showing how to use numpy.cumproduct(). 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: pase   Author: santi-pdp   File: modules.py    License: MIT License 6 votes vote down vote up
def __init__(self, feat_dims, upsample_scales=[4, 4, 10], compute_dims=128,
                 res_blocks=10, res_out_dims=128, pad=2):
        super().__init__()
        self.num_outputs = res_out_dims
        total_scale = np.cumproduct(upsample_scales)[-1]
        self.indent = pad * total_scale
        self.resnet = MelResNet(res_blocks, feat_dims, compute_dims, res_out_dims, pad)
        self.resnet_stretch = Stretch2d(total_scale, 1)
        self.up_layers = nn.ModuleList()
        for scale in upsample_scales:
            k_size = (1, scale * 2 + 1)
            padding = (0, scale)
            stretch = Stretch2d(scale, 1)
            conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=padding, bias=False)
            conv.weight.data.fill_(1. / k_size[1])
            self.up_layers.append(stretch)
            self.up_layers.append(conv) 
Example 2
Project: Computable   Author: ktraunmueller   File: util.py    License: MIT License 6 votes vote down vote up
def cartesian_product(X):
    '''
    Numpy version of itertools.product or pandas.compat.product.
    Sometimes faster (for large inputs)...

    Examples
    --------
    >>> cartesian_product([list('ABC'), [1, 2]])
    [array(['A', 'A', 'B', 'B', 'C', 'C'], dtype='|S1'),
 	array([1, 2, 1, 2, 1, 2])]

    '''

    lenX = np.fromiter((len(x) for x in X), dtype=int)
    cumprodX = np.cumproduct(lenX)

    a = np.roll(cumprodX, 1)
    a[0] = 1

    b = cumprodX[-1] / cumprodX

    return [np.tile(np.repeat(x, b[i]), 
                    np.product(a[i]))
               for i, x in enumerate(X)] 
Example 3
Project: WaveRNN   Author: fatchord   File: fatchord_version.py    License: MIT License 6 votes vote down vote up
def __init__(self, feat_dims, upsample_scales, compute_dims,
                 res_blocks, res_out_dims, pad):
        super().__init__()
        total_scale = np.cumproduct(upsample_scales)[-1]
        self.indent = pad * total_scale
        self.resnet = MelResNet(res_blocks, feat_dims, compute_dims, res_out_dims, pad)
        self.resnet_stretch = Stretch2d(total_scale, 1)
        self.up_layers = nn.ModuleList()
        for scale in upsample_scales:
            k_size = (1, scale * 2 + 1)
            padding = (0, scale)
            stretch = Stretch2d(scale, 1)
            conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=padding, bias=False)
            conv.weight.data.fill_(1. / k_size[1])
            self.up_layers.append(stretch)
            self.up_layers.append(conv) 
Example 4
Project: WaveRNN-Pytorch   Author: G-Wang   File: model.py    License: MIT License 6 votes vote down vote up
def __init__(self, feat_dims, upsample_scales, compute_dims, 
                 res_blocks, res_out_dims, pad) :
        super().__init__()
        total_scale = np.cumproduct(upsample_scales)[-1]
        self.indent = pad * total_scale
        self.resnet = MelResNet(res_blocks, feat_dims, compute_dims, res_out_dims)
        self.resnet_stretch = Stretch2d(total_scale, 1)
        self.up_layers = nn.ModuleList()
        for scale in upsample_scales :
            k_size = (1, scale * 2 + 1)
            padding = (0, scale)
            stretch = Stretch2d(scale, 1)
            conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=padding, bias=False)
            conv.weight.data.fill_(1. / k_size[1])
            self.up_layers.append(stretch)
            self.up_layers.append(conv) 
Example 5
Project: recruit   Author: Frank-qlu   File: test_transform.py    License: Apache License 2.0 5 votes vote down vote up
def test_cython_group_transform_cumprod():
    # see gh-4095
    dtype = np.float64
    pd_op, np_op = groupby.group_cumprod_float64, np.cumproduct
    _check_cython_group_transform_cumulative(pd_op, np_op, dtype) 
Example 6
Project: ODYM   Author: IndEcol   File: ODYM_Functions.py    License: MIT License 5 votes vote down vote up
def Tuple_MI(Tuple, IdxLength): 
    """
    Function to return the absolution position of a multiindex when the index tuple
    and the index hierarchy and size are given.
    Example: Tuple_MI([2,7,3],[100,10,5]) = 138
    Tuple_MI is the inverse of MI_Tuple.
    """
    # First, generate the index position offset values
    A =  IdxLength[1:] +  IdxLength[:1] # Shift 1 to left
    A[-1] = 1 # Replace lowest index by 1
    A.reverse()
    IdxPosOffset = np.cumproduct(A).tolist()
    IdxPosOffset.reverse()
    Position = np.sum([a*b for a,b in zip(Tuple,IdxPosOffset)])
    return Position 
Example 7
Project: Computable   Author: ktraunmueller   File: functions.py    License: MIT License 5 votes vote down vote up
def cumproduct(x, axis=0):
    return np.cumproduct(x, axis) 
Example 8
def test_cython_group_transform_cumprod():
    # see gh-4095
    dtype = np.float64
    pd_op, np_op = groupby.group_cumprod_float64, np.cumproduct
    _check_cython_group_transform_cumulative(pd_op, np_op, dtype) 
Example 9
Project: biskit   Author: graik   File: functions.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cumproduct(x, axis=0):
    return np.cumproduct(x, axis) 
Example 10
Project: Carnets   Author: holzschu   File: test_quantity_non_ufuncs.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_cumproduct(self):
        with pytest.raises(u.UnitsError):
            np.cumproduct(self.q) 
Example 11
Project: recruit   Author: Frank-qlu   File: util.py    License: Apache License 2.0 4 votes vote down vote up
def cartesian_product(X):
    """
    Numpy version of itertools.product or pandas.compat.product.
    Sometimes faster (for large inputs)...

    Parameters
    ----------
    X : list-like of list-likes

    Returns
    -------
    product : list of ndarrays

    Examples
    --------
    >>> cartesian_product([list('ABC'), [1, 2]])
    [array(['A', 'A', 'B', 'B', 'C', 'C'], dtype='|S1'),
    array([1, 2, 1, 2, 1, 2])]

    See Also
    --------
    itertools.product : Cartesian product of input iterables.  Equivalent to
        nested for-loops.
    pandas.compat.product : An alias for itertools.product.
    """
    msg = "Input must be a list-like of list-likes"
    if not is_list_like(X):
        raise TypeError(msg)
    for x in X:
        if not is_list_like(x):
            raise TypeError(msg)

    if len(X) == 0:
        return []

    lenX = np.fromiter((len(x) for x in X), dtype=np.intp)
    cumprodX = np.cumproduct(lenX)

    a = np.roll(cumprodX, 1)
    a[0] = 1

    if cumprodX[-1] != 0:
        b = cumprodX[-1] / cumprodX
    else:
        # if any factor is empty, the cartesian product is empty
        b = np.zeros_like(cumprodX)

    return [np.tile(np.repeat(np.asarray(com.values_from_object(x)), b[i]),
                    np.product(a[i]))
            for i, x in enumerate(X)] 
Example 12
Project: vnpy_crypto   Author: birforce   File: test_transform.py    License: MIT License 4 votes vote down vote up
def test_cython_group_transform_algos():
    # GH 4095
    dtypes = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint32,
              np.uint64, np.float32, np.float64]

    ops = [(groupby.group_cumprod_float64, np.cumproduct, [np.float64]),
           (groupby.group_cumsum, np.cumsum, dtypes)]

    is_datetimelike = False
    for pd_op, np_op, dtypes in ops:
        for dtype in dtypes:
            data = np.array([[1], [2], [3], [4]], dtype=dtype)
            ans = np.zeros_like(data)
            labels = np.array([0, 0, 0, 0], dtype=np.int64)
            pd_op(ans, data, labels, is_datetimelike)
            tm.assert_numpy_array_equal(np_op(data), ans[:, 0],
                                        check_dtype=False)

    # with nans
    labels = np.array([0, 0, 0, 0, 0], dtype=np.int64)

    data = np.array([[1], [2], [3], [np.nan], [4]], dtype='float64')
    actual = np.zeros_like(data)
    actual.fill(np.nan)
    groupby.group_cumprod_float64(actual, data, labels, is_datetimelike)
    expected = np.array([1, 2, 6, np.nan, 24], dtype='float64')
    tm.assert_numpy_array_equal(actual[:, 0], expected)

    actual = np.zeros_like(data)
    actual.fill(np.nan)
    groupby.group_cumsum(actual, data, labels, is_datetimelike)
    expected = np.array([1, 3, 6, np.nan, 10], dtype='float64')
    tm.assert_numpy_array_equal(actual[:, 0], expected)

    # timedelta
    is_datetimelike = True
    data = np.array([np.timedelta64(1, 'ns')] * 5, dtype='m8[ns]')[:, None]
    actual = np.zeros_like(data, dtype='int64')
    groupby.group_cumsum(actual, data.view('int64'), labels,
                         is_datetimelike)
    expected = np.array([np.timedelta64(1, 'ns'), np.timedelta64(
        2, 'ns'), np.timedelta64(3, 'ns'), np.timedelta64(4, 'ns'),
        np.timedelta64(5, 'ns')])
    tm.assert_numpy_array_equal(actual[:, 0].view('m8[ns]'), expected) 
Example 13
Project: vnpy_crypto   Author: birforce   File: util.py    License: MIT License 4 votes vote down vote up
def cartesian_product(X):
    """
    Numpy version of itertools.product or pandas.compat.product.
    Sometimes faster (for large inputs)...

    Parameters
    ----------
    X : list-like of list-likes

    Returns
    -------
    product : list of ndarrays

    Examples
    --------
    >>> cartesian_product([list('ABC'), [1, 2]])
    [array(['A', 'A', 'B', 'B', 'C', 'C'], dtype='|S1'),
    array([1, 2, 1, 2, 1, 2])]

    See also
    --------
    itertools.product : Cartesian product of input iterables.  Equivalent to
        nested for-loops.
    pandas.compat.product : An alias for itertools.product.
    """
    msg = "Input must be a list-like of list-likes"
    if not is_list_like(X):
        raise TypeError(msg)
    for x in X:
        if not is_list_like(x):
            raise TypeError(msg)

    if len(X) == 0:
        return []

    lenX = np.fromiter((len(x) for x in X), dtype=np.intp)
    cumprodX = np.cumproduct(lenX)

    a = np.roll(cumprodX, 1)
    a[0] = 1

    if cumprodX[-1] != 0:
        b = cumprodX[-1] / cumprodX
    else:
        # if any factor is empty, the cartesian product is empty
        b = np.zeros_like(cumprodX)

    return [np.tile(np.repeat(np.asarray(com._values_from_object(x)), b[i]),
                    np.product(a[i]))
            for i, x in enumerate(X)] 
Example 14
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: util.py    License: Apache License 2.0 4 votes vote down vote up
def cartesian_product(X):
    """
    Numpy version of itertools.product or pandas.compat.product.
    Sometimes faster (for large inputs)...

    Parameters
    ----------
    X : list-like of list-likes

    Returns
    -------
    product : list of ndarrays

    Examples
    --------
    >>> cartesian_product([list('ABC'), [1, 2]])
    [array(['A', 'A', 'B', 'B', 'C', 'C'], dtype='|S1'),
    array([1, 2, 1, 2, 1, 2])]

    See Also
    --------
    itertools.product : Cartesian product of input iterables.  Equivalent to
        nested for-loops.
    pandas.compat.product : An alias for itertools.product.
    """
    msg = "Input must be a list-like of list-likes"
    if not is_list_like(X):
        raise TypeError(msg)
    for x in X:
        if not is_list_like(x):
            raise TypeError(msg)

    if len(X) == 0:
        return []

    lenX = np.fromiter((len(x) for x in X), dtype=np.intp)
    cumprodX = np.cumproduct(lenX)

    a = np.roll(cumprodX, 1)
    a[0] = 1

    if cumprodX[-1] != 0:
        b = cumprodX[-1] / cumprodX
    else:
        # if any factor is empty, the cartesian product is empty
        b = np.zeros_like(cumprodX)

    return [np.tile(np.repeat(np.asarray(com.values_from_object(x)), b[i]),
                    np.product(a[i]))
            for i, x in enumerate(X)] 
Example 15
Project: Splunking-Crime   Author: nccgroup   File: util.py    License: GNU Affero General Public License v3.0 4 votes vote down vote up
def cartesian_product(X):
    """
    Numpy version of itertools.product or pandas.compat.product.
    Sometimes faster (for large inputs)...

    Parameters
    ----------
    X : list-like of list-likes

    Returns
    -------
    product : list of ndarrays

    Examples
    --------
    >>> cartesian_product([list('ABC'), [1, 2]])
    [array(['A', 'A', 'B', 'B', 'C', 'C'], dtype='|S1'),
    array([1, 2, 1, 2, 1, 2])]

    See also
    --------
    itertools.product : Cartesian product of input iterables.  Equivalent to
        nested for-loops.
    pandas.compat.product : An alias for itertools.product.
    """
    msg = "Input must be a list-like of list-likes"
    if not is_list_like(X):
        raise TypeError(msg)
    for x in X:
        if not is_list_like(x):
            raise TypeError(msg)

    if len(X) == 0:
        return []

    lenX = np.fromiter((len(x) for x in X), dtype=np.intp)
    cumprodX = np.cumproduct(lenX)

    a = np.roll(cumprodX, 1)
    a[0] = 1

    if cumprodX[-1] != 0:
        b = cumprodX[-1] / cumprodX
    else:
        # if any factor is empty, the cartesian product is empty
        b = np.zeros_like(cumprodX)

    return [np.tile(np.repeat(np.asarray(com._values_from_object(x)), b[i]),
                    np.product(a[i]))
            for i, x in enumerate(X)] 
Example 16
Project: elasticintel   Author: securityclippy   File: test_transform.py    License: GNU General Public License v3.0 4 votes vote down vote up
def test_cython_group_transform_algos(self):
        # GH 4095
        dtypes = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint32,
                  np.uint64, np.float32, np.float64]

        ops = [(groupby.group_cumprod_float64, np.cumproduct, [np.float64]),
               (groupby.group_cumsum, np.cumsum, dtypes)]

        is_datetimelike = False
        for pd_op, np_op, dtypes in ops:
            for dtype in dtypes:
                data = np.array([[1], [2], [3], [4]], dtype=dtype)
                ans = np.zeros_like(data)
                labels = np.array([0, 0, 0, 0], dtype=np.int64)
                pd_op(ans, data, labels, is_datetimelike)
                tm.assert_numpy_array_equal(np_op(data), ans[:, 0],
                                            check_dtype=False)

        # with nans
        labels = np.array([0, 0, 0, 0, 0], dtype=np.int64)

        data = np.array([[1], [2], [3], [np.nan], [4]], dtype='float64')
        actual = np.zeros_like(data)
        actual.fill(np.nan)
        groupby.group_cumprod_float64(actual, data, labels, is_datetimelike)
        expected = np.array([1, 2, 6, np.nan, 24], dtype='float64')
        tm.assert_numpy_array_equal(actual[:, 0], expected)

        actual = np.zeros_like(data)
        actual.fill(np.nan)
        groupby.group_cumsum(actual, data, labels, is_datetimelike)
        expected = np.array([1, 3, 6, np.nan, 10], dtype='float64')
        tm.assert_numpy_array_equal(actual[:, 0], expected)

        # timedelta
        is_datetimelike = True
        data = np.array([np.timedelta64(1, 'ns')] * 5, dtype='m8[ns]')[:, None]
        actual = np.zeros_like(data, dtype='int64')
        groupby.group_cumsum(actual, data.view('int64'), labels,
                             is_datetimelike)
        expected = np.array([np.timedelta64(1, 'ns'), np.timedelta64(
            2, 'ns'), np.timedelta64(3, 'ns'), np.timedelta64(4, 'ns'),
            np.timedelta64(5, 'ns')])
        tm.assert_numpy_array_equal(actual[:, 0].view('m8[ns]'), expected) 
Example 17
Project: elasticintel   Author: securityclippy   File: util.py    License: GNU General Public License v3.0 4 votes vote down vote up
def cartesian_product(X):
    """
    Numpy version of itertools.product or pandas.compat.product.
    Sometimes faster (for large inputs)...

    Parameters
    ----------
    X : list-like of list-likes

    Returns
    -------
    product : list of ndarrays

    Examples
    --------
    >>> cartesian_product([list('ABC'), [1, 2]])
    [array(['A', 'A', 'B', 'B', 'C', 'C'], dtype='|S1'),
    array([1, 2, 1, 2, 1, 2])]

    See also
    --------
    itertools.product : Cartesian product of input iterables.  Equivalent to
        nested for-loops.
    pandas.compat.product : An alias for itertools.product.
    """
    msg = "Input must be a list-like of list-likes"
    if not is_list_like(X):
        raise TypeError(msg)
    for x in X:
        if not is_list_like(x):
            raise TypeError(msg)

    if len(X) == 0:
        return []

    lenX = np.fromiter((len(x) for x in X), dtype=np.intp)
    cumprodX = np.cumproduct(lenX)

    a = np.roll(cumprodX, 1)
    a[0] = 1

    if cumprodX[-1] != 0:
        b = cumprodX[-1] / cumprodX
    else:
        # if any factor is empty, the cartesian product is empty
        b = np.zeros_like(cumprodX)

    return [np.tile(np.repeat(np.asarray(com._values_from_object(x)), b[i]),
                    np.product(a[i]))
            for i, x in enumerate(X)] 
Example 18
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_transform.py    License: MIT License 4 votes vote down vote up
def test_cython_group_transform_algos():
    # GH 4095
    dtypes = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint32,
              np.uint64, np.float32, np.float64]

    ops = [(groupby.group_cumprod_float64, np.cumproduct, [np.float64]),
           (groupby.group_cumsum, np.cumsum, dtypes)]

    is_datetimelike = False
    for pd_op, np_op, dtypes in ops:
        for dtype in dtypes:
            data = np.array([[1], [2], [3], [4]], dtype=dtype)
            ans = np.zeros_like(data)
            labels = np.array([0, 0, 0, 0], dtype=np.int64)
            pd_op(ans, data, labels, is_datetimelike)
            tm.assert_numpy_array_equal(np_op(data), ans[:, 0],
                                        check_dtype=False)

    # with nans
    labels = np.array([0, 0, 0, 0, 0], dtype=np.int64)

    data = np.array([[1], [2], [3], [np.nan], [4]], dtype='float64')
    actual = np.zeros_like(data)
    actual.fill(np.nan)
    groupby.group_cumprod_float64(actual, data, labels, is_datetimelike)
    expected = np.array([1, 2, 6, np.nan, 24], dtype='float64')
    tm.assert_numpy_array_equal(actual[:, 0], expected)

    actual = np.zeros_like(data)
    actual.fill(np.nan)
    groupby.group_cumsum(actual, data, labels, is_datetimelike)
    expected = np.array([1, 3, 6, np.nan, 10], dtype='float64')
    tm.assert_numpy_array_equal(actual[:, 0], expected)

    # timedelta
    is_datetimelike = True
    data = np.array([np.timedelta64(1, 'ns')] * 5, dtype='m8[ns]')[:, None]
    actual = np.zeros_like(data, dtype='int64')
    groupby.group_cumsum(actual, data.view('int64'), labels,
                         is_datetimelike)
    expected = np.array([np.timedelta64(1, 'ns'), np.timedelta64(
        2, 'ns'), np.timedelta64(3, 'ns'), np.timedelta64(4, 'ns'),
        np.timedelta64(5, 'ns')])
    tm.assert_numpy_array_equal(actual[:, 0].view('m8[ns]'), expected)