You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_tensor.py 16 kB

5 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """
  16. @File : test_tensor.py
  17. @Author:
  18. @Date : 2019-03-14
  19. @Desc : test mindspore tensor's operation
  20. """
  21. import numpy as np
  22. import pytest
  23. import mindspore as ms
  24. import mindspore.common.api as me
  25. import mindspore.nn as nn
  26. from mindspore import Tensor, context
  27. from mindspore.common.initializer import initializer
  28. from mindspore.common.parameter import Parameter
  29. from ..ut_filter import non_graph_engine
  30. ndarr = np.ones((2, 3))
  31. context.set_context(mode=context.GRAPH_MODE)
  32. def test_tensor_flatten():
  33. with pytest.raises(AttributeError):
  34. lst = [1, 2, 3, 4,]
  35. tensor_list = ms.Tensor(lst, ms.float32)
  36. tensor_list = tensor_list.Flatten()
  37. print(tensor_list)
  38. def test_tensor_list():
  39. lst = [[1.0, 2.0, 1.0], [1.0, 10.0, 9.0]]
  40. tensor_list = ms.Tensor(lst, ms.float32)
  41. print(tensor_list)
  42. def test_tensor():
  43. """test_tensor"""
  44. t1 = ms.Tensor(ndarr)
  45. assert isinstance(t1, ms.Tensor)
  46. assert t1.dtype == ms.float64
  47. t2 = ms.Tensor(np.zeros([1, 2, 3]), ms.float32)
  48. assert isinstance(t2, ms.Tensor)
  49. assert t2.shape == (1, 2, 3)
  50. assert t2.dtype == ms.float32
  51. t3 = ms.Tensor(0.1)
  52. assert isinstance(t3, ms.Tensor)
  53. assert t3.dtype == ms.float32
  54. t4 = ms.Tensor(1)
  55. assert isinstance(t4, ms.Tensor)
  56. assert t4.dtype == ms.int64
  57. def test_tensor_type_float16():
  58. t_float16 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float16))
  59. assert isinstance(t_float16, ms.Tensor)
  60. assert t_float16.shape == (2, 3)
  61. assert t_float16.dtype == ms.float16
  62. def test_tensor_type_complex64():
  63. np_input = np.array(
  64. [[1+0.1j, 2j, 3+0.3j], [4-0.4j, 5, 6]], dtype=np.complex64)
  65. t_complex64 = ms.Tensor(np_input)
  66. assert isinstance(t_complex64, ms.Tensor)
  67. assert t_complex64.shape == (2, 3)
  68. assert t_complex64.dtype == ms.complex64
  69. assert np.all(t_complex64.asnumpy() == np_input)
  70. def test_tensor_type_complex64_user_define():
  71. np_input = np.zeros([1, 2, 3])
  72. t_complex64 = ms.Tensor(np_input, ms.complex64)
  73. assert isinstance(t_complex64, ms.Tensor)
  74. assert t_complex64.shape == (1, 2, 3)
  75. assert t_complex64.dtype == ms.complex64
  76. assert np.all(t_complex64.asnumpy() == np_input)
  77. def test_tensor_type_complex128():
  78. #complex python object
  79. py_input = 1 + 2.22222222j
  80. t_complex128 = ms.Tensor(py_input)
  81. assert t_complex128.shape == ()
  82. assert t_complex128.dtype == ms.complex128
  83. assert np.all(t_complex128.asnumpy() == py_input)
  84. #complex in numpy array
  85. np_input = np.array(
  86. [[1+0.1j, 2j, 3+0.3j], [4-0.4j, 5, 6]], dtype=np.complex128)
  87. t_complex128 = ms.Tensor(np_input)
  88. assert isinstance(t_complex128, ms.Tensor)
  89. assert t_complex128.shape == (2, 3)
  90. assert t_complex128.dtype == ms.complex128
  91. assert np.all(t_complex128.asnumpy() == np_input)
  92. #complex in tuple
  93. py_input = (1, 2.22222222j, 3)
  94. t_complex128 = ms.Tensor(py_input)
  95. assert np.all(t_complex128.asnumpy() == py_input)
  96. #complex in list
  97. py_input = [[1+0.1j, 2j, 3+0.3j], [4-0.4j, 5, 6]]
  98. t_complex128 = ms.Tensor(py_input)
  99. assert isinstance(t_complex128, ms.Tensor)
  100. assert t_complex128.shape == (2, 3)
  101. assert t_complex128.dtype == ms.complex128
  102. assert np.all(t_complex128.asnumpy() == py_input)
  103. def test_tensor_type_complex128_user_define():
  104. np_input = np.zeros([1, 2, 3])
  105. t_complex128 = ms.Tensor(np_input, ms.complex128)
  106. assert isinstance(t_complex128, ms.Tensor)
  107. assert t_complex128.shape == (1, 2, 3)
  108. assert t_complex128.dtype == ms.complex128
  109. assert np.all(t_complex128.asnumpy() == np_input)
  110. def test_tensor_type_float32():
  111. t_float32 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))
  112. assert isinstance(t_float32, ms.Tensor)
  113. assert t_float32.shape == (2, 3)
  114. assert t_float32.dtype == ms.float32
  115. def test_tensor_type_float32_user_define():
  116. t = ms.Tensor(np.zeros([1, 2, 3]), ms.float32)
  117. assert isinstance(t, ms.Tensor)
  118. assert t.shape == (1, 2, 3)
  119. assert t.dtype == ms.float32
  120. def test_tensor_type_float64():
  121. t = ms.Tensor([[1.0, 2, 3], [4, 5, 6]])
  122. assert isinstance(t, ms.Tensor)
  123. assert t.shape == (2, 3)
  124. assert t.dtype == ms.float32
  125. t_zero = ms.Tensor(np.zeros([1, 2, 3]))
  126. assert isinstance(t_zero, ms.Tensor)
  127. assert t_zero.shape == (1, 2, 3)
  128. assert t_zero.dtype == ms.float64
  129. def test_tensor_type_float64_user_define():
  130. t = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=float))
  131. assert isinstance(t, ms.Tensor)
  132. assert t.shape == (2, 3)
  133. assert t.dtype == ms.float64
  134. t_float64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]]), ms.float64)
  135. assert isinstance(t_float64, ms.Tensor)
  136. assert t_float64.shape == (2, 3)
  137. assert t_float64.dtype == ms.float64
  138. def test_tensor_type_bool():
  139. # init a tensor with bool type
  140. ts_bool_array = ms.Tensor(np.zeros([2, 3], np.bool), ms.bool_)
  141. assert isinstance(ts_bool_array, ms.Tensor)
  142. assert ts_bool_array.dtype == ms.bool_
  143. t_bool = ms.Tensor(True)
  144. assert isinstance(t_bool, ms.Tensor)
  145. assert t_bool.dtype == ms.bool_
  146. t_bool_array = ms.Tensor(np.array([[True, False, True], [False, False, False]]))
  147. assert isinstance(t_bool_array, ms.Tensor)
  148. assert t_bool_array.shape == (2, 3)
  149. assert t_bool_array.dtype == ms.bool_
  150. def test_tensor_type_int8():
  151. t_int8_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int8))
  152. assert isinstance(t_int8_array, ms.Tensor)
  153. assert t_int8_array.shape == (2, 3)
  154. assert t_int8_array.dtype == ms.int8
  155. def test_tensor_type_int16():
  156. t_int16_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16))
  157. assert isinstance(t_int16_array, ms.Tensor)
  158. assert t_int16_array.shape == (2, 3)
  159. assert t_int16_array.dtype == ms.int16
  160. def test_tensor_type_int32():
  161. t_int = ms.Tensor([[1, 2, 3], [4, 5, 6]])
  162. assert isinstance(t_int, ms.Tensor)
  163. assert t_int.shape == (2, 3)
  164. assert t_int.dtype == ms.int64
  165. t_int_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
  166. assert isinstance(t_int_array, ms.Tensor)
  167. assert t_int_array.shape == (2, 3)
  168. assert t_int_array.dtype == ms.int32
  169. def test_tensor_type_int64():
  170. t_int64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int64))
  171. assert isinstance(t_int64, ms.Tensor)
  172. assert t_int64.shape == (2, 3)
  173. assert t_int64.dtype == ms.int64
  174. def test_tensor_type_uint8():
  175. t_uint8_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8))
  176. assert isinstance(t_uint8_array, ms.Tensor)
  177. assert t_uint8_array.shape == (2, 3)
  178. assert t_uint8_array.dtype == ms.uint8
  179. def test_tensor_type_uint16():
  180. t_uint16_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint16))
  181. assert isinstance(t_uint16_array, ms.Tensor)
  182. assert t_uint16_array.shape == (2, 3)
  183. assert t_uint16_array.dtype == ms.uint16
  184. def test_tensor_type_uint32():
  185. t_uint32_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint32))
  186. assert isinstance(t_uint32_array, ms.Tensor)
  187. assert t_uint32_array.shape == (2, 3)
  188. assert t_uint32_array.dtype == ms.uint32
  189. def test_tensor_type_uint64():
  190. t_uint64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint64))
  191. assert isinstance(t_uint64, ms.Tensor)
  192. assert t_uint64.shape == (2, 3)
  193. assert t_uint64.dtype == ms.uint64
  194. def test_set_type():
  195. t = ms.Tensor(ndarr)
  196. t.set_dtype(ms.float32)
  197. assert t.dtype == ms.float32
  198. @non_graph_engine
  199. def test_add():
  200. x = ms.Tensor(ndarr)
  201. y = ms.Tensor(ndarr)
  202. z = x + y
  203. assert isinstance(z, ms.Tensor)
  204. @non_graph_engine
  205. def test_sub():
  206. x = ms.Tensor(ndarr)
  207. y = ms.Tensor(ndarr)
  208. z = x - y
  209. assert isinstance(z, ms.Tensor)
  210. @non_graph_engine
  211. def test_div():
  212. x = ms.Tensor(np.array([[2, 6, 10], [12, 4, 8]]).astype(np.float32))
  213. y = ms.Tensor(np.array([[2, 2, 5], [6, 1, 2]]).astype(np.float32))
  214. z = x / y
  215. z2 = x / 2
  216. assert isinstance(z, ms.Tensor)
  217. assert isinstance(z2, ms.Tensor)
  218. @non_graph_engine
  219. def test_parameter():
  220. x = Parameter(initializer(1, [1], ms.float32), name="beta1_power")
  221. x = x.init_data()
  222. z = x / 2
  223. print(z)
  224. class Net(nn.Cell):
  225. """Net definition"""
  226. def __init__(self, dim):
  227. super(Net, self).__init__()
  228. self.dim = dim
  229. def construct(self, input_x):
  230. return input_x
  231. @non_graph_engine
  232. def test_return_tensor():
  233. """test_return_tensor"""
  234. net = Net(0)
  235. input_data = ms.Tensor(np.array([[1.2, 2.1], [2.2, 3.2]]).astype('float32'))
  236. input_data.set_dtype(ms.float32)
  237. exe = me._cell_graph_executor
  238. exe.compile(net, input_data)
  239. tensor_ = exe(net, input_data)
  240. # get shape
  241. shape_ = tensor_.shape
  242. print("shape = ", shape_)
  243. # get type
  244. type_ = tensor_.dtype
  245. print("type = ", type_)
  246. # get value
  247. value_ = tensor_.asnumpy()
  248. print("numpy value = ", value_)
  249. def test_tensor_contiguous():
  250. """test_tensor_contiguous"""
  251. input_c = np.arange(6).reshape(2, 3)
  252. input_f = input_c.T
  253. np.ascontiguousarray(input_c, dtype=np.float32)
  254. assert True, input_c.flags['C_CONTIGUOUS']
  255. print("input_f flags = ", input_f.flags)
  256. assert True, input_f.flags['F_CONTIGUOUS']
  257. tensor_f_float32 = ms.Tensor(input_f)
  258. rt_f = tensor_f_float32.asnumpy()
  259. assert True, rt_f.flags['C_CONTIGUOUS']
  260. print("rt_f flags = ", rt_f.flags)
  261. def test_tensor_contiguous2():
  262. input_data = np.random.randn(32, 112, 112, 3).astype(np.float32)
  263. input_me = input_data.transpose(0, 3, 1, 2)
  264. print("input_me flags = ", input_me.flags)
  265. tensor_f_float32 = ms.Tensor(input_me)
  266. out_f = tensor_f_float32.asnumpy()
  267. print("out_f flags = ", out_f.flags)
  268. def test_tensor_input_string():
  269. with pytest.raises(TypeError):
  270. input_data = 'ccc'
  271. ms.Tensor(input_data)
  272. def test_tensor_input_tuple_string():
  273. with pytest.raises(TypeError):
  274. input_data = (2, 3, '4', 5)
  275. ms.Tensor(input_data)
  276. def test_tensor_input_list_string():
  277. with pytest.raises(TypeError):
  278. input_data = [[2, 3, '4', 5], [1, 2, 3, 4]]
  279. ms.Tensor(input_data)
  280. def test_tensor_input_none():
  281. with pytest.raises(TypeError):
  282. input_data = None
  283. ms.Tensor(input_data, np.int64)
  284. # pylint: disable=no-value-for-parameter
  285. def test_tensor_input_empty():
  286. with pytest.raises(TypeError):
  287. ms.Tensor()
  288. def test_tensor_input_ndarray_str():
  289. inp = np.array(["88", 0, 9])
  290. tensor = ms.Tensor(inp)
  291. assert str(tensor) == "['88' '0' '9']"
  292. def test_tensor_input_ndarray_bool():
  293. inp = np.array([True, 2, 4])
  294. ms.Tensor(inp)
  295. inp = np.array([False, 2, 4])
  296. ms.Tensor(inp)
  297. def test_tensor_input_ndarray_none():
  298. with pytest.raises(TypeError):
  299. inp = np.array([None, 2, 4])
  300. ms.Tensor(inp)
  301. def test_tensor_input_ndarray_dict():
  302. with pytest.raises(TypeError):
  303. inp = {'a': 6, 'b': 7}
  304. ms.Tensor(inp)
  305. def test_tensor_input_np_nan():
  306. with pytest.raises(TypeError):
  307. input_data = (1, 2, 3, np.nan)
  308. ms.Tensor(input_data, np.int64)
  309. def test_tensor_input_tuple_inf():
  310. with pytest.raises(TypeError):
  311. input_data = (1, 2, 3, float("inf"))
  312. ms.Tensor(input_data, np.int64)
  313. def test_tensor_input_dict():
  314. with pytest.raises(TypeError):
  315. input_data = {'a': 6, 'b': 7}
  316. ms.Tensor(input_data, np.int64)
  317. def test_tensor_input_complex():
  318. with pytest.raises(TypeError):
  319. input_data = (1, 2j, 3)
  320. ms.Tensor(input_data, np.int64)
  321. def test_tensor_dtype_np_float():
  322. with pytest.raises(TypeError):
  323. input_data = np.random.randn(32, 112, 112, 3).astype(np.float)
  324. ms.Tensor(input_data, np.float)
  325. def test_tensor_dtype_np_float16():
  326. with pytest.raises(TypeError):
  327. input_data = np.random.randn(32, 112, 112, 3).astype(np.float16)
  328. ms.Tensor(input_data, np.float16)
  329. def test_tensor_dtype_np_float32():
  330. with pytest.raises(TypeError):
  331. input_data = np.random.randn(32, 112, 112, 3).astype(np.float32)
  332. ms.Tensor(input_data, np.float32)
  333. def test_tensor_dtype_np_float64():
  334. with pytest.raises(TypeError):
  335. input_data = np.random.randn(32, 112, 112, 3).astype(np.float64)
  336. ms.Tensor(input_data, np.float64)
  337. def test_tensor_dtype_np_int():
  338. with pytest.raises(TypeError):
  339. input_data = np.random.randn(32, 112, 112, 3).astype(np.int)
  340. ms.Tensor(input_data, np.int)
  341. def test_tensor_dtype_np_int8():
  342. with pytest.raises(TypeError):
  343. input_data = np.random.randn(32, 112, 112, 3).astype(np.int8)
  344. ms.Tensor(input_data, np.int8)
  345. def test_tensor_dtype_np_int16():
  346. with pytest.raises(TypeError):
  347. input_data = np.random.randn(32, 112, 112, 3).astype(np.int16)
  348. ms.Tensor(input_data, np.int16)
  349. def test_tensor_dtype_np_int32():
  350. with pytest.raises(TypeError):
  351. input_data = np.random.randn(32, 112, 112, 3).astype(np.int32)
  352. ms.Tensor(input_data, np.int32)
  353. def test_tensor_dtype_np_int64():
  354. with pytest.raises(TypeError):
  355. input_data = np.random.randn(32, 112, 112, 3).astype(np.int64)
  356. ms.Tensor(input_data, np.int64)
  357. def test_tensor_dtype_fp32_to_bool():
  358. input_ = np.random.randn(2, 3, 4, 5).astype(np.float32)
  359. input_ = ms.Tensor(input_)
  360. t = ms.Tensor(input_, dtype=ms.bool_)
  361. assert isinstance(t, ms.Tensor)
  362. assert t.shape == (2, 3, 4, 5)
  363. assert t.dtype == ms.bool_
  364. def test_tensor_dtype_fp64_to_uint8():
  365. array = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float64)
  366. t = ms.Tensor(array, ms.uint8)
  367. assert isinstance(t, ms.Tensor)
  368. assert t.shape == (2, 3)
  369. assert t.dtype == ms.uint8
  370. def test_tensor_dtype_complex64_to_float32():
  371. array = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.complex64)
  372. t = ms.Tensor(array, ms.float32)
  373. assert isinstance(t, ms.Tensor)
  374. assert t.shape == (2, 3)
  375. assert t.dtype == ms.float32
  376. def test_tensor_dtype_float32_to_complex64():
  377. array = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
  378. t = ms.Tensor(array, ms.complex64)
  379. assert isinstance(t, ms.Tensor)
  380. assert t.shape == (2, 3)
  381. assert t.dtype == ms.complex64
  382. def test_tensor_operation():
  383. x = Tensor(np.ones((3, 3)) * 4)
  384. res = x + 1
  385. assert np.all(res.asnumpy() == np.ones((3, 3)) * 5)
  386. res = 1 + x
  387. assert np.all(res.asnumpy() == np.ones((3, 3)) * 5)
  388. res = x - 2
  389. assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)
  390. res = 6 - x
  391. assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)
  392. res = x * 3
  393. assert np.all(res.asnumpy() == np.ones((3, 3)) * 12)
  394. res = 3 * x
  395. assert np.all(res.asnumpy() == np.ones((3, 3)) * 12)
  396. res = x / 2
  397. assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)
  398. res = 8 / x
  399. assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)
  400. res = x % 3
  401. assert np.all(res.asnumpy() == np.ones((3, 3)))
  402. res = x // 3
  403. assert np.all(res.asnumpy() == np.ones((3, 3)))
  404. x %= 3
  405. assert np.all(x.asnumpy() == np.ones((3, 3)))
  406. res = x * (2, 3, 4)
  407. assert np.all(res.asnumpy() == np.ones((3, 3)) * (2, 3, 4))
  408. res = 5 % x
  409. assert np.all(x.asnumpy() == np.ones((3, 3)))
  410. res = 5 // x
  411. assert np.all(x.asnumpy() == np.ones((3, 3)))
  412. def test_tensor_from_numpy():
  413. a = np.ones((2, 3))
  414. t = ms.Tensor.from_numpy(a)
  415. assert isinstance(t, ms.Tensor)
  416. assert np.all(t.asnumpy() == 1)
  417. # 't' and 'a' share same data.
  418. a[1] = 2
  419. assert np.all(t.asnumpy()[0] == 1)
  420. assert np.all(t.asnumpy()[1] == 2)
  421. # 't' is still valid after 'a' deleted.
  422. del a
  423. assert np.all(t.asnumpy()[0] == 1)
  424. assert np.all(t.asnumpy()[1] == 2)
  425. with pytest.raises(TypeError):
  426. # incorrect input.
  427. t = ms.Tensor.from_numpy([1, 2, 3])