电子科技大学人工智能综合实验二1.1

1.1 数据操作

In [1]:

 
import torch
torch.manual_seed(0)#设置 (CPU) 生成随机数的种子,一旦固定种子,后面依次生成的随机数其实都是固定的
torch.cuda.manual_seed(0)#为GPU生成随机数种子
print(torch.__version__)
1.9.0

1.1.1 创建Tensor

创建一个5x3的未初始化的Tensor

In [2]:

x = torch.empty(5, 3)
print(x)
tensor([[1.6932e+22, 3.0728e+32, 1.1093e+27],
        [7.4111e+34, 1.7936e+25, 6.2618e+22],
        [4.7428e+30, 2.9514e+29, 1.4607e-19],
        [1.8888e+31, 3.0308e+24, 1.1542e+19],
        [4.7429e+30, 1.6098e+19, 4.7429e+30]])

创建一个5x3的随机初始化的Tensor:

In [3]:

x = torch.rand(5, 3)
print(x)
tensor([[0.4963, 0.7682, 0.0885],
        [0.1320, 0.3074, 0.6341],
        [0.4901, 0.8964, 0.4556],
        [0.6323, 0.3489, 0.4017],
        [0.0223, 0.1689, 0.2939]])

创建一个5x3的long型全0的Tensor:

In [4]:

x = torch.zeros(5, 3, dtype=torch.long)
print(x)
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

直接根据数据创建:

In [5]:

 
x = torch.tensor([5.5, 3])
print(x)
tensor([5.5000, 3.0000])

还可以通过现有的Tensor来创建,此方法会默认重用输入Tensor的一些属性,例如数据类型,除非自定义数据类型。

In [6]:

x = x.new_ones(5, 3, dtype=torch.float64)      # 返回的tensor默认具有相同的torch.dtype和torch.device
print(x)
x = torch.randn_like(x, dtype=torch.float)    # 指定新的数据类型
print(x)                                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值