5

I don't know how to convert the PyTorch method adaptive_avg_pool2d to Keras or TensorFlow. Anyone can help? PyTorch mehod is

adaptive_avg_pool2d(14,[14])

I tried to use the average pooling, the reshape the tensor in Keras, but got the error:

ValueError: total size of new array must be unchanged

Fábio Perez
  • 23,850
  • 22
  • 76
  • 100
user10282036
  • 321
  • 2
  • 5
  • 13

1 Answers1

1

I'm not sure if I understood your question, but in PyTorch, you pass the spatial dimensions to AdaptiveAvgPool2d. For instance, if you want to have an output sized 5x7, you can use nn.AdaptiveAvgPool2d((5,7)).

If you want a global average pooling layer, you can use nn.AdaptiveAvgPool2d(1). In Keras you can just use GlobalAveragePooling2D.

For other output sizes in Keras, you need to use AveragePooling2D, but you can't specify the output shape directly. You need to calculate/define the pool_size, stride, and padding parameters depending on how you want the output shape. If you need help with the calculations, check this page of CS231n course.

Fábio Perez
  • 23,850
  • 22
  • 76
  • 100
  • 1
    yes, I want to get the same with with Pytorch adaptive_avg_pool2d using keras, for example, adaptive_avg_pool2d(X, [14,14]) will output 14,14,2048, but the original shape is 21,45,2048, I want to reshape it to 14,14,2048 using keras code. Thankyou. – user10282036 Oct 03 '18 at 13:00
  • Another, the output shape is always the same, 14,14,2048, no matter how the input shape. Any good suggestions? Thanks. – user10282036 Oct 03 '18 at 13:18
  • You may use the information of the previous layer and define the pooling layer based on that info. – Fábio Perez Oct 03 '18 at 13:39
  • Thank you, Fábio Perez. Sorry, I am not familiar with pytorch and keras. Would you please give a specific example. Currently, I am using resnet101, original shape is 21,45,2048, Using pytorch adaptive_avg_pool2d(X, [14,14]), the output shape is 14,14,2048. so I am using AveragePooling2D((3, 3), name='avg_pool')(x) in keras, the shape changed to 7,15,2048, need change shape to 14,14,2048. – user10282036 Oct 03 '18 at 14:01
  • Thanks you for your answer, it is great help, Fábio Perez – user10282036 Oct 04 '18 at 00:56
  • you can create a custom layer on top of the AveragePooling2D layer for that purpose – York Yang Sep 12 '20 at 06:49