python - 如何使用索引为张量赋值
问题描述
我定义了四个张量,分别代表 index_x、index_y、index_z 和 value,并使用这三个索引将 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())
print(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,))
推荐阅读
- java - 为什么这个强引用的对象会被回收
- powerbi - 如何合并来自不同数据库的两个或多个表以在 PowerBI 中生成报告?
- powerbi - Powerbi 中使用过滤器的动态百分比变化
- php - 如何使用laravel中另一个表中的外键获取所需的列
- reactjs - 月范围过滤器反应
- windows - PyCharm 启动错误:无法检测 Windows Subsystem for Linux (WSL) Ubuntu 上的图形环境
- django - 使用 Ajax 和 Django 添加注释
- php - 如何修复“此路线不支持 GET 方法。支持的方法:POST。'?
- java - 为什么直接写入文件时PrintWriter中没有autoflush参数?
- python - 用 pandas 计算分组的总数