[英]how to assign value to a tensor using index
我定義了四個分別代表 index_x、index_y、index_z 和 value 的張量,並使用這三個索引為新張量賦值。 為什么兩次作業的結果不同?
import torch
import numpy as np
import random
import os
def seed_torch(seed=0):
random.seed(seed)
np.random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
seed_torch(1)
a_list, b_list, c_list = [], [], []
for i in range(0, 512*512):
a_ = random.randint(0, 399)
b_ = random.randint(0, 399)
c_ = random.randint(0, 199)
a_list.append(a_)
b_list.append(b_)
c_list.append(c_)
a = torch.tensor(a_list)
b = torch.tensor(b_list)
c = torch.tensor(c_list)
v = torch.rand(512*512)
matrix1 = torch.zeros(400,400,200)
matrix2 = torch.zeros(400,400,200)
index=[a,b,c]
matrix1[index]=v
matrix2[index]=v
m = matrix1 - matrix2
print(m.sum())
打印(m.sum())不為零
無法添加評論,但是當我運行您的確切代碼時,它會在我的機器上返回tensor(0.)
,因此它似乎工作得很好。
另外,只是一個提示,而不是 for 循環
a_list, b_list, c_list = [], [], []
for i in range(0, 512*512):
a_ = random.randint(0, 399)
b_ = random.randint(0, 399)
c_ = random.randint(0, 199)
a_list.append(a_)
b_list.append(b_)
c_list.append(c_)
a = torch.tensor(a_list)
b = torch.tensor(b_list)
c = torch.tensor(c_list)
你也可以這樣做:
a = torch.randint(400, (512*512,))
b = torch.randint(400, (512*512,))
c = torch.randint(200, (512*512,))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.