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.1 kB

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