pytorch 张量

例程1:

import torch
t2=torch.tensor([[0,1,2],[3,4,5]])
print(t2)
print('数据={}'.format(t2))
print(t2.reshape(3,2))
print(t2+1)
print('大小={}'.format(t2.size()))
print('维度={}'.format(t2.dim()))
print('元素的个数={}'.format(t2.numel()))
print('元素的类型={}'.format(t2.dtype))

运行结果:

tensor([[0, 1, 2],
        [3, 4, 5]])
数据=tensor([[0, 1, 2],
        [3, 4, 5]])
tensor([[0, 1],
        [2, 3],
        [4, 5]])
tensor([[1, 2, 3],
        [4, 5, 6]])
大小=torch.Size([2, 3])
维度=2
元素的个数=6
元素的类型=torch.int64

构造随机变量

torch.bernoulli() 可以生成元素值为1或者0的张量

例程2.1 

probs=torch.full((3,4),0.5)
print(probs)
z1=torch.bernoulli(probs)
print(z1)

运行结果

 torch.multinomial(x,y)可以生成元素值{0,1,...n-1} 的张量。函数有两个参数,分别表示结果张量中元素出现的可能性张量和表示对每个概率分布抽样的次数(通常为1)。

例程2.2

weights = torch.tensor([[1,100],[100,1],[1,1]],dtype=torch.float32)
z2=torch.multinomial(weights,1)
print(weights)
print(z2)

运行结果

 2.3 

low表示均匀分布最小值,high表示均匀分布最大值。

z=torch.randint(low=0,high=4,size=(3,4))
print(z)
z1=torch.randint_like(torch.ones(3,4),low=0,high=4)
print(z1)

运行结果:

重新排量张量元素

例程3.1 

import torch
tc = torch.arange(12)
print('tc={}'.format(tc))
t43=tc.reshape(4,3)#会变换为矩阵
print('t43={}'.format(t43))
t322=tc.reshape(3,2,2)#不会变换为矩阵
print('t322={}'.format(tc))

 

例程3.2

z=torch.arange(24).reshape(2,-1,4)#大小(2,3,4)
print(z)
t=torch.arange(24).reshape(2,1,3,1,4)#大小(2,1,3,1,4)
print(t)
print(t.squeeze())#消除张量中大小为1的维度

 运行结果:

例程3.3

t= torch.arange(24).reshape(2,3,4)#大小(2,3,4)
print(t)
print(t.unsqueeze(dim=2))#大小为(2,1,3,4)

运行结果

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值