1.定义Tensors:
torch.zeros(5,3):
生成一个5*3的全是0的张量。
>>>torch.zeros(5,3)
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
>>>torch.zeros(5)
tensor([0., 0., 0., 0., 0.])
x = torch.empty(5,3):
生成一个5*3的矩阵(未初始化)
>>>torch.empty(5,3)
tensor([[6.5122e-39, 0.0000e+00, 6.5122e-39],
[0.0000e+00, 6.5122e-39, 0.0000e+00],
[6.5122e-39, 0.0000e+00, 6.5122e-39],
[0.0000e+00, 6.5122e-39, 0.0000e+00],
[6.5122e-39, 0.0000e+00, 6.5122e-39]])
torch.rand(5,3)
:生成一个5*3的随机初始化的矩阵
>>>torch.rand(5,3)
tensor([[0.5079, 0.1242, 0.4101],
[0.6364, 0.1674, 0.2489],
[0.2376, 0.4224, 0.9875],
[0.9710, 0.0372, 0.5550],
[0.1719, 0.0052, 0.6556]])
torch.randn(5,3)
:生成一个5*3的标准正态分布N(0,1)的随机数。(里面的数有正有负)
>>>torch.randn(5,3)
tensor([[-2.2971, 0.2847, -0.4776],
[ 0.5875, -0.5847, -0.1421],
[-0.6393, -0.2509, 0.2685],
[-2.3049, 0.6499, 1.9672],
[-0.2830, -0.0089, 1.4584]])
torch.tensor([5.5,3])
创建tensor并使用现有数据初始化:
>>>torch.tensor([5.5,3])
tensor([5.5000, 3.0000])
torch.ones(5,3)
:创建一个5*3的全是1的张量
`
>>>torch.ones(5,3)
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
根据已有张量来生成一个大小(维度)一样的张量。
>>>x = torch.ones(5,3) #生成一个5*3的全是1的张量。
>>>torch.randn_like(x,dtype=torch.double) #生成一个维度和x一样的矩阵,但是数值和数值的类型不一样。
tensor([[-0.1901, 0.5882, 1.4445],
[ 1.4619, -0.2704, 0.4470],
[ 1.5624, -0.6046, -0.9181],
[-1.5480, 0.2511, 1.9130],
[-2.1051, -1.4523, -0.3877]], dtype=torch.float64)
x.size()
输出x的尺寸
>>>x.size()
torch.Size([5, 3])
torch.arange(1,6,1)
torch.arange(start=0, end, step=1)返回一个从start到end的序列,步长为step,可以只输入一个end参数,就跟python的range()一样。[start,end)
左闭右开。
>>>torch.arange(1,5,1)
tensor([1, 2, 3, 4])
torch.full((2,3),4)
生成一个两行三列的全是4的张量。
>>>torch.full((2,3),4)
tensor([[4., 4., 4.],
[4., 4., 4.]])
2.张量的操作:
张量的加法:torch.add(x,y)
>>>x=torch.ones(5,3)
>>>y=torch.rand(5,3)
>>>torch.add(x,y)
tensor([[1.1259, 1.6325, 1.5112],
[1.9166, 1.9107, 1.7514],
[1.1589, 1.9283, 1.4688],
[1.4948, 1.3876, 1.7834],
[1.6360, 1.7465, 1.8248]])
.y.add_(x)
任何 以_
结尾的操作都会用结果替换原变量. 例如: x.copy_(y)
, x.t_()
, 都会改变 x
.
>>>y.add_(x) # y加上x之后将值赋给
>>>print(y)
tensor([[ 0.7808, -1.4388, 0.3151],
[-0.0076, 1.0716, -0.8465],
[-0.8175, 0.3625, -0.2005],
[ 0.2435, 0.8512, 0.7142],
[ 1.4737, -0.8545, 2.4833]])
torch.view()
相当于numpy的reshape
>>>x = torch.randn(4, 4)
>>>y = x.view(16)
>>>z = x.view(-1, 8) # size -1 从其他维度推断
>>>print(x.size(), y.size(), z.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2,8])
3、Torch Tensor与Numpy的互相转换
Tensor-->Numpy
:将Tensor类型转换成Numpy类型,我们可以直接使用.numpy
来转换,转换后,numpy类型的变量会和原来的Tensor共用底层内存地址,所以改变其中一个,另外一个也会改变。
>>>a=torch.randn(5)
>>>a
tensor([-0.2814, -1.8397, 0.1669, -1.4093, -0.4031])
>>>b = a.numpy()
>>>b
array([-0.28141832, -1.8396882 , 0.16691928, -1.409325 , -0.40305737],
dtype=float32)
Numpy-->Tensor
>>>import numpy as np
>>>a = np.ones(5)
>>>b = torch.from_numpy(a)
>>>np.add(a, 1, out=a)
>>>print(a)
>>>print(b)
[1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
暂时就这些了,假如遇到什么问题,可以自己直接去pytorch官网搜索