Numpy dot 矩阵乘积

举报
千江有水千江月 发表于 2021/12/20 12:20:29 2021/12/20
【摘要】 环境信息ModelArtsCodeLabConda-python3numpy 1.19.1  代码示例import numpy as npa = np.array([[1,2,3,4],[5,6,7,8]])b = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])aarray([[1, 2, 3, 4], [5, 6, 7, 8]])...

环境信息

  • ModelArts
    • CodeLab
      • Conda-python3
        • numpy 1.19.1

代码示例

import numpy as np
a = np.array([[1,2,3,4],[5,6,7,8]])
b = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
a

array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
b

array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
a.shape,b.shape

((2, 4), (4, 3))
# 第一个矩阵的列数(column)和第二个矩阵的行数(row)相同
np.dot(a,b)

array([[ 70,  80,  90],
       [158, 184, 210]])
np.dot(b,a)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-20-e6bd3a7b39a0> in <module>()
----> 1 np.dot(b,a)

<__array_function__ internals> in dot(*args, **kwargs)

ValueError: shapes (4,3) and (2,4) not aligned: 3 (dim 1) != 2 (dim 0)

源码学习

help(np.dot)

Help on function dot in module numpy:

dot(...)
    dot(a, b, out=None)
    
    Dot product of two arrays. Specifically,
    
    - If both `a` and `b` are 1-D arrays, it is inner product of vectors
      (without complex conjugation).
    
    - If both `a` and `b` are 2-D arrays, it is matrix multiplication,
      but using :func:`matmul` or ``a @ b`` is preferred.
    
    - If either `a` or `b` is 0-D (scalar), it is equivalent to :func:`multiply`
      and using ``numpy.multiply(a, b)`` or ``a * b`` is preferred.
    
    - If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
      the last axis of `a` and `b`.
    
    - If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
      sum product over the last axis of `a` and the second-to-last axis of `b`::
    
        dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

......

备注

  1. 欢迎各位同学一起来交流学习心得^_^
  2. 在线课程、沙箱实验、认证、大赛、论坛和直播,其中包含了许多优质的内容,推荐了解与学习。
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。