1# Copyright 2020 Huawei Technologies Co., Ltd 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================ 15import numpy as np 16import pytest 17 18import mindspore.context as context 19import mindspore.nn as nn 20from mindspore import Tensor 21 22context.set_context(mode=context.GRAPH_MODE, device_target='CPU') 23 24 25@pytest.mark.level0 26@pytest.mark.platform_x86_cpu 27@pytest.mark.env_onecard 28def test_avgpool_k2s1pv(): 29 x = np.arange(1 * 1 * 6 * 6).reshape((1, 1, 6, 6)).astype(np.float32) 30 net = nn.AvgPool2d(kernel_size=2, stride=1, pad_mode='valid') 31 out = net(Tensor(x)) 32 print(out) 33 expect_result = np.array( 34 [[[[3.5, 4.5, 5.5, 6.5, 7.5], 35 [9.5, 10.5, 11.5, 12.5, 13.5], 36 [15.5, 16.5, 17.5, 18.5, 19.5], 37 [21.5, 22.5, 23.5, 24.5, 25.5], 38 [27.5, 28.5, 29.5, 30.5, 31.5]]]] 39 ) 40 assert np.allclose(out.asnumpy(), expect_result) 41 42 43@pytest.mark.level0 44@pytest.mark.platform_x86_cpu 45@pytest.mark.env_onecard 46def test_avgpool_k2s2pv(): 47 x = np.arange(1 * 1 * 6 * 6).reshape((1, 1, 6, 6)).astype(np.float32) 48 net = nn.AvgPool2d(kernel_size=2, stride=2, pad_mode='valid') 49 out = net(Tensor(x)) 50 print(out) 51 expect_result = np.array( 52 [[[[3.5, 5.5, 7.5], 53 [15.5, 17.5, 19.5], 54 [27.5, 29.5, 31.5]]]] 55 ) 56 assert np.allclose(out.asnumpy(), expect_result) 57 58 59@pytest.mark.level0 60@pytest.mark.platform_x86_cpu 61@pytest.mark.env_onecard 62def test_avgpool_k3s2pv(): 63 x = np.arange(1 * 1 * 6 * 6).reshape((1, 1, 6, 6)).astype(np.float32) 64 net = nn.AvgPool2d(kernel_size=3, stride=2, pad_mode='valid') 65 out = net(Tensor(x)) 66 print(out) 67 expect_result = np.array( 68 [[[[7., 9.], 69 [19., 21.]]]] 70 ) 71 assert np.allclose(out.asnumpy(), expect_result) 72 73 74@pytest.mark.level0 75@pytest.mark.platform_x86_cpu 76@pytest.mark.env_onecard 77def test_avgpool_k3s2ps(): 78 x = np.arange(1 * 1 * 6 * 6).reshape((1, 1, 6, 6)).astype(np.float32) 79 net = nn.AvgPool2d(kernel_size=3, stride=2, pad_mode='same') 80 out = net(Tensor(x)) 81 print(out) 82 expect_result = np.array( 83 [[[[7., 9., 10.5], 84 [19., 21., 22.5], 85 [28., 30., 31.5]]]] 86 ) 87 assert np.allclose(out.asnumpy(), expect_result) 88 89 90if __name__ == '__main__': 91 test_avgpool_k2s1pv() 92 test_avgpool_k2s2pv() 93 test_avgpool_k3s2pv() 94 test_avgpool_k3s2ps() 95