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_sparse_tensor.py 2.3 kB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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_sparse_tensor.py
  17. @Author:
  18. @Date : 2020-07-16
  19. @Desc : test mindspore sparse_tensor's operation
  20. """
  21. import mindspore as ms
  22. import mindspore.nn as nn
  23. from mindspore.ops import composite as C
  24. from mindspore import Tensor, SparseTensor, context
  25. context.set_context(mode=context.GRAPH_MODE, enable_sparse=True)
  26. def test_sparse_tensor_make_sparse_tensor():
  27. class MakeSparseTensor(nn.Cell):
  28. def __init__(self):
  29. super(MakeSparseTensor, self).__init__()
  30. self.dense_shape = (3, 4)
  31. def construct(self, indices, values):
  32. ret = (SparseTensor(indices, values, self.dense_shape),)
  33. return ret[0]
  34. indices = Tensor([[0, 1], [1, 2]])
  35. values = Tensor([1, 2], dtype=ms.float32)
  36. MakeSparseTensor()(indices, values)
  37. def test_sparse_tensor_attr():
  38. grad_op = C.GradOperation('get_all', get_all=True)
  39. class GradWrap(nn.Cell):
  40. def __init__(self, network):
  41. super(GradWrap, self).__init__()
  42. self.network = network
  43. def construct(self, input1, input2):
  44. gout = grad_op(self.network)(input1, input2)
  45. return gout
  46. class SparseTensorGetAttr(nn.Cell):
  47. def __init__(self):
  48. super(SparseTensorGetAttr, self).__init__()
  49. self.dense_shape = (3, 4)
  50. def construct(self, indices, values):
  51. x = SparseTensor(indices, values, self.dense_shape)
  52. return x.values(), x.indices(), x.dense_shape()
  53. indices = Tensor([[0, 1], [1, 2]])
  54. values = Tensor([1, 2], dtype=ms.float32)
  55. SparseTensorGetAttr()(indices, values)