简体   繁体   English

如何从更大的 pytorch 张量中提取张量到 numpy arrays 或列表

[英]How to extract tensors to numpy arrays or lists from a larger pytorch tensor

I have a list of pytorch tensors as shown below:我有一个 pytorch 张量列表,如下所示:

data = [[tensor([0, 0, 0]), tensor([1, 2, 3])],
        [tensor([0, 0, 0]), tensor([4, 5, 6])]]

Now this is just a sample data, the actual one is quite large but the structure is similar.现在这只是一个示例数据,实际数据很大但结构相似。

Question: I want to extract the tensor([1, 2, 3]) , tensor([4, 5, 6]) ie, the index 1 tensors from data to either a numpy array or a list in flattened form.问题:我想提取tensor([1, 2, 3])tensor([4, 5, 6])即索引 1 张量从data到 numpy 数组或扁平形式的列表。

Expected Output:预期 Output:

out = array([1, 2, 3, 4, 5, 6])

OR或者

out = [1, 2, 3, 4, 5, 6]

I have tried several ways one including map function like:我尝试了几种方法,其中一种包括map function,例如:

map(lambda x: x[1].numpy(), data)

This gives:这给出了:

[array([1, 2, 3]),
 array([4, 5, 6])]

And I'm unable to get the desired result with any other method I'm using.而且我无法使用我正在使用的任何其他方法获得所需的结果。 Any help would be appreciated.任何帮助,将不胜感激。

Thanks in advance:)提前致谢:)

OK, you can just do this.好的,你可以这样做。

out = np.concatenate(list(map(lambda x: x[1].numpy(), data)))

You can convert a nested list of tensors to a tensor/numpy array with a nested stack:您可以将张量的嵌套列表转换为具有嵌套堆栈的张量/numpy 数组:

data = np.stack([np.stack([d for d in d_]) for d_ in data])

You can then easily index this, and concatenate the output:然后,您可以轻松地对其进行索引,并连接 output:

>>> np.concatenate(data[:,1])
array([[1, 2, 3],
       [4, 5, 6]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM