zoukankan      html  css  js  c++  java
  • 【pytorch】torch.manual_seed()用法详解

    描述

    设置CPU生成随机数的种子,方便下次复现实验结果。

    语法

    torch.manual_seed(seed) → torch._C.Generator

    参数

    seed (int) – CPU生成随机数的种子。取值范围为[-0x8000000000000000, 0xffffffffffffffff],十进制是[-9223372036854775808, 18446744073709551615],超出该范围将触发RuntimeError报错。

    返回

    返回一个torch.Generator对象。

    示例

    设置随机种子

    # test.py
    import torch
    torch.manual_seed(0)
    print(torch.rand(1)) # 返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数
    

    每次运行test.py的输出结果都是一样:

    tensor([0.4963])
    

    没有随机种子

    # test.py
    import torch
    
    print(torch.rand(1)) # 返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数
    

    每次运行test.py的输出结果都不相同:

    tensor([0.2079])
    ----------------------------------
    tensor([0.6536])
    ----------------------------------
    tensor([0.2735])
    

    注意

    设置随机种子后,是每次运行test.py文件的输出结果都一样,而不是每次随机函数生成的结果一样:

    # test.py
    import torch
    torch.manual_seed(0)
    print(torch.rand(1))
    print(torch.rand(1))
    

    输出:

    tensor([0.4963])
    tensor([0.7682])
    

    可以看到两次打印torch.rand(1)函数生成的结果是不一样的,但如果你再运行test.py,还是会打印:

    tensor([0.4963])
    tensor([0.7682])
    

    但是,如果你就是想要每次运行随机函数生成的结果都一样,那你可以在每个随机函数前都设置一模一样的随机种子:

    # test.py
    import torch
    torch.manual_seed(0)
    print(torch.rand(1))
    torch.manual_seed(0)
    print(torch.rand(1))
    

    输出:

    tensor([0.4963])
    tensor([0.4963])
    

    引用

    https://pytorch.org/docs/stable/generated/torch.manual_seed.html

    相关

    【python】random.seed()用法详解

  • 相关阅读:
    第4章.计算节点
    Eclipse插件ViPlugin2.X的破解方法
    金刚经
    js
    C++ 重写重载重定义区别
    string::substr()简介
    信息熵与二进制
    一个简单的条件概率问题
    HPLINUX hplinux 安装升级 至 jdk1.8
    linux 解压命令
  • 原文地址:https://www.cnblogs.com/ghgxj/p/14491426.html
Copyright © 2011-2022 走看看