import numpy as np
import torch
a = np.array([2,3.3])
b = torch.from_numpy(a)print("b: \t", b)
c = np.ones([2,3])
d = torch.from_numpy(c)print("d: \t", d)
import torch
a = torch.tensor([1.2,3]).type()print("a:\t", a)
torch.set_default_tensor_type(torch.DoubleTensor)# 设定tensor的类型为:DoubleTensor
b = torch.tensor([1.2,3]).type()print("b: \t", b)
a: torch.FloatTensor
b: torch.DoubleTensor
rand/rand_like, randint:
import torch
# rand() 0~1之间
a = torch.rand(3,3)print('a:\t', a)
b = torch.rand_like(a)# 接收的是一个torchprint("b:\t", b)# 均匀采样0~10的Tensor randint()只能采样整数
c = torch.randint(1,10,[3,3])print("c \t", c)
a: tensor([[0.5405,0.0994,0.7603],[0.9873,0.6534,0.0490],[0.7819,0.9018,0.1276]])
b: tensor([[0.4911,0.0674,0.2491],[0.7798,0.0695,0.4160],[0.9018,0.7866,0.1199]])
c tensor([[7,8,4],[5,5,1],[9,8,4]])
randn 正态分布 N(0, 1)
import torch
a = torch.randn(3,3)print("a:\t", a)# 自定义均值 和 方差
b = torch.normal(mean=torch.full([10],0), std=torch.arange(1,0,-0.1))print("b:\t", b)
import torch
# [2,3]相当于一个 shape , 7:表示赋值
a = torch.full([2,3],7)print('a:\t', a)
b = torch.full([],7)# dim =0 print("b:\t", b)
c = torch.full([1],7)# dim =1print("c:\t", c)
import torch
# linspace(): 0-10都包含进来了 step数量值 例:steps=4 等分切出4个值
a = torch.linspace(0,10, steps=4)print("a:\t", a)
b = torch.linspace(0,10, steps=10)print("b:\t", b)
c = torch.linspace(0,10, steps=11)print("c:\t", c )# logspace(): logspace的base参数可以设置为2, 10, e等底数
d = torch.logspace(0,-1, steps=10)#以为底数 10的0次方~10的-1次方print("d:\t", d)
import torch
# 全部是one的矩阵
a = torch.ones(3,3)print("a:\t", a)# 全部是zero矩阵
b = torch.zeros(3,3)print("b:\t", b)# eye: 单位矩阵
c = torch.eye(3,4)print("c:\t", c)
d = torch.eye(3)print("d:\t", d)
e = torch.ones_like(a)print("e:\t", e)
a = torch.randperm(10)# 0~9 的1随机索引print("a:\t", a)
a: tensor([9,1,4,5,2,8,6,0,3,7])
import torch
a = torch.rand(2,3)
b = torch.rand(2,2)print("a, b : \t", a, b)
idx = torch.randperm(2)print("idx:\t", idx)print("a[idx]:\t", a[idx])# 相当于索引一行 print("b[idx]:\t", b[idx])# 相当于索引一行
a, b : tensor([[0.1115,0.4137,0.6847],[0.0791,0.4034,0.0941]]) tensor([[0.5270,0.5309],[0.2291,0.2432]])
idx: tensor([1,0])
a[idx]: tensor([[0.0791,0.4034,0.0941],[0.1115,0.4137,0.6847]])
b[idx]: tensor([[0.2291,0.2432],[0.5270,0.5309]])