简体   繁体   English

将滑动 window 应用到 torch.tensor 并调整张量初始大小

[英]Appling sliding window to torch.tensor and adjusting tensor initial size

Looking for a simpler way of torch.tensor modification.寻找更简单的 torch.tensor 修改方式。 Probably there is a way to apply Unfold to initial tensor directly.可能有一种方法可以直接将展开应用于初始张量。

input:输入:

tensor([[0., 1., 2.],
        [3., 4., 5.],
        [6., 7., 8.]])

output: output:

tensor([[0., 1., 3., 4.],
        [1., 2., 4., 5.],
        [3., 4., 6., 7.],
        [4., 5., 7., 8.]])

possible solution:可能的解决方案:

import torch

t = torch.linspace(0., 8., steps=9)

t1 = t.reshape(3,3) # starting point

t2 = torch.flatten(t1)

t3 = t2.reshape(1, 1, 1, -1) # unfold works with 4D only

unfold = torch.nn.Unfold(kernel_size=(1, 5), dilation=1)

t4 = unfold(t3)

indices = torch.tensor([0, 1, 3, 4]) # deleting 3d (or middle) row and 3d (middle) column

t5 = torch.index_select(torch.index_select(t4.squeeze(), 0, indices), 1, indices)

t5

You can use unfold , but in a simpler manner:您可以使用unfold ,但以更简单的方式:

import torch
import torch.nn.functional as nnf

t1 = torch.arange(9.).reshape(3,3)  # initial tensor
out = nnf.unfold(t1[None, None, ...], kernel_size=2, padding=0)  # that's it. done.

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

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