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.

eval.py 4.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. """FastText for Evaluation"""
  16. import argparse
  17. import numpy as np
  18. import mindspore.nn as nn
  19. import mindspore.common.dtype as mstype
  20. import mindspore.ops.operations as P
  21. from mindspore.common.tensor import Tensor
  22. from mindspore.train.model import Model
  23. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  24. import mindspore.dataset as ds
  25. import mindspore.dataset.transforms.c_transforms as deC
  26. from mindspore import context
  27. from src.fasttext_model import FastText
  28. parser = argparse.ArgumentParser(description='fasttext')
  29. parser.add_argument('--data_path', type=str, help='infer dataset path..')
  30. parser.add_argument('--data_name', type=str, required=True, default='ag',
  31. help='dataset name. eg. ag, dbpedia')
  32. parser.add_argument("--model_ckpt", type=str, required=True,
  33. help="existed checkpoint address.")
  34. args = parser.parse_args()
  35. if args.data_name == "ag":
  36. from src.config import config_ag as config
  37. target_label1 = ['0', '1', '2', '3']
  38. elif args.data_name == 'dbpedia':
  39. from src.config import config_db as config
  40. target_label1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']
  41. elif args.data_name == 'yelp_p':
  42. from src.config import config_yelpp as config
  43. target_label1 = ['0', '1']
  44. context.set_context(
  45. mode=context.GRAPH_MODE,
  46. save_graphs=False,
  47. device_target="Ascend")
  48. class FastTextInferCell(nn.Cell):
  49. """
  50. Encapsulation class of FastText network infer.
  51. Args:
  52. network (nn.Cell): FastText model.
  53. Returns:
  54. Tuple[Tensor, Tensor], predicted_ids
  55. """
  56. def __init__(self, network):
  57. super(FastTextInferCell, self).__init__(auto_prefix=False)
  58. self.network = network
  59. self.argmax = P.ArgMaxWithValue(axis=1, keep_dims=True)
  60. self.log_softmax = nn.LogSoftmax(axis=1)
  61. def construct(self, src_tokens, src_tokens_lengths):
  62. """construct fasttext infer cell"""
  63. prediction = self.network(src_tokens, src_tokens_lengths)
  64. predicted_idx = self.log_softmax(prediction)
  65. predicted_idx, _ = self.argmax(predicted_idx)
  66. return predicted_idx
  67. def load_infer_dataset(batch_size, datafile):
  68. """data loader for infer"""
  69. data_set = ds.MindDataset(datafile, columns_list=['src_tokens', 'src_tokens_length', 'label_idx'])
  70. type_cast_op = deC.TypeCast(mstype.int32)
  71. data_set = data_set.map(operations=type_cast_op, input_columns="src_tokens")
  72. data_set = data_set.map(operations=type_cast_op, input_columns="src_tokens_length")
  73. data_set = data_set.map(operations=type_cast_op, input_columns="label_idx")
  74. data_set = data_set.batch(batch_size=batch_size, drop_remainder=True)
  75. return data_set
  76. def run_fasttext_infer():
  77. """run infer with FastText"""
  78. dataset = load_infer_dataset(batch_size=config.batch_size, datafile=args.data_path)
  79. fasttext_model = FastText(config.vocab_size, config.embedding_dims, config.num_class)
  80. parameter_dict = load_checkpoint(args.model_ckpt)
  81. load_param_into_net(fasttext_model, parameter_dict=parameter_dict)
  82. ft_infer = FastTextInferCell(fasttext_model)
  83. model = Model(ft_infer)
  84. predictions = []
  85. target_sens = []
  86. for batch in dataset.create_dict_iterator(output_numpy=True, num_epochs=1):
  87. target_sens.append(batch['label_idx'])
  88. src_tokens = Tensor(batch['src_tokens'], mstype.int32)
  89. src_tokens_length = Tensor(batch['src_tokens_length'], mstype.int32)
  90. predicted_idx = model.predict(src_tokens, src_tokens_length)
  91. predictions.append(predicted_idx.asnumpy())
  92. from sklearn.metrics import accuracy_score, classification_report
  93. target_sens = np.array(target_sens).flatten()
  94. predictions = np.array(predictions).flatten()
  95. acc = accuracy_score(target_sens, predictions)
  96. result_report = classification_report(target_sens, predictions, target_names=target_label1)
  97. print("********Accuracy: ", acc)
  98. print(result_report)
  99. if __name__ == '__main__':
  100. run_fasttext_infer()