test_selected_rows.py 1.8 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

15
import paddle.fluid.core as core
Q
qijun 已提交
16 17 18 19 20 21 22 23 24
import unittest
import numpy as np


class TestSelectedRows(unittest.TestCase):
    def test_selected_rows(self):
        place = core.CPUPlace()
        height = 10
        rows = [0, 4, 7]
Q
qijun 已提交
25 26 27
        row_numel = 12
        selected_rows = core.SelectedRows(rows, height)
        np_array = np.ones((len(rows), row_numel)).astype("float32")
Q
qijun 已提交
28 29
        np_array[0, 0] = 2.0
        np_array[2, 8] = 4.0
Q
qijun 已提交
30
        tensor = selected_rows.get_tensor()
Q
qijun 已提交
31 32 33
        tensor.set(np_array, place)

        # compare rows
Q
qijun 已提交
34 35 36
        self.assertEqual(0, selected_rows.rows()[0])
        self.assertEqual(4, selected_rows.rows()[1])
        self.assertEqual(7, selected_rows.rows()[2])
Q
qijun 已提交
37 38

        # compare height
Q
qijun 已提交
39
        self.assertEqual(10, selected_rows.height())
Q
qijun 已提交
40 41 42

        # compare tensor
        self.assertAlmostEqual(2.0,
Y
yuyang18 已提交
43
                               selected_rows.get_tensor()._get_float_element(0))
Q
qijun 已提交
44
        self.assertAlmostEqual(1.0,
Y
yuyang18 已提交
45
                               selected_rows.get_tensor()._get_float_element(1))
Q
qijun 已提交
46
        self.assertAlmostEqual(
Q
qijun 已提交
47
            4.0,
Y
yuyang18 已提交
48
            selected_rows.get_tensor()._get_float_element(2 * row_numel + 8))
Q
qijun 已提交
49 50 51 52


if __name__ == "__main__":
    unittest.main()