Numpy 与Pytorch 关于一维数组的处理(2)

1 一维数组在点积的右边

Numpy中的一维数组 B = np.array([7, 8]) ,表现形式是行向量,参与运算的时候,表现为二维列向量。

A = np.array([[1, 2], [3, 4], [5, 6]])
print(A.shape)        # (3 , 2)
B = np.array([7, 8])  # (2,)
print(np.dot(A, B))   # (3,)

(3, 2)
(2,)
[23 53 83] (3,)

上述相同的代表,在Pytorch中表现如何呢,将上式上的np.array换成torch.tensor

import torch
A = torch.tensor([[1, 2], [3, 4], [5, 6]])
print(A.shape)
B = torch.tensor([7, 8])
print(B)
C = torch.mm(A, B)
print(C, C.shape)

torch.Size([3, 2])
tensor([7, 8])
Traceback (most recent call last):
C = torch.mm(A, B)
RuntimeError: mat2 must be a matrix

出现了报错,B不是一个矩阵,
为了达到,跟上述一致的结果,采用的方法是,torch.unsqueeze

import torch
A = torch.tensor([[1, 2], [3, 4], [5, 6]])
print(A.shape)
B = torch.tensor([7, 8]).unsqueeze(1)
print(B)
C = torch.mm(A, B)
print(C, C.shape)

torch.Size([3, 2])
tensor(
[[7],
[8]])
tensor(
[[23],
[53],
[83]]) torch.Size([3, 1])

到此为止,两个框架得到了,一致的结果。 Pytorch中先将一维数组array转化为二维数组matrix,然后,再进行运算。

2 一维数组在点积的左边

import numpy as np
X = np.array([1.0, 0.5])
W1 = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
B1 = np.array([0.1, 0.2, 0.3])

print(X.shape)  # (2,)
print(W1.shape)  # (2, 3)
print(B1.shape)  # (3,)

A1 = np.dot(X, W1) + B1
print(A1)

(2,)
(2, 3)
(3,)
[0.3 0.7 1.1]

同样的方式,转化为Pytorch的Tensor格式:

import torch
X = torch.tensor([1.0, 0.5])
W1 = torch.tensor([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
B1 = torch.tensor([0.1, 0.2, 0.3])

print(X.shape) 
print(W1.shape) 
print(B1.shape)  

A1 = torch.mm(X, W1) + B1
print(A1)

torch.Size([2])
torch.Size([2, 3])
torch.Size([3])
Traceback (most recent call last):
File “d:/MyDesktop/my/t.py”, line 534, in
A1 = torch.mm(X, W1) + B1
RuntimeError: self must be a matrix

报错的结果也是说,A不是一个matrix, 怎么处理才能达到如上同样的结果呢? pytorch.unsqueeze()

import torch
X = torch.tensor([1.0, 0.5]).unsqueeze(dim=0)
W1 = torch.tensor([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
B1 = torch.tensor([0.1, 0.2, 0.3])

print(X.shape)  # (2,)
print(W1.shape)  # (2, 3)
print(B1.shape)  # (3,)

A1 = torch.mm(X, W1) + B1
print(A1)

结果如下:
torch.Size([1, 2])
torch.Size([2, 3])
torch.Size([3])
tensor([[0.3000, 0.7000, 1.1000]])

小结

矩阵的乘法,遵守,(m,p).dot(p,n) 得到的结果同( m,n ),Numpy的语法结构,对于一维数组同矩阵的乘法不那么的严谨,而Pytorch中则会直接报错。
Pytorch中,则对于,一维数组同矩阵的乘法,如果在右边,则需要 unsqueeze(dim=1),如果在左边,则需要.unsqueeze(dim=0)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

developer_wgl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值