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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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 os
  19. import time
  20. import argparse
  21. import ast
  22. import numpy as np
  23. from matplotlib import pyplot as plt
  24. from matplotlib import animation
  25. from sklearn import manifold
  26. from mindspore import context
  27. from mindspore import Tensor
  28. from mindspore.train.serialization import save_checkpoint, load_checkpoint
  29. from src.gcn import GCN
  30. from src.metrics import LossAccuracyWrapper, TrainNetWrapper
  31. from src.config import ConfigGCN
  32. from src.dataset import get_adj_features_labels, get_mask
  33. def t_SNE(out_feature, dim):
  34. t_sne = manifold.TSNE(n_components=dim, init='pca', random_state=0)
  35. return t_sne.fit_transform(out_feature)
  36. def update_graph(i, data, scat, plot):
  37. scat.set_offsets(data[i])
  38. plt.title('t-SNE visualization of Epoch:{0}'.format(i))
  39. return scat, plot
  40. def train():
  41. """Train model."""
  42. parser = argparse.ArgumentParser(description='GCN')
  43. parser.add_argument('--data_dir', type=str, default='./data/cora/cora_mr', help='Dataset directory')
  44. parser.add_argument('--train_nodes_num', type=int, default=140, help='Nodes numbers for training')
  45. parser.add_argument('--eval_nodes_num', type=int, default=500, help='Nodes numbers for evaluation')
  46. parser.add_argument('--test_nodes_num', type=int, default=1000, help='Nodes numbers for test')
  47. parser.add_argument('--save_TSNE', type=ast.literal_eval, default=False, help='Whether to save t-SNE graph')
  48. args_opt = parser.parse_args()
  49. if not os.path.exists("ckpts"):
  50. os.mkdir("ckpts")
  51. context.set_context(mode=context.GRAPH_MODE,
  52. device_target="Ascend", save_graphs=False)
  53. config = ConfigGCN()
  54. adj, feature, label_onehot, label = get_adj_features_labels(args_opt.data_dir)
  55. nodes_num = label_onehot.shape[0]
  56. train_mask = get_mask(nodes_num, 0, args_opt.train_nodes_num)
  57. eval_mask = get_mask(nodes_num, args_opt.train_nodes_num, args_opt.train_nodes_num + args_opt.eval_nodes_num)
  58. test_mask = get_mask(nodes_num, nodes_num - args_opt.test_nodes_num, nodes_num)
  59. class_num = label_onehot.shape[1]
  60. input_dim = feature.shape[1]
  61. gcn_net = GCN(config, input_dim, class_num)
  62. gcn_net.add_flags_recursive(fp16=True)
  63. adj = Tensor(adj)
  64. feature = Tensor(feature)
  65. eval_net = LossAccuracyWrapper(gcn_net, label_onehot, eval_mask, config.weight_decay)
  66. train_net = TrainNetWrapper(gcn_net, label_onehot, train_mask, config)
  67. loss_list = []
  68. if args_opt.save_TSNE:
  69. out_feature = gcn_net()
  70. tsne_result = t_SNE(out_feature.asnumpy(), 2)
  71. graph_data = []
  72. graph_data.append(tsne_result)
  73. fig = plt.figure()
  74. scat = plt.scatter(tsne_result[:, 0], tsne_result[:, 1], s=2, c=label, cmap='rainbow')
  75. plt.title('t-SNE visualization of Epoch:0', fontsize='large', fontweight='bold', verticalalignment='center')
  76. for epoch in range(config.epochs):
  77. t = time.time()
  78. train_net.set_train()
  79. train_result = train_net(adj, feature)
  80. train_loss = train_result[0].asnumpy()
  81. train_accuracy = train_result[1].asnumpy()
  82. eval_net.set_train(False)
  83. eval_result = eval_net(adj, feature)
  84. eval_loss = eval_result[0].asnumpy()
  85. eval_accuracy = eval_result[1].asnumpy()
  86. loss_list.append(eval_loss)
  87. print("Epoch:", '%04d' % (epoch + 1), "train_loss=", "{:.5f}".format(train_loss),
  88. "train_acc=", "{:.5f}".format(train_accuracy), "val_loss=", "{:.5f}".format(eval_loss),
  89. "val_acc=", "{:.5f}".format(eval_accuracy), "time=", "{:.5f}".format(time.time() - t))
  90. if args_opt.save_TSNE:
  91. out_feature = gcn_net()
  92. tsne_result = t_SNE(out_feature.asnumpy(), 2)
  93. graph_data.append(tsne_result)
  94. if epoch > config.early_stopping and loss_list[-1] > np.mean(loss_list[-(config.early_stopping+1):-1]):
  95. print("Early stopping...")
  96. break
  97. save_checkpoint(gcn_net, "ckpts/gcn.ckpt")
  98. gcn_net_test = GCN(config, input_dim, class_num)
  99. load_checkpoint("ckpts/gcn.ckpt", net=gcn_net_test)
  100. gcn_net_test.add_flags_recursive(fp16=True)
  101. test_net = LossAccuracyWrapper(gcn_net_test, label_onehot, test_mask, config.weight_decay)
  102. t_test = time.time()
  103. test_net.set_train(False)
  104. test_result = test_net(adj, feature)
  105. test_loss = test_result[0].asnumpy()
  106. test_accuracy = test_result[1].asnumpy()
  107. print("Test set results:", "loss=", "{:.5f}".format(test_loss),
  108. "accuracy=", "{:.5f}".format(test_accuracy), "time=", "{:.5f}".format(time.time() - t_test))
  109. if args_opt.save_TSNE:
  110. ani = animation.FuncAnimation(fig, update_graph, frames=range(config.epochs + 1), fargs=(graph_data, scat, plt))
  111. ani.save('t-SNE_visualization.gif', writer='imagemagick')
  112. if __name__ == '__main__':
  113. train()