- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个 pytorch 稀疏张量,我需要使用此切片 [idx][:,idx]
对行/列进行切片,其中 idx
是索引列表,使用提到的切片在普通浮点张量上产生我想要的结果。是否可以在稀疏张量上应用相同的切片?这里的例子:
#constructing sparse matrix
i = np.array([[0,1,2,2],[0,1,2,1]])
v = np.ones(4)
i = torch.from_numpy(i.astype("int64"))
v = torch.from_numpy(v.astype("float32"))
test1 = torch.sparse.FloatTensor(i, v)
#constructing float tensor
test2 = np.array([[1,0,0],[0,1,0],[0,1,1]])
test2 = autograd.Variable(torch.cuda.FloatTensor(test2), requires_grad=False)
#slicing
idx = [1,2]
print(test2[idx][:,idx])
输出:
Variable containing:
1 0
1 1
[torch.cuda.FloatTensor of size 2x2 (GPU 0)]
我持有一个 250.000 x 250.000 的邻接矩阵,我需要在其中切片 n
行和 n
列,使用随机 idx,通过简单地采样 n
随机 idx。由于数据集太大,转换为更方便的数据类型是不现实的。
我能在test1上得到同样的切片结果吗?有可能吗?如果没有,是否有任何解决方法?
现在我正在使用以下解决方案的“hack”运行我的模型:
idx = sorted(random.sample(range(0, np.shape(test1)[0]), 9000))
test1 = test1AsCsr[idx][:,idx].todense().astype("int32")
test1 = autograd.Variable(torch.cuda.FloatTensor(test1), requires_grad=False)
其中 test1AsCsr 是我的 test1 转换为 numpy CSR 矩阵。该解决方案有效,但速度非常慢,并且使我的 GPU 利用率非常低,因为它需要不断地从 CPU 内存读取/写入。
编辑:结果是非稀疏张量没问题
最佳答案
在下面找到答案,玩几个pytorch方法(torch.eq()
, torch.unique()
, torch.sort()
等)以输出形状为 (len(idx), len(idx))
的紧凑切片张量。
我测试了几个边缘情况(无序 idx
、v
和 0
、i
和多个相同的索引对等),虽然我可能忘记了一些。还应检查性能。
import torch
import numpy as np
def in1D(x, labels):
"""
Sub-optimal equivalent to numpy.in1D().
Hopefully this feature will be properly covered soon
c.f. https://github.com/pytorch/pytorch/issues/3025
Snippet by Aron Barreira Bordin
Args:
x (Tensor): Tensor to search values in
labels (Tensor/list): 1D array of values to search for
Returns:
Tensor: Boolean tensor y of same shape as x, with y[ind] = True if x[ind] in labels
Example:
>>> in1D(torch.FloatTensor([1, 2, 0, 3]), [2, 3])
FloatTensor([False, True, False, True])
"""
mapping = torch.zeros(x.size()).byte()
for label in labels:
mapping = mapping | x.eq(label)
return mapping
def compact1D(x):
"""
"Compact" values 1D uint tensor, so that all values are in [0, max(unique(x))].
Args:
x (Tensor): uint Tensor
Returns:
Tensor: uint Tensor of same shape as x
Example:
>>> densify1D(torch.ByteTensor([5, 8, 7, 3, 8, 42]))
ByteTensor([1, 3, 2, 0, 3, 4])
"""
x_sorted, x_sorted_ind = torch.sort(x, descending=True)
x_sorted_unique, x_sorted_unique_ind = torch.unique(x_sorted, return_inverse=True)
x[x_sorted_ind] = x_sorted_unique_ind
return x
# Input sparse tensor:
i = torch.from_numpy(np.array([[0,1,4,3,2,1],[0,1,3,1,4,1]]).astype("int64"))
v = torch.from_numpy(np.arange(1, 7).astype("float32"))
test1 = torch.sparse.FloatTensor(i, v)
print(test1.to_dense())
# tensor([[ 1., 0., 0., 0., 0.],
# [ 0., 8., 0., 0., 0.],
# [ 0., 0., 0., 0., 5.],
# [ 0., 4., 0., 0., 0.],
# [ 0., 0., 0., 3., 0.]])
# note: test1[1, 1] = v[i[1,:]] + v[i[6,:]] = 2 + 6 = 8
# since both i[1,:] and i[6,:] are [1,1]
# Input slicing indices:
idx = [4,1,3]
# Getting the elements in `i` which correspond to `idx`:
v_idx = in1D(i, idx).byte()
v_idx = v_idx.sum(dim=0).squeeze() == i.size(0) # or `v_idx.all(dim=1)` for pytorch 0.5+
v_idx = v_idx.nonzero().squeeze()
# Slicing `v` and `i` accordingly:
v_sliced = v[v_idx]
i_sliced = i.index_select(dim=1, index=v_idx)
# Building sparse result tensor:
i_sliced[0] = compact1D(i_sliced[0])
i_sliced[1] = compact1D(i_sliced[1])
# To make sure to have a square dense representation:
size_sliced = torch.Size([len(idx), len(idx)])
res = torch.sparse.FloatTensor(i_sliced, v_sliced, size_sliced)
print(res)
# torch.sparse.FloatTensor of size (3,3) with indices:
# tensor([[ 0, 2, 1, 0],
# [ 0, 1, 0, 0]])
# and values:
# tensor([ 2., 3., 4., 6.])
print(res.to_dense())
# tensor([[ 8., 0., 0.],
# [ 4., 0., 0.],
# [ 0., 3., 0.]])
根据相关 open issue 中分享的直觉,这是一个(可能不是最优的并且没有涵盖所有边缘情况)解决方案(希望这个功能很快就会被正确覆盖):
# Constructing a sparse tensor a bit more complicated for the sake of demo:
i = torch.LongTensor([[0, 1, 5, 2]])
v = torch.FloatTensor([[1, 3, 0], [5, 7, 0], [9, 9, 9], [1,2,3]])
test1 = torch.sparse.FloatTensor(i, v)
# note: if you directly have sparse `test1`, you can get `i` and `v`:
# i, v = test1._indices(), test1._values()
# Getting the slicing indices:
idx = [1,2]
# Preparing to slice `v` according to `idx`.
# For that, we gather the list of indices `v_idx` such that i[v_idx[k]] == idx[k]:
i_squeeze = i.squeeze()
v_idx = [(i_squeeze == j).nonzero() for j in idx] # <- doesn't seem optimal...
v_idx = torch.cat(v_idx, dim=1)
# Slicing `v` accordingly:
v_sliced = v[v_idx.squeeze()][:,idx]
# Now defining your resulting sparse tensor.
# I'm not sure what kind of indexing you want, so here are 2 possibilities:
# 1) "Dense" indixing:
test1x = torch.sparse.FloatTensor(torch.arange(v_idx.size(1)).long().unsqueeze(0), v_sliced)
print(test1x)
# torch.sparse.FloatTensor of size (3,2) with indices:
#
# 0 1
# [torch.LongTensor of size (1,2)]
# and values:
#
# 7 0
# 2 3
# [torch.FloatTensor of size (2,2)]
# 2) "Sparse" indixing using the original `idx`:
test1x = torch.sparse.FloatTensor(autograd.Variable(torch.LongTensor(idx)).unsqueeze(0), v_sliced)
# note: this indexing would fail if elements of `idx` were not in `i`.
print(test1x)
# torch.sparse.FloatTensor of size (3,2) with indices:
#
# 1 2
# [torch.LongTensor of size (1,2)]
# and values:
#
# 7 0
# 2 3
# [torch.FloatTensor of size (2,2)]
关于python - 列/行切片 torch 稀疏张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50666440/
我想向 Torch 添加一个损失函数,用于计算预测值和目标值之间的编辑距离。 有没有一种简单的方法来实现这个想法? 还是我必须编写自己的具有向后和向前功能的类? 最佳答案 如果您的标准可以表示为现有模
我如何沿着 torch 中的列求和?我有一个 128*1024 的张量,我想通过对所有行求和得到一个 1*1024 的张量。 例如:一个: 1 2 3 4 5 6 我想要b 5 7 9 最佳答案 为此
阅读pytorch文档后,我仍然需要帮助来理解torch.mm、torch.matmul和torch.mul之间的区别.由于我不完全理解它们,我无法简明扼要地解释这一点。 B = torch.tens
minibatch = torch.Tensor(5, 2, 3,5) m = nn.View(-1):setNumInputDims(1) m:forward(minibatch) 给出一个大小
有两个 PyTorch 存储库: https://github.com/hughperkins/pytorch https://github.com/pytorch/pytorch 第一个显然需要 T
晚上好, 我刚刚安装了 PyTorch 0.4.0,我正在尝试执行第一个教程“什么是 PyTorch?” 我编写了一个 Tutorial.py 文件,我尝试使用 Visual Studio Code
我有一个浮点值列表(或一个 numpy 数组)。我想创建一个包含所有这些值的一维 torch 张量。我可以创建 torch 张量并运行循环来存储值。 但我想知道有没有什么办法,我可以使用列表或数组中的
这是我在将 convertinf DQN 转换为 Double DQN 来解决 cartpole 问题时遇到的问题。我快要弄清楚了。 tensor([0.1205, 0.1207, 0.1197, 0
鉴于: x_batch = torch.tensor([[-0.3, -0.7], [0.3, 0.7], [1.1, -0.7], [-1.1, 0.7]]) 然后申请 torch.sigmoid(
我正在学习一门类(class),该类(class)使用已弃用的 PyTorch 版本,该版本不会根据需要将 torch.int64 更改为 torch.LongTensor。当前引发错误的代码部分是:
我正在尝试从 this repo 运行代码.我通过将 main.py 中的第 39/40 行从更改为禁用了 cuda parser.add_argument('--type', default='to
从 0.4.0 版本开始,可以使用 torch.tensor 和 torch.Tensor 有什么区别?提供这两个非常相似且令人困惑的替代方案的原因是什么? 最佳答案 在 PyTorch 中,torc
用于强化学习的 OpenAI REINFORCE 和 actor-critic 示例具有以下代码: REINFORCE : policy_loss = torch.cat(policy_loss).s
我在装有 CentOS Linux 7.3.1611(核心)操作系统的计算机上使用 Python 3.5.1。 我正在尝试使用 PyTorch 并开始使用 this tutorial . 不幸的是,示
我正在尝试使用 torch.load 加载预训练模型。 我收到以下错误: ModuleNotFoundError: No module named 'utils' 我已通过从命令行打开它来检查我使用的
这篇文章与我之前的 How to define a Python Class which uses R code, but called from rTorch? 有关. 我在 R ( https:/
是否torch.manual_seed包括torch.cuda.manual_seed_all的操作? 如果是,我们可以使用 torch.manual_seed设置种子。否则我们应该调用这两个函数。
我们可以使用 torch.Tensor([1., 2.], device='cuda') 在 GPU 上分配张量.使用这种方式而不是torch.cuda.Tensor([1., 2.])有什么不同吗?
我正在尝试深入了解 PyTorch 张量内存模型的工作原理。 # input numpy array In [91]: arr = np.arange(10, dtype=float32).resha
我同时安装了 python38,37 和 anaconda,操作系统 - win10,x64。 我无法在 py38,37 中安装 torch - 但在 anaconda 中安装了它。 系统环境变量“路
我是一名优秀的程序员,十分优秀!