• 【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()用法详解

  • 相关阅读:
    docker在Linux环境下的安装
    docker在Windows环境下的安装
    tcpdump和windump
    Centos7下安装Elasticsearch 5.6.6
    使用concurrent.futures模块并发,实现进程池、线程池
    Nginx配置Gzip
    linux常用命令
    Linux下文档与目录结构
    快速读取大文件的几种方式
    linux 将大文件分解为多个小文件
  • 原文地址:https://www.cnblogs.com/ghgxj/p/14491426.html
Copyright © 2020-2023  润新知