mindspore2022/tests/ut/python/dataset/test_Tensor.py

75 lines
2.2 KiB
Python

# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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 numpy as np
"""
导入了MindSpore深度学习框架中的数据引擎模块
用于数据预处理和数据增强等任务
"""
import mindspore._c_dataengine as cde
"""
创建一个张量形状并进行一些断言测试
测试'cde.TensorShape()'函数的行为是否符合预期
"""
def test_shape():
x = [2, 3]
s = cde.TensorShape(x)
assert s.as_list() == x
assert s.is_known()
"""
使用NumPy和'cde'模块进行一些基本的数组操作
并添加了更多的断言测试来验证结果
"""
def test_basic():
x = np.array([1, 2, 3, 4, 5])
n = cde.Tensor(x)
arr = np.array(n, copy=False)
arr[0] = 0
x = np.array([0, 2, 3, 4, 5])
np.testing.assert_array_equal(x, arr)
assert n.type() == cde.DataType("int64")
arr2 = n.as_array()
arr[0] = 2
x = np.array([2, 2, 3, 4, 5])
np.testing.assert_array_equal(x, arr2)
assert n.type() == cde.DataType("int64")
assert arr.__array_interface__['data'] == arr2.__array_interface__['data']
"""
'test_strides()'函数对NumPy数组和'cde'模块中的张量进行了转换操作,并进行了断言测试
测试结果可以帮助确保转换操作的过程没有产生错误
"""
def test_strides():
x = np.array([[1, 2, 3], [4, 5, 6]])
n1 = cde.Tensor(x[:, 1])
arr = np.array(n1, copy=False)
np.testing.assert_array_equal(x[:, 1], arr)
n2 = cde.Tensor(x.transpose())
arr = np.array(n2, copy=False)
np.testing.assert_array_equal(x.transpose(), arr)
if __name__ == '__main__':
test_shape()
test_strides()
test_basic()