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_graphdata.py 8.5 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. import random
  16. import pytest
  17. import numpy as np
  18. import mindspore.dataset as ds
  19. from mindspore import log as logger
  20. DATASET_FILE = "../data/mindrecord/testGraphData/testdata"
  21. SOCIAL_DATA_FILE = "../data/mindrecord/testGraphData/sns"
  22. def test_graphdata_getfullneighbor():
  23. """
  24. Test get all neighbors
  25. """
  26. logger.info('test get all neighbors.\n')
  27. g = ds.GraphData(DATASET_FILE, 2)
  28. nodes = g.get_all_nodes(1)
  29. assert len(nodes) == 10
  30. neighbor = g.get_all_neighbors(nodes, 2)
  31. assert neighbor.shape == (10, 6)
  32. row_tensor = g.get_node_feature(neighbor.tolist(), [2, 3])
  33. assert row_tensor[0].shape == (10, 6)
  34. def test_graphdata_getnodefeature_input_check():
  35. """
  36. Test get node feature input check
  37. """
  38. logger.info('test getnodefeature input check.\n')
  39. g = ds.GraphData(DATASET_FILE)
  40. with pytest.raises(TypeError):
  41. input_list = [1, [1, 1]]
  42. g.get_node_feature(input_list, [1])
  43. with pytest.raises(TypeError):
  44. input_list = [[1, 1], 1]
  45. g.get_node_feature(input_list, [1])
  46. with pytest.raises(TypeError):
  47. input_list = [[1, 1], [1, 1, 1]]
  48. g.get_node_feature(input_list, [1])
  49. with pytest.raises(TypeError):
  50. input_list = [[1, 1, 1], [1, 1]]
  51. g.get_node_feature(input_list, [1])
  52. with pytest.raises(TypeError):
  53. input_list = [[1, 1], [1, [1, 1]]]
  54. g.get_node_feature(input_list, [1])
  55. with pytest.raises(TypeError):
  56. input_list = [[1, 1], [[1, 1], 1]]
  57. g.get_node_feature(input_list, [1])
  58. with pytest.raises(TypeError):
  59. input_list = [[1, 1], [1, 1]]
  60. g.get_node_feature(input_list, 1)
  61. with pytest.raises(TypeError):
  62. input_list = [[1, 0.1], [1, 1]]
  63. g.get_node_feature(input_list, 1)
  64. with pytest.raises(TypeError):
  65. input_list = np.array([[1, 0.1], [1, 1]])
  66. g.get_node_feature(input_list, 1)
  67. with pytest.raises(TypeError):
  68. input_list = [[1, 1], [1, 1]]
  69. g.get_node_feature(input_list, ["a"])
  70. with pytest.raises(TypeError):
  71. input_list = [[1, 1], [1, 1]]
  72. g.get_node_feature(input_list, [1, "a"])
  73. def test_graphdata_getsampledneighbors():
  74. """
  75. Test sampled neighbors
  76. """
  77. logger.info('test get sampled neighbors.\n')
  78. g = ds.GraphData(DATASET_FILE, 1)
  79. edges = g.get_all_edges(0)
  80. nodes = g.get_nodes_from_edges(edges)
  81. assert len(nodes) == 40
  82. neighbor = g.get_sampled_neighbors(
  83. np.unique(nodes[0:21, 0]), [2, 3], [2, 1])
  84. assert neighbor.shape == (10, 9)
  85. def test_graphdata_getnegsampledneighbors():
  86. """
  87. Test neg sampled neighbors
  88. """
  89. logger.info('test get negative sampled neighbors.\n')
  90. g = ds.GraphData(DATASET_FILE, 2)
  91. nodes = g.get_all_nodes(1)
  92. assert len(nodes) == 10
  93. neighbor = g.get_neg_sampled_neighbors(nodes, 5, 2)
  94. assert neighbor.shape == (10, 6)
  95. def test_graphdata_graphinfo():
  96. """
  97. Test graph info
  98. """
  99. logger.info('test graph info.\n')
  100. g = ds.GraphData(DATASET_FILE, 2)
  101. graph_info = g.graph_info()
  102. assert graph_info['node_type'] == [1, 2]
  103. assert graph_info['edge_type'] == [0]
  104. assert graph_info['node_num'] == {1: 10, 2: 10}
  105. assert graph_info['edge_num'] == {0: 40}
  106. assert graph_info['node_feature_type'] == [1, 2, 3, 4]
  107. assert graph_info['edge_feature_type'] == [1, 2]
  108. class RandomBatchedSampler(ds.Sampler):
  109. # RandomBatchedSampler generate random sequence without replacement in a batched manner
  110. def __init__(self, index_range, num_edges_per_sample):
  111. super().__init__()
  112. self.index_range = index_range
  113. self.num_edges_per_sample = num_edges_per_sample
  114. def __iter__(self):
  115. indices = [i+1 for i in range(self.index_range)]
  116. # Reset random seed here if necessary
  117. # random.seed(0)
  118. random.shuffle(indices)
  119. for i in range(0, self.index_range, self.num_edges_per_sample):
  120. # Drop reminder
  121. if i + self.num_edges_per_sample <= self.index_range:
  122. yield indices[i: i + self.num_edges_per_sample]
  123. class GNNGraphDataset():
  124. def __init__(self, g, batch_num):
  125. self.g = g
  126. self.batch_num = batch_num
  127. def __len__(self):
  128. # Total sample size of GNN dataset
  129. # In this case, the size should be total_num_edges/num_edges_per_sample
  130. return self.g.graph_info()['edge_num'][0] // self.batch_num
  131. def __getitem__(self, index):
  132. # index will be a list of indices yielded from RandomBatchedSampler
  133. # Fetch edges/nodes/samples/features based on indices
  134. nodes = self.g.get_nodes_from_edges(index.astype(np.int32))
  135. nodes = nodes[:, 0]
  136. neg_nodes = self.g.get_neg_sampled_neighbors(
  137. node_list=nodes, neg_neighbor_num=3, neg_neighbor_type=1)
  138. nodes_neighbors = self.g.get_sampled_neighbors(node_list=nodes, neighbor_nums=[
  139. 2, 2], neighbor_types=[2, 1])
  140. neg_nodes_neighbors = self.g.get_sampled_neighbors(
  141. node_list=neg_nodes[:, 1:].reshape(-1), neighbor_nums=[2, 2], neighbor_types=[2, 2])
  142. nodes_neighbors_features = self.g.get_node_feature(
  143. node_list=nodes_neighbors, feature_types=[2, 3])
  144. neg_neighbors_features = self.g.get_node_feature(
  145. node_list=neg_nodes_neighbors, feature_types=[2, 3])
  146. return nodes_neighbors, neg_nodes_neighbors, nodes_neighbors_features[0], neg_neighbors_features[1]
  147. def test_graphdata_generatordataset():
  148. """
  149. Test generator dataset
  150. """
  151. logger.info('test generator dataset.\n')
  152. g = ds.GraphData(DATASET_FILE)
  153. batch_num = 2
  154. edge_num = g.graph_info()['edge_num'][0]
  155. out_column_names = ["neighbors", "neg_neighbors", "neighbors_features", "neg_neighbors_features"]
  156. dataset = ds.GeneratorDataset(source=GNNGraphDataset(g, batch_num), column_names=out_column_names,
  157. sampler=RandomBatchedSampler(edge_num, batch_num), num_parallel_workers=4)
  158. dataset = dataset.repeat(2)
  159. itr = dataset.create_dict_iterator()
  160. i = 0
  161. for data in itr:
  162. assert data['neighbors'].shape == (2, 7)
  163. assert data['neg_neighbors'].shape == (6, 7)
  164. assert data['neighbors_features'].shape == (2, 7)
  165. assert data['neg_neighbors_features'].shape == (6, 7)
  166. i += 1
  167. assert i == 40
  168. def test_graphdata_randomwalkdefault():
  169. """
  170. Test random walk defaults
  171. """
  172. logger.info('test randomwalk with default parameters.\n')
  173. g = ds.GraphData(SOCIAL_DATA_FILE, 1)
  174. nodes = g.get_all_nodes(1)
  175. assert len(nodes) == 33
  176. meta_path = [1 for _ in range(39)]
  177. walks = g.random_walk(nodes, meta_path)
  178. assert walks.shape == (33, 40)
  179. def test_graphdata_randomwalk():
  180. """
  181. Test random walk
  182. """
  183. logger.info('test random walk with given parameters.\n')
  184. g = ds.GraphData(SOCIAL_DATA_FILE, 1)
  185. nodes = g.get_all_nodes(1)
  186. assert len(nodes) == 33
  187. meta_path = [1 for _ in range(39)]
  188. walks = g.random_walk(nodes, meta_path, 2.0, 0.5, -1)
  189. assert walks.shape == (33, 40)
  190. def test_graphdata_getedgefeature():
  191. """
  192. Test get edge feature
  193. """
  194. logger.info('test get_edge_feature.\n')
  195. g = ds.GraphData(DATASET_FILE)
  196. edges = g.get_all_edges(0)
  197. features = g.get_edge_feature(edges, [1, 2])
  198. assert features[0].shape == (40,)
  199. assert features[1].shape == (40,)
  200. if __name__ == '__main__':
  201. test_graphdata_getfullneighbor()
  202. test_graphdata_getnodefeature_input_check()
  203. test_graphdata_getsampledneighbors()
  204. test_graphdata_getnegsampledneighbors()
  205. test_graphdata_graphinfo()
  206. test_graphdata_generatordataset()
  207. test_graphdata_randomwalkdefault()
  208. test_graphdata_randomwalk()
  209. test_graphdata_getedgefeature()