pytorch学习一Tensor的创建

张量Tensors

判断是否是张量

torch.is_tensor(obj)

张量个数

torch.numel(a)
a = torch.randn(2,3,4,2)
print(torch.numel(a)) #48

张量的创建

torch.eye

创建2维张量,对角线位置全为1,其它位置全为0
torch.eye(n, m=None, out=None)
参数:
n 行数
m 列数,如果为None,则默认为n
out 结果张量

print(torch.eye(3))

1 0 0
0 1 0
0 0 1

torch.from_numpy

将numpy.ndarray转换为pytorch的Tensor

a = numpy.array([2,3,4])
t = torch.from_numpy(a)
print(t)

tensor([2, 3, 4], dtype=torch.int32)

t[0 = -1
print(a)

[-1 3 4]

torch.linspace

torch.linspace(start, end, steps=100, out=None)
返回一个1维张量
参数:

  • start(float)-序列的第一个值
  • end(float)-序列的最后一个值
  • steps(int)-在start和end间生成的样本数
  • out-结果张量
a = torch.linspace(3,10,steps=5)
print(a)

tensor([ 3.0000, 6.5000, 10.0000])

torch.ones

返回一个全为1的张量

a = torch.ones(2,3)
print(a)

tensor([[1., 1., 1.],
[1., 1., 1.]])

torch.rand

返回一个从区间(0,1)的均匀分布中抽取的随机数的张量

torch.randn

返回从标准正态分布(均值为0,方差为 1)的随机数的张量

torch.randperm

返回从0到n-1的随机整数的张量

torch.arange

参数

  • start (float) – 序列的起始点
  • end (float) – 序列的终止点
  • step (float) – 相邻点的间隔大小
  • out (Tensor, optional) – 结果张量
a = torch.arange(1,4,0.5)
print(a)

tensor([1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000])

torch.zeros

返回一个标量0的张量

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值