文章目录
1.torch的range和arange
代码如下(示例):
>>> y=torch.range(1,6)
>>> y
tensor([1., 2., 3., 4., 5., 6.])
>>> y.dtype
torch.float32
>>> z=torch.arange(1,6)
>>> z
tensor([1, 2, 3, 4, 5])
>>> z.dtype
torch.int64
总结:
torch.range(start=1, end=6) 的结果是会包含end的,
而torch.arange(start=1, end=6)的结果并不包含end。
两者创建的tensor的类型也不一样。
2.torch.cat()
代码如下(示例):
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y),dim=0) # 按行合并
torch.cat((X, Y), dim=1) # 按列合并
结果:
(tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 2., 1., 4., 3.],
[ 1., 2., 3., 4.],
[ 4., 3., 2., 1.]]),
tensor([[ 0., 1., 2., 3., 2., 1., 4., 3.],
[ 4., 5., 6., 7., 1., 2., 3., 4.],
[ 8., 9., 10., 11., 4., 3., 2., 1.]]))
3.torch.normal()、torch.rand() 和 torch.randn()
1.torch.normal()
normal(mean, std, *, generator=None, out=None)
# 该函数返回从单独的正态分布中提取的随机数的张量,该正态分布的均值是mean,标准差是std。
# 用法一:
# 我们从一个标准正态分布N~(0,1),提取一个2x2的矩阵
torch.normal(mean=0.,std=1.,size=(2,2))
# 情况二:
# 我们也可以让每一个值服从不同的正态分布,我们还是生成2x2的矩阵:
torch.normal(mean=torch.arange(4.),std=torch.arange(1.,0.6,-0.1)).reshape(2,2)
2.torch.rand(*sizes, out=None)
torch.randn(*sizes, out=None)
# rand是随机生成服从均匀分布的数据,返回值为张量。
# randn是随机生成服从正态分布的数据,返回值为张量。
import torch
x = torch.randn(5, 5)
print(x)
x = torch.rand(5, 5)
print(x)
# 结果:
tensor([[-1.2067e+00, -1.7496e-01, -8.8117e-01, 1.6632e-01, 6.3906e-01],
[ 3.7858e-02, 2.8564e-02, -3.1674e-02, -2.3180e+00, 1.5624e+00],
[ 1.8508e+00, -2.8605e-01, -1.0858e+00, -1.6341e-02, -9.7166e-01],
[-1.2331e+00, 6.5460e-01, -3.2398e-01, -6.5933e-01, -8.2312e-01],
[-9.6841e-02, -1.1673e+00, -1.8217e-03, -1.4767e+00, -2.0411e-02]])
tensor([[0.5935, 0.0334, 0.3593, 0.0768, 0.8266],
[0.1705, 0.0965, 0.9235, 0.5899, 0.5111],
[0.0445, 0.2402, 0.0333, 0.9654, 0.4318],
[0.1791, 0.1183, 0.1795, 0.4961, 0.5653],
[0.7089, 0.5844, 0.2965, 0.2817, 0.1237]])
4.pytorch中的numel函数
# 获取tensor中一共包含多少个元素
import torch
x = torch.randn(3,3)
print("number elements of x is ",x.numel())
y = torch.randn(3,10,5)
print("number elements of y is ",y.numel())
# 结果:
number elements of x is 9
number elements of y is 150
5.torch.mul()、torch.mm()、torch.dot()、torch.mv()和torch.matmul()
- torch.mul()是矩阵的点乘,即对应的位相乘,要求shape一样, 返回的还是个矩阵
- torch.mm()是矩阵正常的矩阵相乘,(a, b)* ( b, c ) = ( a, c )
- torch.dot()类似于mul(),它是向量(即只能是一维的张量)的对应位相乘再求和,返回一个tensor数值
- torch.mv()是矩阵和向量相乘,类似于torch.mm()
import torch
A = torch.tensor([[1,2,3],
[4,5,6]])
x = torch.tensor([1,2,3])
torch.mv(A, x) # 第一个参数是矩阵,第二个参数只能是一维向量
输出:tensor([14, 32])
- torch.matmul()有两种情况:
5.1 对于维数相同的张量
A.shape =(b,m,n);B.shape = (b,n,k)
numpy.matmul(A,B) 结果shape为(b,m,k)
要求第一维度相同,后两个维度能满足矩阵相乘条件。
5.2 对于维数不一样的张量
比如 A.shape =(m,n); B.shape = (b,n,k); C.shape=(k,l)
numpy.matmul(A,B) 结果shape为(b,m,k)
numpy.matmul(B,C) 结果shape为(b,n,l)
2D张量要和3D张量的后两个维度满足矩阵相乘条件。