【Numpy】详解 Numpy 中的各种”乘法“操作

本文详细介绍了Numpy中的乘法操作,包括np.multiply的逐元素乘法,np.matmul的矩阵乘法,以及np.dot的多种运算方式。每个函数都配以注释和示例,帮助读者理解它们的区别和应用场景。
摘要由CSDN通过智能技术生成

前言

文章主要介绍了 Numpy 中几个乘法函数的使用方法,包含较多的示例代码,建议点击目录直达所需内容,所有的示例代码可以 点击此处 免费获取。

在以下示例代码中,均已事前导入Numpy:import numpy as np

环境

  • Windows 10
  • Python 3.7.0
  • Numpy 1.18.1

np.multiply(x1, x2)

函数注释

该函数是逐元素乘法,如果两个参数x1x2的shape不同,将会进行 broadcastable

Multiply arguments element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays to be multiplied. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
Returns
-------
y : ndarray
The product of x1 and x2, element-wise.
This is a scalar if both x1 and x2 are scalars.

用法示例

【注】该函数的两个参数的位置可以替换,不影响最后的运算结果。

  1. x1 x2都是 scalar,返回两者的乘积,也是 scalar

    print(np.multiply(2, 4))
    print(np.multiply(2, 3.8))
    ---output---
    8
    7.6
    
  2. x1scalarx2 为 array_like,此时为矩阵与数的乘法,该数与矩阵中每一元素相乘,最后返回同shape的 array。按照文档中的描述,应该是先将scalar 广播(broadcast)为与另一参数同shape的矩阵,再进行逐元素的乘法。

    print(np.multiply(2, [3, 4, 8]))
    print(np.multiply(2, np.arange(0, 8).reshape((2, 2, 2))))
    ---output---
    [ 6  8 16]
    [[[ 0  2]
      [ 4  6]]
    
     [[ 8 10]
      [12 14]]]
    
  3. x1 x2都是 array_like, 如果两个的shape相同,直接逐元素相乘再返回即可,否则需要进行广播(broadcast)。可以广播的最基本的条件就是两者shape的最后一个维度必须是相同的,具体的广播策略比较复杂,通过几个例子来试着理解一下。
    【例1】 (2, 2, 3) , (2, 3) —>(2, 2, 3)

    x1 = np.arange(0, 12).reshape((2, 2, 3))
    x2 = np.arange(0, 6).reshape(2, 3)
    print("-----x1------", x1.shape, "\n", x1)
    print("-----x2------", x2.shape, "\n", x2)
    print("-----multiply(x1, x2)------", np.multiply(x1, x2).shape, "\n", np.multiply(x1, x2))
    ---output---
    -----x1------ (2, 2, 3) 
     [[[ 0  1  2]
      [ 3  4  5]]
    
     [[ 6  7  8]
      [ 9 10 11]]]
    -----x2------ (2, 3) 
     [[0 1 2]
     [3 4 5]]
    -----multiply(x1, x2)------ (2, 2, 3) 
     [[[ 0  1  4]
      [ 9 16 25]]
    
     [[ 0  7 16]
      [27 40 55]]]
    

    【例2】(2, 2, 1, 3) ,(2, 3) —>(2, 2, 2, 3)

    x1 = np.arange(0, 12).reshape((2, 2, 1, 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值