def test_asfarray():
    test_case = Cases()
    for array in test_case.array_sets:
        # Check for dtype matching
        actual = onp.asfarray(array)
        expected = mnp.asfarray(array).asnumpy()
        # Since we set float32/int32 as the default dtype in mindspore, we need
        # to make a conversion between numpy.asarray and mindspore.numpy.asarray
        if actual.dtype is onp.dtype('float64'):
            assert expected.dtype == onp.dtype('float32')
        else:
            assert actual.dtype == expected.dtype
        match_array(actual, expected, error=7)

        for i in range(len(test_case.onp_dtypes)):
            actual = onp.asfarray(array, test_case.onp_dtypes[i])
            expected = mnp.asfarray(array, test_case.mnp_dtypes[i]).asnumpy()
            match_array(actual, expected, error=7)

    # Additional tests for nested tensor/numpy_array mixture
    mnp_input = [(mnp.ones(3, ), mnp.ones(3)), [[1, 1, 1], (1, 1, 1)]]
    onp_input = [(onp.ones(3, ), onp.ones(3)), [[1, 1, 1], (1, 1, 1)]]

    actual = onp.asfarray(onp_input)
    expected = mnp.asfarray(mnp_input).asnumpy()
    match_array(actual, expected, error=7)
def test_ones():
    test_case = Cases()
    for shape in test_case.all_shapes:
        for i in range(len(test_case.onp_dtypes)):
            actual = onp.ones(shape, test_case.onp_dtypes[i])
            expected = mnp.ones(shape, test_case.mnp_dtypes[i]).asnumpy()
            match_array(actual, expected)
        actual = onp.ones(shape)
        expected = mnp.ones(shape).asnumpy()
        match_array(actual, expected)
def test_tri_triu_tril():
    x = mnp.ones((16, 32), dtype="bool")
    match_array(mnp.tril(x).asnumpy(), onp.tril(x.asnumpy()))
    match_array(mnp.tril(x, -1).asnumpy(), onp.tril(x.asnumpy(), -1))
    match_array(mnp.triu(x).asnumpy(), onp.triu(x.asnumpy()))
    match_array(mnp.triu(x, -1).asnumpy(), onp.triu(x.asnumpy(), -1))

    x = mnp.ones((64, 64), dtype="uint8")
    match_array(mnp.tril(x).asnumpy(), onp.tril(x.asnumpy()))
    match_array(mnp.tril(x, 25).asnumpy(), onp.tril(x.asnumpy(), 25))
    match_array(mnp.triu(x).asnumpy(), onp.triu(x.asnumpy()))
    match_array(mnp.triu(x, 25).asnumpy(), onp.triu(x.asnumpy(), 25))

    match_array(mnp.tri(64, 64).asnumpy(), onp.tri(64, 64))
    match_array(mnp.tri(64, 64, -10).asnumpy(), onp.tri(64, 64, -10))
Example #4
0
    def __init__(self,
                 input_dim,
                 hidden_num,
                 hidden_dim,
                 output_dim,
                 mu,
                 lamb,
                 nonlinear="leaky-relu",
                 norm_prod='paths',
                 square_prod=False):

        super(BaseModel, self).__init__()
        self.input_dim = input_dim
        self.hidden_num = hidden_num
        self.hidden_dim = hidden_dim
        self.output_dim = output_dim
        self.mu = mu
        self.lamb = lamb
        self.nonlinear = nonlinear
        self.norm_prod = norm_prod
        self.square_prod = square_prod

        self.normal = msd.Normal(dtype=mstype.float32)
        self.extra_params = []

        # initialize current adjacency matrix
        self.adjacency = msnp.ones(
            (self.input_dim, self.input_dim), dtype=mstype.float32) - msnp.eye(
                self.input_dim, dtype=mstype.float32)

        # Generate layer_list
        layer_list = [self.hidden_dim] * self.hidden_num
        layer_list.insert(0, self.input_dim)
        layer_list.append(self.output_dim)

        # Instantiate the parameters of each layer in the model of each variable
        tmp_weights = list()
        tmp_biases = list()
        for i, item in enumerate(layer_list[:-1]):
            in_dim = item
            out_dim = layer_list[i + 1]
            tmp_weights.append(
                Parameter(msnp.zeros((self.input_dim, out_dim, in_dim),
                                     dtype=mstype.float32),
                          requires_grad=True,
                          name='w' + str(i)))
            tmp_biases.append(
                Parameter(msnp.zeros((self.input_dim, out_dim),
                                     dtype=mstype.float32),
                          requires_grad=True,
                          name='b' + str(i)))

        self.weights = ParameterTuple(tmp_weights)
        self.biases = ParameterTuple(tmp_biases)

        # reset initialization parameters
        self.reset_params()
def test_array():
    # array's function is very similar to asarray, so we mainly test the
    # `copy` argument.
    test_case = Cases()
    for array in test_case.array_sets:
        arr1 = mnp.asarray(array)
        arr2 = mnp.array(arr1, copy=False)
        arr3 = mnp.array(arr1)
        arr4 = mnp.asarray(array, dtype='int32')
        arr5 = mnp.asarray(arr4, dtype=mnp.int32)
        assert arr1 is arr2
        assert arr1 is not arr3
        assert arr4 is arr5

    # Additional tests for nested tensor/numpy_array mixture
    mnp_input = [(mnp.ones(3, ), mnp.ones(3)), [[1, 1, 1], (1, 1, 1)]]
    onp_input = [(onp.ones(3, ), onp.ones(3)), [[1, 1, 1], (1, 1, 1)]]

    actual = onp.array(onp_input)
    expected = mnp.array(mnp_input).asnumpy()
    match_array(actual, expected, error=7)
Example #6
0
def test_cumsum():
    x = mnp.ones((16, 16), dtype="bool")
    match_array(mnp.cumsum(x).asnumpy(), onp.cumsum(x.asnumpy()))
    match_array(
        mnp.cumsum(x, axis=0).asnumpy(), onp.cumsum(x.asnumpy(), axis=0))
    match_meta(mnp.cumsum(x).asnumpy(), onp.cumsum(x.asnumpy()))

    x = rand_int(3, 4, 5)
    match_array(
        mnp.cumsum(mnp.asarray(x), dtype="bool").asnumpy(),
        onp.cumsum(x, dtype="bool"))
    match_array(
        mnp.cumsum(mnp.asarray(x), axis=-1).asnumpy(), onp.cumsum(x, axis=-1))
Example #7
0
def test_swapaxes_exception():
    with pytest.raises(ValueError):
        mnp.swapaxes(mnp.ones((3, 3)), 1, 10)
Example #8
0
def test_expand_dims_exception():
    with pytest.raises(TypeError):
        mnp.expand_dims(mnp.ones((3, 3)), 1.2)
Example #9
0
    def __init__(self):
        self.all_shapes = [
            0, 1, 2, (), (1,), (2,), (1, 2, 3), [], [1], [2], [1, 2, 3]
        ]
        self.onp_dtypes = [onp.int32, 'int32', int,
                           onp.float32, 'float32', float,
                           onp.uint32, 'uint32',
                           onp.bool_, 'bool', bool]

        self.mnp_dtypes = [mnp.int32, 'int32', int,
                           mnp.float32, 'float32', float,
                           mnp.uint32, 'uint32',
                           mnp.bool_, 'bool', bool]

        self.array_sets = [1, 1.1, True, [1, 0, True], [1, 1.0, 2], (1,),
                           [(1, 2, 3), (4, 5, 6)], onp.random.random(  # pylint: disable=no-member
                               (100, 100)).astype(onp.float32),
                           onp.random.random((100, 100)).astype(onp.bool)]

        self.arrs = [
            rand_int(2),
            rand_int(2, 3),
            rand_int(2, 3, 4),
            rand_int(2, 3, 4, 5),
        ]

        # scalars expanded across the 0th dimension
        self.scalars = [
            rand_int(),
            rand_int(1),
            rand_int(1, 1),
            rand_int(1, 1, 1),
        ]

        # arrays of the same size expanded across the 0th dimension
        self.expanded_arrs = [
            rand_int(2, 3),
            rand_int(1, 2, 3),
            rand_int(1, 1, 2, 3),
            rand_int(1, 1, 1, 2, 3),
        ]

        # arrays with dimensions of size 1
        self.nested_arrs = [
            rand_int(1),
            rand_int(1, 2),
            rand_int(3, 1, 8),
            rand_int(1, 3, 9, 1),
        ]

        # arrays which can be broadcast
        self.broadcastables = [
            rand_int(5),
            rand_int(6, 1),
            rand_int(7, 1, 5),
            rand_int(8, 1, 6, 1)
        ]

        # boolean arrays which can be broadcast
        self.bool_broadcastables = [
            rand_bool(),
            rand_bool(1),
            rand_bool(5),
            rand_bool(6, 1),
            rand_bool(7, 1, 5),
            rand_bool(8, 1, 6, 1),
        ]

        self.mnp_prototypes = [
            mnp.ones((2, 3, 4)),
            mnp.ones((0, 3, 0, 2, 5)),
            onp.ones((2, 7, 0)),
            onp.ones(()),
            [mnp.ones(3), (1, 2, 3), onp.ones(3), [4, 5, 6]],
            ([(1, 2), mnp.ones(2)], (onp.ones(2), [3, 4])),
        ]

        self.onp_prototypes = [
            onp.ones((2, 3, 4)),
            onp.ones((0, 3, 0, 2, 5)),
            onp.ones((2, 7, 0)),
            onp.ones(()),
            [onp.ones(3), (1, 2, 3), onp.ones(3), [4, 5, 6]],
            ([(1, 2), onp.ones(2)], (onp.ones(2), [3, 4])),
        ]
Example #10
0

class RollSwap(Cell):
    def __init__(self):
        super(RollSwap, self).__init__()

    def construct(self, x):
        x = mnp.rollaxis(x, 2)
        x = mnp.swapaxes(x, 0, 1)
        return x


test_case_array_ops = [
    ('ReshapeExpandSqueeze', {
        'block': ReshapeExpandSqueeze(),
        'desc_inputs': [mnp.ones((2, 3, 4))]}),

    ('TransposeConcatRavel', {
        'block': TransposeConcatRavel(),
        'desc_inputs': [mnp.ones((2, 3, 4)),
                        mnp.ones((2, 3, 4)),
                        mnp.ones((2, 4, 1))]}),

    ('RollSwap', {
        'block': RollSwap(),
        'desc_inputs': [mnp.ones((2, 3, 4))]})
]

test_case_lists = [test_case_array_ops]
test_exec_case = functools.reduce(lambda x, y: x + y, test_case_lists)
# use -k to select certain testcast
Example #11
0
def test_swapaxes_exception():
    with pytest.raises(TypeError):
        swapaxes_exception(mnp.ones((3, 3)))
Example #12
0

class RollSwap(Cell):
    def __init__(self):
        super(RollSwap, self).__init__()

    def construct(self, x):
        x = mnp.rollaxis(x, 2)
        x = mnp.swapaxes(x, 0, 1)
        return x


test_case_array_ops = [
    ('ReshapeExpandSqueeze', {
        'block': ReshapeExpandSqueeze(),
        'desc_inputs': [mnp.ones((2, 3, 4))]
    }),
    ('TransposeConcatRavel', {
        'block':
        TransposeConcatRavel(),
        'desc_inputs':
        [mnp.ones((2, 3, 4)),
         mnp.ones((2, 3, 4)),
         mnp.ones((2, 4, 1))]
    }),
    ('RollSwap', {
        'block': RollSwap(),
        'desc_inputs': [mnp.ones((2, 3, 4))]
    })
]
Example #13
0
def ones(shape, dtype=mstype.float32):
    return mnp.ones(shape, dtype)