numpy计算矩阵元素相乘 numpy.prod 您所在的位置:网站首页 matlab求向量所有元素的乘积 numpy计算矩阵元素相乘 numpy.prod

numpy计算矩阵元素相乘 numpy.prod

2023-12-24 03:43| 来源: 网络整理| 查看: 265

numpy.prod(a, axis=None, dtype=None, out=None, keepdims=, initial=, where=)

Return the product of array elements over a given axis.

官方链接

a [array_like] Input data.

axis [None or int or tuple of ints, optional] Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.

dtype [dtype, optional] The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

out [ndarray, optional] Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

keepdims [bool, optional] If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

If the default value is passed, then keepdims will not be passed through to the prod method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

initial [scalar, optional] The starting value for this product. See reduce for details.

where [array_like of bool, optional] Elements to include in the product. See reduce for details.

若指定了axis,把数组a沿着维度axis进行切片,并把切片后得到的一系列数组每个对应位置的元素相乘(element-wise product),如果axis未指定,则对数组进行扁平化后计算所有元素的乘积.

示例1. 把向量或矩阵中所有元素相乘

import numpy as np mat= np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) print(np.prod(mat))

结果:

216

示例2. 指定 axis,实现某一维度的元素相乘

例如对于二维数组,指定axis=0,则按照行进行切片,然后对应位置相乘(element-wise product),得到的是每一列元素相乘的乘积。 相当于np.multiply.reduce(mat,axis=0)

import numpy as np mat= np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) print(np.prod(mat,axis=0)) print(np.multiply.reduce(mat,axis=0))

结果:

[ 1 8 27] [ 1 8 27]

示例3. 指定where,实现只对某些index的元素进行相乘

如果要计算 [1,2,3,4,5,6] 中index为 [0,2,4] 三个元素的乘积

np.prod([1., np.nan, 3.], where=[True, False, True])

结果

3.0


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有