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 7.5 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. g = ds.GraphData(DATASET_FILE, 2)
  24. nodes = g.get_all_nodes(1)
  25. assert len(nodes) == 10
  26. neighbor = g.get_all_neighbors(nodes, 2)
  27. assert neighbor.shape == (10, 6)
  28. row_tensor = g.get_node_feature(neighbor.tolist(), [2, 3])
  29. assert row_tensor[0].shape == (10, 6)
  30. def test_graphdata_getnodefeature_input_check():
  31. g = ds.GraphData(DATASET_FILE)
  32. with pytest.raises(TypeError):
  33. input_list = [1, [1, 1]]
  34. g.get_node_feature(input_list, [1])
  35. with pytest.raises(TypeError):
  36. input_list = [[1, 1], 1]
  37. g.get_node_feature(input_list, [1])
  38. with pytest.raises(TypeError):
  39. input_list = [[1, 1], [1, 1, 1]]
  40. g.get_node_feature(input_list, [1])
  41. with pytest.raises(TypeError):
  42. input_list = [[1, 1, 1], [1, 1]]
  43. g.get_node_feature(input_list, [1])
  44. with pytest.raises(TypeError):
  45. input_list = [[1, 1], [1, [1, 1]]]
  46. g.get_node_feature(input_list, [1])
  47. with pytest.raises(TypeError):
  48. input_list = [[1, 1], [[1, 1], 1]]
  49. g.get_node_feature(input_list, [1])
  50. with pytest.raises(TypeError):
  51. input_list = [[1, 1], [1, 1]]
  52. g.get_node_feature(input_list, 1)
  53. with pytest.raises(TypeError):
  54. input_list = [[1, 0.1], [1, 1]]
  55. g.get_node_feature(input_list, 1)
  56. with pytest.raises(TypeError):
  57. input_list = np.array([[1, 0.1], [1, 1]])
  58. g.get_node_feature(input_list, 1)
  59. with pytest.raises(TypeError):
  60. input_list = [[1, 1], [1, 1]]
  61. g.get_node_feature(input_list, ["a"])
  62. with pytest.raises(TypeError):
  63. input_list = [[1, 1], [1, 1]]
  64. g.get_node_feature(input_list, [1, "a"])
  65. def test_graphdata_getsampledneighbors():
  66. g = ds.GraphData(DATASET_FILE, 1)
  67. edges = g.get_all_edges(0)
  68. nodes = g.get_nodes_from_edges(edges)
  69. assert len(nodes) == 40
  70. neighbor = g.get_sampled_neighbors(
  71. np.unique(nodes[0:21, 0]), [2, 3], [2, 1])
  72. assert neighbor.shape == (10, 9)
  73. def test_graphdata_getnegsampledneighbors():
  74. g = ds.GraphData(DATASET_FILE, 2)
  75. nodes = g.get_all_nodes(1)
  76. assert len(nodes) == 10
  77. neighbor = g.get_neg_sampled_neighbors(nodes, 5, 2)
  78. assert neighbor.shape == (10, 6)
  79. def test_graphdata_graphinfo():
  80. g = ds.GraphData(DATASET_FILE, 2)
  81. graph_info = g.graph_info()
  82. assert graph_info['node_type'] == [1, 2]
  83. assert graph_info['edge_type'] == [0]
  84. assert graph_info['node_num'] == {1: 10, 2: 10}
  85. assert graph_info['edge_num'] == {0: 40}
  86. assert graph_info['node_feature_type'] == [1, 2, 3, 4]
  87. assert graph_info['edge_feature_type'] == []
  88. class RandomBatchedSampler(ds.Sampler):
  89. # RandomBatchedSampler generate random sequence without replacement in a batched manner
  90. def __init__(self, index_range, num_edges_per_sample):
  91. super().__init__()
  92. self.index_range = index_range
  93. self.num_edges_per_sample = num_edges_per_sample
  94. def __iter__(self):
  95. indices = [i+1 for i in range(self.index_range)]
  96. # Reset random seed here if necessary
  97. # random.seed(0)
  98. random.shuffle(indices)
  99. for i in range(0, self.index_range, self.num_edges_per_sample):
  100. # Drop reminder
  101. if i + self.num_edges_per_sample <= self.index_range:
  102. yield indices[i: i + self.num_edges_per_sample]
  103. class GNNGraphDataset():
  104. def __init__(self, g, batch_num):
  105. self.g = g
  106. self.batch_num = batch_num
  107. def __len__(self):
  108. # Total sample size of GNN dataset
  109. # In this case, the size should be total_num_edges/num_edges_per_sample
  110. return self.g.graph_info()['edge_num'][0] // self.batch_num
  111. def __getitem__(self, index):
  112. # index will be a list of indices yielded from RandomBatchedSampler
  113. # Fetch edges/nodes/samples/features based on indices
  114. nodes = self.g.get_nodes_from_edges(index.astype(np.int32))
  115. nodes = nodes[:, 0]
  116. neg_nodes = self.g.get_neg_sampled_neighbors(
  117. node_list=nodes, neg_neighbor_num=3, neg_neighbor_type=1)
  118. nodes_neighbors = self.g.get_sampled_neighbors(node_list=nodes, neighbor_nums=[
  119. 2, 2], neighbor_types=[2, 1])
  120. neg_nodes_neighbors = self.g.get_sampled_neighbors(
  121. node_list=neg_nodes[:, 1:].reshape(-1), neighbor_nums=[2, 2], neighbor_types=[2, 2])
  122. nodes_neighbors_features = self.g.get_node_feature(
  123. node_list=nodes_neighbors, feature_types=[2, 3])
  124. neg_neighbors_features = self.g.get_node_feature(
  125. node_list=neg_nodes_neighbors, feature_types=[2, 3])
  126. return nodes_neighbors, neg_nodes_neighbors, nodes_neighbors_features[0], neg_neighbors_features[1]
  127. def test_graphdata_generatordataset():
  128. g = ds.GraphData(DATASET_FILE)
  129. batch_num = 2
  130. edge_num = g.graph_info()['edge_num'][0]
  131. out_column_names = ["neighbors", "neg_neighbors", "neighbors_features", "neg_neighbors_features"]
  132. dataset = ds.GeneratorDataset(source=GNNGraphDataset(g, batch_num), column_names=out_column_names,
  133. sampler=RandomBatchedSampler(edge_num, batch_num), num_parallel_workers=4)
  134. dataset = dataset.repeat(2)
  135. itr = dataset.create_dict_iterator()
  136. i = 0
  137. for data in itr:
  138. assert data['neighbors'].shape == (2, 7)
  139. assert data['neg_neighbors'].shape == (6, 7)
  140. assert data['neighbors_features'].shape == (2, 7)
  141. assert data['neg_neighbors_features'].shape == (6, 7)
  142. i += 1
  143. assert i == 40
  144. def test_graphdata_randomwalk():
  145. g = ds.GraphData(SOCIAL_DATA_FILE, 1)
  146. nodes = g.get_all_nodes(1)
  147. print(len(nodes))
  148. assert len(nodes) == 33
  149. meta_path = [1 for _ in range(39)]
  150. walks = g.random_walk(nodes, meta_path)
  151. assert walks.shape == (33, 40)
  152. if __name__ == '__main__':
  153. test_graphdata_getfullneighbor()
  154. logger.info('test_graphdata_getfullneighbor Ended.\n')
  155. test_graphdata_getnodefeature_input_check()
  156. logger.info('test_graphdata_getnodefeature_input_check Ended.\n')
  157. test_graphdata_getsampledneighbors()
  158. logger.info('test_graphdata_getsampledneighbors Ended.\n')
  159. test_graphdata_getnegsampledneighbors()
  160. logger.info('test_graphdata_getnegsampledneighbors Ended.\n')
  161. test_graphdata_graphinfo()
  162. logger.info('test_graphdata_graphinfo Ended.\n')
  163. test_graphdata_generatordataset()
  164. logger.info('test_graphdata_generatordataset Ended.\n')
  165. test_graphdata_randomwalk()
  166. logger.info('test_graphdata_randomwalk Ended.\n')