1

I am looking for a way to reduce the length of a 1D tensor by applying a pooling operation. How can I do it? If I apply MaxPool1d, I get the error max_pool1d() input tensor must have 2 or 3 dimensions but got 1.

Here is my code:

import numpy as np
import torch

A = np.random.rand(768)
m = nn.MaxPool1d(4,4)
A_tensor = torch.from_numpy(A)
output = m(A_tensor)
albus_c
  • 6,292
  • 14
  • 36
  • 77

3 Answers3

1

Your initialization is fine, you've defined the first two parameters of nn.MaxPool1d: kernel_size and stride. For one-dimensional max-pooling both should be integers, not tuples.

The issue is with your input, it should be two-dimensional (the batch axis is missing):

>>> m = nn.MaxPool1d(4, 4)
>>> A_tensor = torch.rand(1, 768)

Then inference will result in:

>>> output = m(A_tensor)
>>> output.shape
torch.Size([1, 192])
Ivan
  • 34,531
  • 8
  • 55
  • 100
0

I think you meant the following instead:

m = nn.MaxPool1d((4,), 4)

As mentioned in the docs, the arguments are:

torch.nn.MaxPool1d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

As you can see, it's one kernel_size, it's not something like kernel_size1 kernel_size2. Instead it's just only kernel_size

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

For posterity: the solution is to reshape the tensor using A_tensor.reshape(768,1).

albus_c
  • 6,292
  • 14
  • 36
  • 77
  • 2
    This is incorrect, look at the shape of the resulting tensor: it's empty. The extra dimension should be added *first*, not *last*. – Ivan Sep 12 '21 at 09:43