как уменьшить второе измерение в pytorch python tensor operation

#python #pytorch #tensor

#python #pytorch #тензор

Вопрос:

У меня есть приведенный ниже тензор со следующей формой

     seq = dataset['features'][...]
    print(f'shape of seq before unsequeeze {seq.shape}')
    shape of seq before unsequeeze (461, 1024)
  

Я пытаюсь преобразовать форму в (461, 512) Как я должен достичь этого в pytorch tensor operation.

в примерах используется x, как показано ниже,

 import torch 
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.tensor([[0.1,0.8,0.8,0.4,0.9,0.4,0.4,0.5,0.4,0.2,0.3,0.8,0.2,0.7,0.6,0.1,0.2,0.1,0.1,0.4,0.2,0.1,0.0,0.5,0.2,0.4,0.3,0.3,0.7,0.1,0.4,0.6,0.5,1.0,0.1,0.8,0.9,0.0,0.2,0.9,0.8,0.0,0.9,0.7,0.2,0.2,0.9,0.6,0.1,0.2,0.6,0.0,0.1,0.1,0.3,0.5,0.8,0.8,0.4,0.4,0.7,0.7,0.4,0.2,0.1,1.0,0.3,0.8,0.1,0.7,0.7,0.9,0.6,0.3,0.8,0.2,0.9,0.6,0.7,0.8,0.2,0.1,1.0,0.6,0.5,0.5,0.5,0.8,0.8,0.3,0.1,0.2,0.5,0.9,0.6,0.8,0.0,0.6,0.2,0.1,0.8,0.4,0.8,0.5,0.8,0.4,0.7,0.6,0.8,0.1,0.4,0.8,1.0,0.9,0.4,0.4,0.4,0.1,0.7,0.3,0.8,0.6,0.4,0.5,0.9,0.1,0.9,0.7,0.4,0.7,0.1,0.8,0.2,0.2,0.7,0.2,0.9,0.6,0.2,0.9,0.1,0.9,0.2,1.0,0.9,0.6,0.3,0.6,0.9,0.6,0.0,0.3,0.4,0.6,0.7,0.9,0.2,0.6,0.2,0.5,0.3,0.3,0.4,0.4,0.1,0.2,0.6,0.0,0.7,0.5,0.5,0.2,0.5,0.6,0.5,0.5,0.7,0.8,0.4,0.5,0.8,0.8,0.1,0.5,0.7,0.8,0.1,0.1,0.8,0.6,0.6,0.4,1.0,0.4,0.6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.2,0.3,0.8,0.2,0.4,0.2,1.0,1.0,0.7,0.8,0.2,0.5,0.3,0.5,0.4,0.6,0.5,0.3,0.6,0.5,1.0,0.7,0.8,0.9,0.0,0.6,0.3,0.9,0.3,0.9,0.5,0.7,0.5,0.1,0.1,0.3,0.7,0.8,0.1,0.0,0.7,0.5,1.0,0.3,0.8,0.7,0.7,0.2,0.9,0.5,0.6,0.1,0.5,0.5,0.0,0.2,0.7,0.9,0.1,0.9,0.3,0.2]]).to(
    device, dtype=torch.int64
)

x.shape
torch.Size([2, 1024])
  

Мне нужно уменьшить размер объекта до 512, сохраняя размер первого пакета dim в такте,

 x.shape
torch.Size([2, 512])
  

Спасибо

Комментарии:

1. Это зависит от того, как вы хотите его уменьшить. Среднее? Максимум? Мин? Еще одна операция? В конкретном случае, если бы у вас было [[1,2,3,4]] , какими были бы 2 элемента в результирующем тензоре?

2. Я хотел уменьшить только размеры.. Я нашел некоторые результаты, которыми поделился ниже, спасибо за ваш вопрос.

Ответ №1:

 z = torch.narrow(x,1,0,512)
z.shape
torch.Size([2, 512])
  

если вы используете x.unsqueeze(0), то dim 2 потребует изменения,

 z = torch.narrow(x,2,0,512)
  

Комментарии:

1. Вы понимаете, что это только выбор первых 512 элементов? Это точно так же, как z = x[:, 0:512] когда dim=1 .

2. @Berriel Я попробовал один такой синтаксис, позвольте мне попробовать ваше предложение и посмотреть. вы правы, но у меня был unsqueezed X, тогда как работает синтаксис.

3. Дело в том, что это то, чего вы хотели? Уменьшить, выбрав?

4. нужно уменьшить, но у меня было добавлено еще одно измерение.

5. Тогда это было бы x[:, :, :512] , но дело не в этом. Неважно.