- Python : 3.8.11
- numpy : 1.20.1
- OS : Ubuntu Kylin 20.04
- Conda : 4.10.1
- jupyter lab : 3.1.4
代码示例
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-69-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])
......
复制代码
学习推荐
- Python文档 - English
- Python文档 - 中文
- Python规范 PEP
- Python规范 google版
- Python 源码
- Python PEP
- 优麒麟
- 掘金平台
- gitee平台
Python具有开源、跨平台、解释型、交互式等特性,值得学习。
Python的设计哲学:优雅,明确,简单。提倡用一种方法,最好是只有一种方法来做一件事。
代码的书写要遵守规范,这样有助于沟通和理解。
每种语言都有独特的思想,初学者需要转变思维、踏实践行、坚持积累。