当前位置: 首页>>代码示例>>Python>>正文


Python numpy.product方法代码示例

本文整理汇总了Python中numpy.product方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.product方法的具体用法?Python numpy.product怎么用?Python numpy.product使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.product方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_basic_use

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def test_basic_use(self, simple_linear_model):
        """ Test the basic use of `ConstantParameter` using the Python API """
        model = simple_linear_model
        # Add two scenarios
        scA = Scenario(model, 'Scenario A', size=2)
        scB = Scenario(model, 'Scenario B', size=5)

        p = ConstantParameter(model, np.pi, name='pi', comment='Mmmmm Pi!')

        assert not p.is_variable
        assert p.double_size == 1
        assert p.integer_size == 0

        model.setup()
        ts = model.timestepper.current
        # Now ensure the appropriate value is returned for all scenarios
        for i, (a, b) in enumerate(itertools.product(range(scA.size), range(scB.size))):
            si = ScenarioIndex(i, np.array([a, b], dtype=np.int32))
            np.testing.assert_allclose(p.value(ts, si), np.pi) 
开发者ID:pywr,项目名称:pywr,代码行数:21,代码来源:test_parameters.py

示例2: test_parameter_constant_scenario

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def test_parameter_constant_scenario(simple_linear_model):
    """
    Test ConstantScenarioParameter

    """
    model = simple_linear_model
    # Add two scenarios
    scA = Scenario(model, 'Scenario A', size=2)
    scB = Scenario(model, 'Scenario B', size=5)

    p = ConstantScenarioParameter(model, scB, np.arange(scB.size, dtype=np.float64))
    model.setup()
    ts = model.timestepper.current
    # Now ensure the appropriate value is returned for the Scenario B indices.
    for i, (a, b) in enumerate(itertools.product(range(scA.size), range(scB.size))):
        si = ScenarioIndex(i, np.array([a, b], dtype=np.int32))
        np.testing.assert_allclose(p.value(ts, si), float(b)) 
开发者ID:pywr,项目名称:pywr,代码行数:19,代码来源:test_parameters.py

示例3: test_load

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def test_load(self, simple_linear_model):
        """ Test load from JSON dict"""
        model = simple_linear_model
        data = {
            "type": "aggregated",
            "agg_func": "product",
            "parameters": [
                0.8,
                {
                    "type": "monthlyprofile",
                    "values": list(range(12))
                }
            ]
        }

        p = load_parameter(model, data)
        # Correct instance is loaded
        assert isinstance(p, AggregatedParameter)

        @assert_rec(model, p)
        def expected(timestep, scenario_index):
            return (timestep.month - 1) * 0.8

        model.run() 
开发者ID:pywr,项目名称:pywr,代码行数:26,代码来源:test_parameters.py

示例4: _load_one_param_type

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def _load_one_param_type(self, conv_params, param_category, suffix):
        """Deserializes the weights from a file stream in the DarkNet order.

        Keyword arguments:
        conv_params -- a ConvParams object
        param_category -- the category of parameters to be created ('bn' or 'conv')
        suffix -- a string determining the sub-type of above param_category (e.g.,
        'weights' or 'bias')
        """
        param_name = conv_params.generate_param_name(param_category, suffix)
        channels_out, channels_in, filter_h, filter_w = conv_params.conv_weight_dims
        if param_category == 'bn':
            param_shape = [channels_out]
        elif param_category == 'conv':
            if suffix == 'weights':
                param_shape = [channels_out, channels_in, filter_h, filter_w]
            elif suffix == 'bias':
                param_shape = [channels_out]
        param_size = np.product(np.array(param_shape))
        param_data = np.ndarray(
            shape=param_shape,
            dtype='float32',
            buffer=self.weights_file.read(param_size * 4))
        param_data = param_data.flatten().astype(float)
        return param_name, param_data, param_shape 
开发者ID:aimuch,项目名称:iAI,代码行数:27,代码来源:yolov3_to_onnx.py

示例5: evaluate

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def evaluate(self, variable_values):
        """
        Evaluate this polynomial for a given set of variable values.

        Parameters
        ----------
        variable_values : array-like
            An object that can be indexed so that `variable_values[i]` gives the
            numerical value for i-th variable (x_i).

        Returns
        -------
        float or complex
            Depending on the types of the coefficients and `variable_values`.
        """
        #FUTURE: make this function smarter (Russian peasant)
        ret = 0
        for ivar, coeff in self.coeffs.items():
            ret += coeff * _np.product([variable_values[i] for i in ivar])
        return ret 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:22,代码来源:polynomial.py

示例6: tensor_product_block_dims

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def tensor_product_block_dims(self, iTPB):  # unused
        """
        Get the dimension corresponding to each label in the
        `iTBP`-th tensor-product block.  The dimension of the
        entire block is the product of these.

        Parameters
        ----------
        iTPD : int
           The index of the tensor product block whose state-space
           dimensions you wish to retrieve.

        Returns
        -------
        tuple
        """
        return tuple((self.labeldims[lbl] for lbl in self.labels[iTPB])) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:19,代码来源:labeldicts.py

示例7: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def __init__(self, povm_to_marginalize, all_sslbls, sslbls_after_marginalizing):
        """ TODO: docstring """
        self.povm_to_marginalize = povm_to_marginalize

        if isinstance(all_sslbls, _ld.StateSpaceLabels):
            assert(len(all_sslbls.labels) == 1), "all_sslbls should only have a single tensor product block!"
            all_sslbls = all_sslbls.labels[0]

        #now all_sslbls is a tuple of labels, like sslbls_after_marginalizing
        self.sslbls_to_marginalize = all_sslbls
        self.sslbls_after_marginalizing = sslbls_after_marginalizing
        indices_to_keep = set([list(all_sslbls).index(l) for l in sslbls_after_marginalizing])
        indices_to_remove = set(range(len(all_sslbls))) - indices_to_keep
        self.indices_to_marginalize = sorted(indices_to_remove, reverse=True)

        elements_to_sum = {}
        for k in self.povm_to_marginalize.keys():
            mk = self.marginalize_effect_label(k)
            if mk in elements_to_sum:
                elements_to_sum[mk].append(k)
            else:
                elements_to_sum[mk] = [k]
        self._elements_to_sum = {k: tuple(v) for k, v in elements_to_sum.items()}  # convert to tuples
        super(MarginalizedPOVM, self).__init__(self.povm_to_marginalize.dim, self.povm_to_marginalize._evotype) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:26,代码来源:povm.py

示例8: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [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) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:27,代码来源:slowreplib.py

示例9: adjoint_acton

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def adjoint_acton(self, state):
        """ Act the adjoint of this gate map on an input state """
        #NOTE: Same as acton except uses 'adjoint_acton(...)' below
        output_state = DMStateRep(_np.zeros(state.base.shape, 'd'))
        offset = self.offset  # if relToBlock else self.offset (relToBlock == False here)

        for b in _itertools.product(*self.basisInds_noop_blankaction):  # zeros in all action-index locations
            vec_index_noop = _np.dot(self.multipliers, tuple(b))
            inds = []
            for op_b in _itertools.product(*self.basisInds_action):
                vec_index = vec_index_noop
                for i, bInd in zip(self.actionInds, op_b):
                    #b[i] = bInd #don't need to do this; just update vec_index:
                    vec_index += self.multipliers[i] * bInd
                inds.append(offset + vec_index)
            embedded_instate = DMStateRep(state.base[inds])
            embedded_outstate = self.embedded.adjoint_acton(embedded_instate)
            output_state.base[inds] += embedded_outstate.base

        #act on other blocks trivially:
        self._acton_other_blocks_trivially(output_state, state)
        return output_state 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:24,代码来源:slowreplib.py

示例10: acton

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def acton(self, state):
        output_state = SVStateRep(_np.zeros(state.base.shape, complex))
        offset = self.offset  # if relToBlock else self.offset (relToBlock == False here)

        for b in _itertools.product(*self.basisInds_noop_blankaction):  # zeros in all action-index locations
            vec_index_noop = _np.dot(self.multipliers, tuple(b))
            inds = []
            for op_b in _itertools.product(*self.basisInds_action):
                vec_index = vec_index_noop
                for i, bInd in zip(self.actionInds, op_b):
                    #b[i] = bInd #don't need to do this; just update vec_index:
                    vec_index += self.multipliers[i] * bInd
                inds.append(offset + vec_index)
            embedded_instate = SVStateRep(state.base[inds])
            embedded_outstate = self.embedded.acton(embedded_instate)
            output_state.base[inds] += embedded_outstate.base

        #act on other blocks trivially:
        self._acton_other_blocks_trivially(output_state, state)
        return output_state 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:22,代码来源:slowreplib.py

示例11: dot

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def dot(self, other):
        """
        Computes the Hilbert-Schmidt dot product (normed to 1) between this
        Pauli operator and `other`.

        Parameters
        ----------
        other : NQPauliOp
            The other operator to take a dot product with.

        Returns
        -------
        integer
            Either 0, 1, or -1.
        """
        assert(len(self) == len(other)), "Length mismatch!"
        if other.rep == self.rep:
            return self.sign * other.sign
        else:
            return 0 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:22,代码来源:pauliobjs.py

示例12: affine

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def affine(h_num_hidden, h_W_init_fn, h_b_init_fn):

    def compile_fn(di, dh):
        m = dh['num_hidden']
        shape = di['in'].get_shape().as_list()
        n = np.product(shape[1:])
        W = tf.Variable(dh['W_init_fn']([n, m]))
        b = tf.Variable(dh['b_init_fn']([m]))

        def forward_fn(di):
            In = di['in']
            if len(shape) > 2:
                In = tf.reshape(In, [-1, n])
            return {'out': tf.add(tf.matmul(In, W), b)}

        return forward_fn

    return siso_tensorflow_module(
        'Affine', compile_fn, {
            'num_hidden': h_num_hidden,
            'W_init_fn': h_W_init_fn,
            'b_init_fn': h_b_init_fn
        }) 
开发者ID:negrinho,项目名称:deep_architect,代码行数:25,代码来源:dnn.py

示例13: affine_simplified

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def affine_simplified(h_num_hidden):

    def compile_fn(di, dh):
        shape = di['in'].get_shape().as_list()
        n = np.product(shape[1:])

        def forward_fn(di):
            In = di['in']
            if len(shape) > 2:
                In = tf.reshape(In, [-1, n])
            return {'out': tf.layers.dense(In, dh['num_hidden'])}

        return forward_fn

    return siso_tensorflow_module('AffineSimplified', compile_fn,
                                  {'num_hidden': h_num_hidden}) 
开发者ID:negrinho,项目名称:deep_architect,代码行数:18,代码来源:dnn.py

示例14: cost_adjust

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def cost_adjust(self,r,z,rvar,zvar,shape,var_axes):
        """
        Computes the cost adjustment term for the
        Bethe Free Energy:
            
            J = beta*[log(2*pi*rvar) + ((z-r)**2 + xvar)/rvar]
            
        where beta = 1 for complex problems and 0 for real problems
        """    
        J0 = np.mean(np.log(2*np.pi*rvar))*np.product(shape)
        rvar_rep = common.repeat_axes(rvar,shape,\
                                      var_axes,rep=False)
        J1 = np.sum(np.abs(r-z)**2/rvar_rep)
        J2 = np.mean(zvar/rvar)*np.product(shape)
        J = J0 + J1 + J2
        if not self.is_complex:
            J = J / 2
        return J 
开发者ID:GAMPTeam,项目名称:vampyre,代码行数:20,代码来源:gamp.py

示例15: repeat_sum

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import product [as 别名]
def repeat_sum(u,shape,rep_axes):
    """
    Computes sum of a repeated matrix
    
    In effect, this routine computes 
    code:`np.sum(repeat(u,shape,rep_axes))`.  However, it performs
    this without having to perform the full repetition.
    
    """
    # Must convert to np.array to perform slicing
    shape_vec = np.array(shape,dtype=int)
    rep_vec = np.array(rep_axes,dtype=int)
    
    # repeat and sum
    urep = repeat_axes(u,shape,rep_axes,rep=False)
    usum = np.sum(urep)*np.product(shape_vec[rep_vec])
    return usum 
开发者ID:GAMPTeam,项目名称:vampyre,代码行数:19,代码来源:utils.py


注:本文中的numpy.product方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。