一、公共部分
1、torch.linespace
返回一维张量,在start和end之间(包括start也包括end)的均匀间隔的steps个点,长度为steps。
print(torch.linspace(1,10,3)) #输出tensor([ 1.0000, 5.5000, 10.0000])
print(torch.linspace(-10,10,10)) #tensor([-10.0000, -7.7778, -5.5556, -3.3333, -1.1111, 1.1111, 3.3333, 5.5556, 7.7778, 10.0000])
2、torch.from_array(ndarray)->Tensor
返回的张量和ndarray共享一片存储区域,修改一个会导致另一个的修改。返回的张量不能改变大小
a=np.array([[1,2,3],[4,5,6]])
b=torch.from_numpy(a)
print(b)#输出tensor([[1, 2, 3],
#[4, 5, 6]], dtype=torch.int32)
b[0][0]=11
print(a)#输出[[11 2 3] #[ 4 5 6]]
3、torch.numel(input)->int
返回tensor中元素的总个数
a=torch.rand(1,2,3,4)
print(torch.numel(a))#输出24
4、torch.logspace(start,end,steps,out=None)
生成10的start次方和10的end次方的steps个数据点
print(torch.logspace(-10,10,10))#输出tensor([1.0000e-10, 1.6681e-08, 2.7826e-06, 4.6416e-04, 7.7426e-02, 1.2915e+01,
#2.1544e+03, 3.5938e+05, 5.9948e+07, 1.0000e+10])
5、torch.rand(*size)
生成均值为0,方差为1的高斯分布数据
print(torch.randn((2,3)))
6、torch.randn(*size)
生成均值为0,方差为1的高斯分布数据
print(torch.randn((2,3)))
7、torch.arange(start,end,step=1,out=None)
返回一维张量,在[start,end)之间
torch.range(start,end,step=1,out=None)没什么区别,只不过数据包含end
print(torch.arange(1,89,9))#输出tensor([ 1, 10, 19, 28, 37, 46, 55, 64, 73, 82])
8、近似值 floor ceil round trunc frac
import torch
a = torch.tensor(3.14)
print(a.floor()) # tensor(3.)
print(a.ceil()) # tensor(4.)
print(a.trunc()) # tensor(3.)
print(a.frac()) # tensor(0.1400)
b = torch.tensor(3.499) # 四舍五入 小于3.5 返回3
print(b.round()) # tensor(3.)
9、数据比较 eq(a,b) equal(a,a) ga(a,0)
import torch
a = torch.randn(4, 10)
print(a > 0)
print(torch.gt(a, 0)) # 效果是和a>0一致 可类比到> >= < <= != ==
b = torch.ones(2, 3)
c = torch.randn(2, 3)
b_c_eq = torch.eq(b, c) # 判断b,c对应位置元素是否相等 相等的元素按位置返回1
print(b_c_eq)
b_c_equal = torch.equal(b, c) # 判断b,c整体是否相等,相等返回True
print(b_c_equal)
a_a_equal = torch.equal(a, a) # 返回True
print(a_a_equal)
10、torch.where
cond = torch.ByteTensor([[1, 1], [1, 0]])
print(cond.shape)
a = torch.tensor([[1, 2], [3, 4]])
print(a.shape)
b = torch.tensor([[5, 6], [7, 8]])
print(b.shape)
a_b_where = torch.where(cond, a, b) # tensor([[1,2],[3,8]]) cond中是条件,为1的地方代表a中同位置元素
print(a_b_where) # torch.where可以用GPU高度并行运算 自己用python写的话是CPU运行慢
二、索引 切片 连接 换位
2.1 torch.cat(tensors,dim=0,out=None)
第⼀个参数tensors是你想要连接的若⼲个张量,按你所传⼊的顺序进⾏连接,注意每⼀个张量需要形状相同,或者更准确的说,进⾏⾏连接的张量要求列数相同,进⾏列连接的张量要求⾏数相同
第⼆个参数dim表⽰维度,dim=0则表⽰按⾏连接,dim=1表⽰按列连接
a=torch.tensor([[1,2,3,4],[1,2,3,4]])
b=torch.tensor([[1,2,3,4,5],[1,2,3,4