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.

train.py 3.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. GCN training script.
  17. """
  18. import time
  19. import argparse
  20. import numpy as np
  21. from mindspore import context
  22. from src.gcn import GCN, LossAccuracyWrapper, TrainNetWrapper
  23. from src.config import ConfigGCN
  24. from src.dataset import get_adj_features_labels, get_mask
  25. def train():
  26. """Train model."""
  27. parser = argparse.ArgumentParser(description='GCN')
  28. parser.add_argument('--data_dir', type=str, default='./data/cora/cora_mr', help='Dataset directory')
  29. parser.add_argument('--seed', type=int, default=123, help='Random seed')
  30. parser.add_argument('--train_nodes_num', type=int, default=140, help='Nodes numbers for training')
  31. parser.add_argument('--eval_nodes_num', type=int, default=500, help='Nodes numbers for evaluation')
  32. parser.add_argument('--test_nodes_num', type=int, default=1000, help='Nodes numbers for test')
  33. args_opt = parser.parse_args()
  34. np.random.seed(args_opt.seed)
  35. context.set_context(mode=context.GRAPH_MODE,
  36. device_target="Ascend", save_graphs=False)
  37. config = ConfigGCN()
  38. adj, feature, label = get_adj_features_labels(args_opt.data_dir)
  39. nodes_num = label.shape[0]
  40. train_mask = get_mask(nodes_num, 0, args_opt.train_nodes_num)
  41. eval_mask = get_mask(nodes_num, args_opt.train_nodes_num, args_opt.train_nodes_num + args_opt.eval_nodes_num)
  42. test_mask = get_mask(nodes_num, nodes_num - args_opt.test_nodes_num, nodes_num)
  43. class_num = label.shape[1]
  44. gcn_net = GCN(config, adj, feature, class_num)
  45. gcn_net.add_flags_recursive(fp16=True)
  46. eval_net = LossAccuracyWrapper(gcn_net, label, eval_mask, config.weight_decay)
  47. test_net = LossAccuracyWrapper(gcn_net, label, test_mask, config.weight_decay)
  48. train_net = TrainNetWrapper(gcn_net, label, train_mask, config)
  49. loss_list = []
  50. for epoch in range(config.epochs):
  51. t = time.time()
  52. train_net.set_train()
  53. train_result = train_net()
  54. train_loss = train_result[0].asnumpy()
  55. train_accuracy = train_result[1].asnumpy()
  56. eval_net.set_train(False)
  57. eval_result = eval_net()
  58. eval_loss = eval_result[0].asnumpy()
  59. eval_accuracy = eval_result[1].asnumpy()
  60. loss_list.append(eval_loss)
  61. print("Epoch:", '%04d' % (epoch + 1), "train_loss=", "{:.5f}".format(train_loss),
  62. "train_acc=", "{:.5f}".format(train_accuracy), "val_loss=", "{:.5f}".format(eval_loss),
  63. "val_acc=", "{:.5f}".format(eval_accuracy), "time=", "{:.5f}".format(time.time() - t))
  64. if epoch > config.early_stopping and loss_list[-1] > np.mean(loss_list[-(config.early_stopping+1):-1]):
  65. print("Early stopping...")
  66. break
  67. t_test = time.time()
  68. test_net.set_train(False)
  69. test_result = test_net()
  70. test_loss = test_result[0].asnumpy()
  71. test_accuracy = test_result[1].asnumpy()
  72. print("Test set results:", "loss=", "{:.5f}".format(test_loss),
  73. "accuracy=", "{:.5f}".format(test_accuracy), "time=", "{:.5f}".format(time.time() - t_test))
  74. if __name__ == '__main__':
  75. train()