torch.manual_seed()解析

本文详细介绍了torch.manual_seed()的作用,通过多个测试案例展示了设置和不设置seed时,生成随机数的不同行为。设置seed可以确保在复现实验结果时,每次运行的随机数序列一致。不设置seed时,每次运行会得到不同的随机数。理解这一概念对于深度学习模型的可重复性至关重要。
摘要由CSDN通过智能技术生成

torch.manual_seed() 介绍

  1. 概述

    用于设置CPU生成随机数的种子。返回一个torch.Generator对象。此时接下来运行随机函数生成的随机数都不会发生变化,方便论文复现结果。

  2. 语法

    torch.manual_seed(seed)
    
  3. 参数

    seed (int) – The desired seed. Value must be within the inclusive range [-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]. Otherwise, a RuntimeError is raised. Negative inputs are remapped to positive values with the formula 0xffff_ffff_ffff_ffff + seed.

测试一:不设置seed,生成随机数

代码如下:

import torch

print(torch.rand(1))  # 随机生成[0, 1)的数

每次运行结果都不同:

tensor([0.1580])
tensor([0.9103])
if __name__ == "__main__": args = parse_args() print("A list all args: \n======================") pprint(vars(args)) print() #设置 CPU 生成随机数的种子 ,方便下次复现实验结果。 torch.manual_seed(args.seed) np.random.seed(args.seed) #路径拼接文件路径,可以传入多个路径 PATH = os.path.join("resources", args.data) EMBEDDING_PATH = "resources/" static_feat = ["sex", "age", "pur_power"] dynamic_feat = ["category", "shop", "brand"] device = torch.device("cuda" if torch.cuda.is_available() else "cpu") n_epochs = args.n_epochs batch_size = args.batch_size lr = args.lr item_embed_size = args.embed_size feat_embed_size = args.embed_size hidden_size = (256, 128) #CosineEmbeddingLoss余弦相似度损失函数,用于判断输入的两个向量是否相似 #BCEWithLogitsLoss就是把Sigmoid-BCELoss合成一步,计算交叉损失熵 criterion = ( nn.CosineEmbeddingLoss() if args.loss == "cosine" else nn.BCEWithLogitsLoss() ) #lower将字符串中的所有大写字母转换为小写字母 criterion_type = ( "cosine" if "cosine" in criterion.__class__.__name__.lower() else "bce" ) neg_label = -1. if criterion_type == "cosine" else 0. neg_item = args.neg_item columns = ["user", "item", "label", "time", "sex", "age", "pur_power", "category", "shop", "brand"] ( n_users, n_items, train_user_consumed, eval_user_consumed, train_data, eval_data, user_map, item_map, feat_map#feature是特征比如数据集里 age, brand 之类的 ) = process_feat_data( PATH, columns, test_size=0.2, time_col="time", static_feat=static_feat, dynamic_feat=dynamic_feat ) print(f"n_users: {n_users}, n_items: {n_items}, " f"train_shape: {train_data.shape}, eval_shape: {eval_data.shape}") train_user, train_item, train_label = sample_items_random( train_data, n_items, train_user_consumed, neg_label, neg_item ) eval_user, eval_item, eval_label = sample_items_random( eval_d
04-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值