test_linalg_lstsq_op.py 10.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
16

17
import numpy as np
18

19 20
import paddle
import paddle.fluid as fluid
21
import paddle.fluid.core as core
22 23 24 25


class LinalgLstsqTestCase(unittest.TestCase):
    def setUp(self):
26
        self.devices = ["cpu"]
27
        self.init_config()
28 29
        if core.is_compiled_with_cuda() and self.driver == "gels":
            self.devices.append("gpu:0")
30 31
        self.generate_input()
        self.generate_output()
H
Haohongxiang 已提交
32
        np.random.seed(2022)
33 34 35 36 37 38 39 40 41 42

    def init_config(self):
        self.dtype = 'float64'
        self.rcond = 1e-15
        self.driver = "gelsd"
        self._input_shape_1 = (5, 4)
        self._input_shape_2 = (5, 3)

    def generate_input(self):
        self._input_data_1 = np.random.random(self._input_shape_1).astype(
43 44
            self.dtype
        )
45
        self._input_data_2 = np.random.random(self._input_shape_2).astype(
46 47
            self.dtype
        )
48 49 50

    def generate_output(self):
        if len(self._input_shape_1) == 2:
51 52 53
            out = np.linalg.lstsq(
                self._input_data_1, self._input_data_2, rcond=self.rcond
            )
54 55 56 57
            self._output_solution = out[0]
            self._output_residuals = out[1]
            self._output_rank = out[2]
            self._output_sg_values = out[3]
58
        elif len(self._input_shape_1) == 3:
59 60 61 62 63
            self._output_solution = []
            self._output_residuals = []
            self._output_rank = []
            self._output_sg_values = []
            for i in range(self._input_shape_1[0]):
64 65 66 67 68
                out = np.linalg.lstsq(
                    self._input_data_1[i],
                    self._input_data_2[i],
                    rcond=self.rcond,
                )
69 70 71 72
                self._output_solution.append(out[0])
                self._output_residuals.append(out[1])
                self._output_rank.append(out[2])
                self._output_sg_values.append(out[3])
73

74
    def test_eager_dygraph(self):
75
        paddle.disable_static()
76 77 78
        for dev in self.devices:
            paddle.set_device(dev)
            place = paddle.CPUPlace() if dev == "cpu" else paddle.CUDAPlace(0)
79 80 81 82 83 84 85 86 87
            x = paddle.to_tensor(
                self._input_data_1, place=place, dtype=self.dtype
            )
            y = paddle.to_tensor(
                self._input_data_2, place=place, dtype=self.dtype
            )
            results = paddle.linalg.lstsq(
                x, y, rcond=self.rcond, driver=self.driver
            )
88 89 90 91 92 93
            self._result_solution = results[0].numpy()
            self._result_residuals = results[1].numpy()
            self._result_rank = results[2].numpy()
            self._result_sg_values = results[3].numpy()
            self.assert_np_close()

94 95 96 97 98 99
    def test_static(self):
        paddle.enable_static()
        for dev in self.devices:
            paddle.set_device(dev)
            place = fluid.CPUPlace() if dev == "cpu" else fluid.CUDAPlace(0)
            with fluid.program_guard(fluid.Program(), fluid.Program()):
100 101 102 103 104 105 106 107 108 109 110 111 112
                x = paddle.fluid.data(
                    name="x",
                    shape=self._input_shape_1,
                    dtype=self._input_data_1.dtype,
                )
                y = paddle.fluid.data(
                    name="y",
                    shape=self._input_shape_2,
                    dtype=self._input_data_2.dtype,
                )
                results = paddle.linalg.lstsq(
                    x, y, rcond=self.rcond, driver=self.driver
                )
113
                exe = fluid.Executor(place)
114 115 116 117 118
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"x": self._input_data_1, "y": self._input_data_2},
                    fetch_list=[results],
                )
119 120 121 122 123 124 125 126
                self._result_solution = fetches[0]
                self._result_residuals = fetches[1]
                self._result_rank = fetches[2]
                self._result_sg_values = fetches[3]
                self.assert_np_close()

    def assert_np_close(self):
        if len(self._input_shape_1) == 2:
127 128 129 130 131 132 133 134 135 136
            np.testing.assert_allclose(
                self._result_solution, self._output_solution, rtol=1e-3
            )
            if (
                self._input_shape_1[-2] > self._input_shape_1[-1]
                and self._output_rank == self._input_shape_1[-1]
            ):
                np.testing.assert_allclose(
                    self._result_residuals, self._output_residuals, rtol=1e-5
                )
137
            if self.driver in ("gelsy", "gelsd", "gelss"):
138 139 140
                np.testing.assert_allclose(
                    self._result_rank, self._output_rank, rtol=1e-5
                )
141
            if self.driver in ("gelsd", "gelss"):
142 143 144
                np.testing.assert_allclose(
                    self._result_sg_values, self._output_sg_values, rtol=1e-5
                )
145 146
        else:
            for i in range(len(self._output_solution)):
147 148 149 150 151 152 153 154 155 156 157 158 159 160
                np.testing.assert_allclose(
                    self._result_solution[i],
                    self._output_solution[i],
                    rtol=1e-3,
                )
                if (
                    self._input_shape_1[-2] > self._input_shape_1[-1]
                    and self._output_rank[i] == self._input_shape_1[-1]
                ):
                    np.testing.assert_allclose(
                        self._result_residuals[i],
                        self._output_residuals[i],
                        rtol=1e-5,
                    )
161
                if self.driver in ("gelsy", "gelsd", "gelss"):
162 163 164
                    np.testing.assert_allclose(
                        self._result_rank[i], self._output_rank[i], rtol=1e-5
                    )
165
                if self.driver in ("gelsd", "gelss"):
166 167 168 169 170
                    np.testing.assert_allclose(
                        self._result_sg_values[i],
                        self._output_sg_values[i],
                        rtol=1e-5,
                    )
171 172 173 174 175 176 177 178 179


class LinalgLstsqTestCase1(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float32'
        self.rcond = 1e-15
        self.driver = "gels"
        self._input_shape_1 = (9, 9)
        self._input_shape_2 = (9, 5)
180 181


182
class LinalgLstsqTestCase2(LinalgLstsqTestCase):
183 184 185 186 187
    def init_config(self):
        self.dtype = 'float64'
        self.rcond = 1e-15
        self.driver = "gels"
        self._input_shape_1 = (5, 10)
188
        self._input_shape_2 = (5, 8)
189 190


191 192 193 194 195 196 197 198 199
class LinalgLstsqTestCase3(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float64'
        self.rcond = 1e-15
        self.driver = "gels"
        self._input_shape_1 = (10, 7, 3)
        self._input_shape_2 = (10, 7, 6)


200 201 202
class LinalgLstsqTestCaseRcond(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float64'
203 204
        self.rcond = 1e-7
        self.driver = "gelsd"
205 206 207 208 209 210 211
        self._input_shape_1 = (3, 2)
        self._input_shape_2 = (3, 3)


class LinalgLstsqTestCaseGelsFloat32(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float32'
212
        self.rcond = None
213 214
        self.driver = "gels"
        self._input_shape_1 = (10, 5)
215 216 217 218 219 220 221 222 223 224
        self._input_shape_2 = (10, 8)


class LinalgLstsqTestCaseGelsFloat64(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float32'
        self.rcond = None
        self.driver = "gels"
        self._input_shape_1 = (3, 2, 8)
        self._input_shape_2 = (3, 2, 15)
225 226 227 228 229


class LinalgLstsqTestCaseGelssFloat64(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float64'
230
        self.rcond = None
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        self.driver = "gelss"
        self._input_shape_1 = (5, 5)
        self._input_shape_2 = (5, 1)


class LinalgLstsqTestCaseGelsyFloat32(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float32'
        self.rcond = 1e-15
        self.driver = "gelsy"
        self._input_shape_1 = (8, 2)
        self._input_shape_2 = (8, 10)


class LinalgLstsqTestCaseBatch1(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float32'
        self.rcond = 1e-15
249
        self.driver = "gelss"
250 251 252 253 254 255 256 257
        self._input_shape_1 = (2, 3, 10)
        self._input_shape_2 = (2, 3, 4)


class LinalgLstsqTestCaseBatch2(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float64'
        self.rcond = 1e-15
258
        self.driver = "gels"
259
        self._input_shape_1 = (10, 8, 6)
260
        self._input_shape_2 = (10, 8, 10)
261 262 263 264 265 266 267 268 269 270 271 272 273


class LinalgLstsqTestCaseLarge1(LinalgLstsqTestCase):
    def init_config(self):
        self.dtype = 'float64'
        self.rcond = 1e-15
        self.driver = "gelsd"
        self._input_shape_1 = (200, 100)
        self._input_shape_2 = (200, 50)


class LinalgLstsqTestCaseLarge2(LinalgLstsqTestCase):
    def init_config(self):
274
        self.dtype = 'float64'
275 276 277 278 279 280
        self.rcond = 1e-15
        self.driver = "gelss"
        self._input_shape_1 = (50, 600)
        self._input_shape_2 = (50, 300)


281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
class TestLinalgLstsqAPIError(unittest.TestCase):
    def setUp(self):
        pass

    def test_api_errors(self):
        def test_x_bad_shape():
            x = paddle.to_tensor(np.random.random(size=(5)), dtype=np.float32)
            y = paddle.to_tensor(
                np.random.random(size=(5, 15)), dtype=np.float32
            )
            out = paddle.linalg.lstsq(x, y, driver='gelsy')

        def test_y_bad_shape():
            x = paddle.to_tensor(
                np.random.random(size=(5, 10)), dtype=np.float32
            )
            y = paddle.to_tensor(np.random.random(size=(5)), dtype=np.float32)
            out = paddle.linalg.lstsq(x, y, driver='gelsy')

        def test_shape_dismatch():
            x = paddle.to_tensor(
                np.random.random(size=(5, 10)), dtype=np.float32
            )
            y = paddle.to_tensor(
                np.random.random(size=(4, 15)), dtype=np.float32
            )
            out = paddle.linalg.lstsq(x, y, driver='gelsy')

        self.assertRaises(ValueError, test_x_bad_shape)
        self.assertRaises(ValueError, test_y_bad_shape)
        self.assertRaises(ValueError, test_shape_dismatch)


314 315
if __name__ == '__main__':
    unittest.main()