zoukankan      html  css  js  c++  java
  • 关于python中的矩阵乘法(array和mat类型)

    一、关于python中的矩阵乘法,我们一般有两种数据格式可以实现:np.array()类型和np.mat()类型;

    对于这两种数据类型均有三种操作方式:

    (1)乘号 *

    (2)np.dot()

    (3)np.multiply()

    而这三种操作方式在操作这两种数据格式时又有点区别,下面一一列出来:

    import numpy as np 
    
    #np.array() type
    #1. np.dot()
    a = np.array([[1 , 2] , [3 , 4]] , dtype = np.float)
    b = np.array([[1 , 2] , [3 , 4]] , dtype = np.float)
    c = np.dot(a , b)
    print(c)
    #output:[[  7.  10.],[ 15.  22.]]
    
    #2. *
    d = a * b
    print(d)
    #output:[[  1.   4.],[  9.  16.]]
    
    #3. np.multiply()
    e = np.multiply(a , b)
    print(e)
    #output:[[  1.   4.],[  9.  16.]]
    
    #np.mat() type
    #4. *
    A = np.mat([[1 , 2] , [3 , 4]] , dtype = np.float)
    B = np.mat([[1 , 2] , [3 , 4]] , dtype = np.float)
    C = A * B
    print(C)
    #output:[[  7.  10.],[ 15.  22.]]
    
    #5. np.dot()
    D = np.dot(A , B)
    print(D)
    #output:[[  7.  10.],[ 15.  22.]]
    
    #6. np.multiply()
    E = np.multiply(A , B)
    print(E)
    #output:[[  1.   4.],[  9.  16.]]
    
    # np.mat() * np.array()
    F = A * a;
    print(F)
    #output:[[  7.  10.],[ 15.  22.]]

    由上面的代码可以总结如下:

    (1)np.dot()对于这两种数据格式均为矩阵乘法;

    (2)np.multiply()对于这两种数据格式均为按元素相乘;

    (3)符号“*”对于array类型是矩阵乘法,对于mat类型是按元素类型相乘,而当一个array类型乘上一个mat类型时,则为矩阵乘法;

    二、pytorch中的乘法:

    (1)矩阵相乘:torch.mm();

    (2)对应元素点乘:torch.mul();

  • 相关阅读:
    竞赛中遇到的英文单词集锦
    #复习 搜索与图论:排列数字、走迷宫~ 20.8.20起
    #容斥原理 20.9.10
    #sort :快速排序、第k个数 20.09.12
    #STL #unordered_map : C++11 unordered_map详细介绍
    Java 面试必备(字符串专题)
    JAVA面试必备题(垃圾回收专题)
    Collection框架的结构(面试重点)
    CSS 层级样式表
    window搭建mongodb副本集
  • 原文地址:https://www.cnblogs.com/zf-blog/p/10018452.html
Copyright © 2011-2022 走看看