两个numpy的向量相乘并生成矩阵

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

1. 错误方法

a*b
array([ 5, 12, 21, 32])
a@b
70

因为在numpy中,array([1, 2, 3, 4])既是行向量也是列向量。

符号*表示逐个元素相乘。

numpy.dot()和符号@表示矩阵乘法,但是它们会自动把参与矩阵乘法的两个array变成第一个为行向量,第二个为列向量的形式进行相乘。

2. 正确方法

2.1 方法1:矩阵外积

函数np.outer()为矩阵的外积运算。

np.outer(a, b)
array([[ 5,  6,  7,  8],
       [10, 12, 14, 16],
       [15, 18, 21, 24],
       [20, 24, 28, 32]])

2.2 方法2:将向量转换为二维数组

  1. 将a和b都变成二维数组然后再使用符号@做矩阵乘法
a.reshape(len(a), 1) @ b.reshape(1, len(b))
array([[ 5,  6,  7,  8],
       [10, 12, 14, 16],
       [15, 18, 21, 24],
       [20, 24, 28, 32]])
  1. 将a和b都变成二维数组然后再使用np.matmul方法做矩阵乘法
np.matmul(a.reshape(len(a), 1), b.reshape(1, len(b)))
array([[ 5,  6,  7,  8],
       [10, 12, 14, 16],
       [15, 18, 21, 24],
       [20, 24, 28, 32]])
  1. 将a和b都变成二维数组然后再使用np.dot()方法做矩阵乘法
np.dot(a.reshape(len(a), 1), b.reshape(1, len(b)))
array([[ 5,  6,  7,  8],
       [10, 12, 14, 16],
       [15, 18, 21, 24],
       [20, 24, 28, 32]])

参考文章

How to multiply two vector and get a matrix?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值