• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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# ============================================================================
15""" Test L1Regularizer """
16import numpy as np
17import pytest
18import mindspore.nn as nn
19import mindspore.context as context
20from mindspore import Tensor, ms_function
21
22context.set_context(mode=context.GRAPH_MODE)
23
24
25class Net_l1_regularizer(nn.Cell):
26    def __init__(self, scale):
27        super(Net_l1_regularizer, self).__init__()
28        self.l1_regularizer = nn.L1Regularizer(scale)
29
30    @ms_function
31    def construct(self, weights):
32        return self.l1_regularizer(weights)
33
34
35@pytest.mark.level0
36@pytest.mark.platform_x86_cpu
37@pytest.mark.env_onecard
38def test_l1_regularizer01():
39    scale = 0.5
40    weights = Tensor(np.array([[1.0, -2.0], [-3.0, 4.0]]).astype(np.float32))
41    l1_regularizer = Net_l1_regularizer(scale)
42    output = l1_regularizer(weights)
43    print("After l1_regularizer01 is: ", output.asnumpy())
44    print("output.shape: ", output.shape)
45    print("output.dtype: ", output.dtype)
46    expect = 5.0
47    assert np.all(output.asnumpy() == expect)
48
49
50@pytest.mark.level0
51@pytest.mark.platform_x86_cpu
52@pytest.mark.env_onecard
53def test_l1_regularizer08():
54    scale = 0.5
55    net = nn.L1Regularizer(scale)
56    weights = Tensor(np.array([[1.0, -2.0], [-3.0, 4.0]]).astype(np.float32))
57    output = net(weights)
58    expect = 5.0
59    print("output : ", output.asnumpy())
60    assert np.all(output.asnumpy() == expect)
61
62
63@pytest.mark.level0
64@pytest.mark.platform_x86_cpu
65@pytest.mark.env_onecard
66def test_l1_regularizer_input_int():
67    scale = 0.5
68    net = nn.L1Regularizer(scale)
69    weights = 2
70    try:
71        output = net(weights)
72        print("output : ", output.asnumpy())
73    except TypeError:
74        assert True
75
76
77@pytest.mark.level0
78@pytest.mark.platform_x86_cpu
79@pytest.mark.env_onecard
80def test_l1_regularizer_input_tuple():
81    scale = 0.5
82    net = nn.L1Regularizer(scale)
83    weights = (1, 2, 3, 4)
84    try:
85        output = net(weights)
86        print("output : ", output.asnumpy())
87    except TypeError:
88        assert True
89