【NumPy】矩阵乘法与点乘

1. Numpy.dot()

  1. 一维矩阵:计算内积
    • dot( 1 x n , 1 x n ) = 一个数
  2. 二维矩阵:线性代数矩阵相乘(n x m)·(m x s)
    • dot( n x m , m x s ) = n x s
import numpy as np

# 1. 一维矩阵:计算内积
# 1 x 3 
one_and_three_a = np.array([1, 2, 3])
# 1 x 3
one_and_three_b = np.array([4, 5, 6])
# 1 x 3  dot  1 x 3
result_1x3_dot_1x3 = np.dot(one_and_three_a, one_and_three_b)
print(result_1x3_dot_1x3)
# print(f'{one_and_three_a} \n   x\n {one_and_three_b}:\n   = \n {result_1x3_dot_1x3}')

# 2. 二维矩阵:线性代数矩阵相乘
# 2 x 3
two_and_three = np.array([[1, 2, 3], [4, 5, 6]])
# 3 x 2
three_and_two = np.array([[1, 2], [3, 4], [5, 6]])
# 2 x 3  dot  3 x 2
result_2x3_dot_3x2 = np.dot(two_and_three, three_and_two)
print(result_2x3_dot_3x2)
# print(f'{two_and_three} \n   x\n {three_and_two}:\n   = \n {result_2x3_dot_3x2}\n\n')

[[22 28]
[49 64]]
32

2. Numpy.multiply() 和 " * "——对应元素相乘

两个矩阵必须行列相同

  1. 矩阵维数:

    multiply( n x m , n x m ) = n x m

    ( n x m ) * ( n x m ) = n x m

  2. 示例:

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

    = [[1x5, 2x6], [3x7, 4x8]]

    = [[5, 12], [21, 32]]

import numpy as np

# 2 x 3
two_and_three_a = np.array([[1, 2, 3], [4, 5, 6]])
two_and_three_b = np.array([[7, 8, 9], [10, 11, 12]])

# 对应元素相乘
result_a = two_and_three_a * two_and_three_b
print(result_a)

# 对应元素相乘
result_b = np.multiply(two_and_three_a, two_and_three_b)
print(result_b)

[[ 7 16 27]
[40 55 72]]
[[ 7 16 27]
[40 55 72]]

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值