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 16
from __future__ import print_function

17
import paddle.fluid.core as core
Q
qijun 已提交
18 19 20 21 22 23 24 25 26
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 已提交
27 28 29
        row_numel = 12
        selected_rows = core.SelectedRows(rows, height)
        np_array = np.ones((len(rows), row_numel)).astype("float32")
Q
qijun 已提交
30 31
        np_array[0, 0] = 2.0
        np_array[2, 8] = 4.0
Q
qijun 已提交
32
        tensor = selected_rows.get_tensor()
Q
qijun 已提交
33 34 35
        tensor.set(np_array, place)

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

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

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


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