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.

README.md 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # Contents
  2. - [NCF Description](#NCF-description)
  3. - [Model Architecture](#model-architecture)
  4. - [Dataset](#dataset)
  5. - [Features](#features)
  6. - [Mixed Precision](#mixed-precision)
  7. - [Environment Requirements](#environment-requirements)
  8. - [Quick Start](#quick-start)
  9. - [Script Description](#script-description)
  10. - [Script and Sample Code](#script-and-sample-code)
  11. - [Script Parameters](#script-parameters)
  12. - [Training Process](#training-process)
  13. - [Training](#training)
  14. - [Distributed Training](#distributed-training)
  15. - [Evaluation Process](#evaluation-process)
  16. - [Evaluation](#evaluation)
  17. - [Model Description](#model-description)
  18. - [Performance](#performance)
  19. - [Evaluation Performance](#evaluation-performance)
  20. - [Inference Performance](#evaluation-performance)
  21. - [How to use](#how-to-use)
  22. - [Inference](#inference)
  23. - [Continue Training on the Pretrained Model](#continue-training-on-the-pretrained-model)
  24. - [Transfer Learning](#transfer-learning)
  25. - [Description of Random Situation](#description-of-random-situation)
  26. - [ModelZoo Homepage](#modelzoo-homepage)
  27. # [NCF Description](#contents)
  28. NCF is a general framework for collaborative filtering of recommendations in which a neural network architecture is used to model user-item interactions. Unlike traditional models, NCF does not resort to Matrix Factorization (MF) with an inner product on latent features of users and items. It replaces the inner product with a multi-layer perceptron that can learn an arbitrary function from data.
  29. [Paper](https://arxiv.org/abs/1708.05031): He X, Liao L, Zhang H, et al. Neural collaborative filtering[C]//Proceedings of the 26th international conference on world wide web. 2017: 173-182.
  30. # [Model Architecture](#contents)
  31. Two instantiations of NCF are Generalized Matrix Factorization (GMF) and Multi-Layer Perceptron (MLP). GMF applies a linear kernel to model the latent feature interactions, and and MLP uses a nonlinear kernel to learn the interaction function from data. NeuMF is a fused model of GMF and MLP to better model the complex user-item interactions, and unifies the strengths of linearity of MF and non-linearity of MLP for modeling the user-item latent structures. NeuMF allows GMF and MLP to learn separate embeddings, and combines the two models by concatenating their last hidden layer. [neumf_model.py](neumf_model.py) defines the architecture details.
  32. # [Dataset](#contents)
  33. The [MovieLens datasets](http://files.grouplens.org/datasets/movielens/) are used for model training and evaluation. Specifically, we use two datasets: **ml-1m** (short for MovieLens 1 million) and **ml-20m** (short for MovieLens 20 million).
  34. ### ml-1m
  35. ml-1m dataset contains 1,000,209 anonymous ratings of approximately 3,706 movies made by 6,040 users who joined MovieLens in 2000. All ratings are contained in the file "ratings.dat" without header row, and are in the following format:
  36. ```
  37. UserID::MovieID::Rating::Timestamp
  38. ```
  39. - UserIDs range between 1 and 6040.
  40. - MovieIDs range between 1 and 3952.
  41. - Ratings are made on a 5-star scale (whole-star ratings only).
  42. ### ml-20m
  43. ml-20m dataset contains 20,000,263 ratings of 26,744 movies by 138493 users. All ratings are contained in the file "ratings.csv". Each line of this file after the header row represents one rating of one movie by one user, and has the following format:
  44. ```
  45. userId,movieId,rating,timestamp
  46. ```
  47. - The lines within this file are ordered first by userId, then, within user, by movieId.
  48. - Ratings are made on a 5-star scale, with half-star increments (0.5 stars - 5.0 stars).
  49. In both datasets, the timestamp is represented in seconds since midnight Coordinated Universal Time (UTC) of January 1, 1970. Each user has at least 20 ratings.
  50. # [Features](#contents)
  51. ## Mixed Precision
  52. The [mixed precision](https://www.mindspore.cn/tutorial/zh-CN/master/advanced_use/mixed_precision.html) training method accelerates the deep learning neural network training process by using both the single-precision and half-precision data formats, and maintains the network precision achieved by the single-precision training at the same time. Mixed precision training can accelerate the computation process, reduce memory usage, and enable a larger model or batch size to be trained on specific hardware.
  53. For FP16 operators, if the input data type is FP32, the backend of MindSpore will automatically handle it with reduced precision. Users could check the reduced-precision operators by enabling INFO log and then searching ‘reduce precision’.
  54. # [Environment Requirements](#contents)
  55. - Hardware(Ascend/GPU)
  56. - Prepare hardware environment with Ascend or GPU processor. If you want to try Ascend , please send the [application form](https://obs-9be7.obs.cn-east-2.myhuaweicloud.com/file/other/Ascend%20Model%20Zoo%E4%BD%93%E9%AA%8C%E8%B5%84%E6%BA%90%E7%94%B3%E8%AF%B7%E8%A1%A8.docx) to ascend@huawei.com. Once approved, you can get the resources.
  57. - Framework
  58. - [MindSpore](https://www.mindspore.cn/install/en)
  59. - For more information, please check the resources below:
  60. - [MindSpore tutorials](https://www.mindspore.cn/tutorial/zh-CN/master/index.html)
  61. - [MindSpore API](https://www.mindspore.cn/api/zh-CN/master/index.html)
  62. # [Quick Start](#contents)
  63. After installing MindSpore via the official website, you can start training and evaluation as follows:
  64. ```python
  65. #run data process
  66. bash scripts/run_download_dataset.sh
  67. # run training example
  68. bash scripts/run_train.sh
  69. # run distributed training example
  70. sh scripts/run_train.sh rank_table.json
  71. # run evaluation example
  72. sh run_eval.sh
  73. ```
  74. # [Script Description](#contents)
  75. ## [Script and Sample Code](#contents)
  76. ```
  77. ├── ModelZoo_NCF_ME
  78. ├── README.md // descriptions about NCF
  79. ├── scripts
  80. │ ├──run_train.sh // shell script for train
  81. │ ├──run_distribute_train.sh // shell script for distribute train
  82. │ ├──run_eval.sh // shell script for evaluation
  83. │ ├──run_download_dataset.sh // shell script for dataget and process
  84. │ ├──run_transfer_ckpt_to_air.sh // shell script for transfer model style
  85. ├── src
  86. │ ├──dataset.py // creating dataset
  87. │ ├──ncf.py // ncf architecture
  88. │ ├──config.py // parameter configuration
  89. │ ├──movielens.py // data download file
  90. │ ├──callbacks.py // model loss and eval callback file
  91. │ ├──constants.py // the constants of model
  92. │ ├──export.py // export checkpoint files into geir/onnx
  93. │ ├──metrics.py // the file for auc compute
  94. │ ├──stat_utils.py // the file for data process functions
  95. ├── train.py // training script
  96. ├── eval.py // evaluation script
  97. ```
  98. ## [Script Parameters](#contents)
  99. Parameters for both training and evaluation can be set in config.py.
  100. - config for NCF, ml-1m dataset
  101. ```python
  102. * `--data_path`: This should be set to the same directory given to the data_download data_dir argument.
  103. * `--dataset`: The dataset name to be downloaded and preprocessed. By default, it is ml-1m.
  104. * `--train_epochs`: Total train epochs.
  105. * `--batch_size`: Training batch size.
  106. * `--eval_batch_size`: Eval batch size.
  107. * `--num_neg`: The Number of negative instances to pair with a positive instance.
  108. * `--layers`: The sizes of hidden layers for MLP.
  109. * `--num_factors`:The Embedding size of MF model.
  110. * `--output_path`:The location of the output file.
  111. * `--eval_file_name` : Eval output file.
  112. * `--loss_file_name` : Loss output file.
  113. ```
  114. ## [Training Process](#contents)
  115. ### Training
  116. ```python
  117. bash scripts/run_train.sh
  118. ```
  119. The python command above will run in the background, you can view the results through the file `train.log`. After training, you'll get some checkpoint files under the script folder by default. The loss value will be achieved as follows:
  120. ```python
  121. # grep "loss is " train.log
  122. ds_train.size: 95
  123. epoch: 1 step: 95, loss is 0.25074288
  124. epoch: 2 step: 95, loss is 0.23324402
  125. epoch: 3 step: 95, loss is 0.18286772
  126. ...
  127. ```
  128. The model checkpoint will be saved in the current directory.
  129. ## [Evaluation Process](#contents)
  130. ### Evaluation
  131. - evaluation on ml-1m dataset when running on Ascend
  132. Before running the command below, please check the checkpoint path used for evaluation. Please set the checkpoint path to be the absolute full path, e.g., "checkpoint/ncf-125_390.ckpt".
  133. ```python
  134. sh scripts/run_eval.sh
  135. ```
  136. The above python command will run in the background. You can view the results through the file "eval.log". The accuracy of the test dataset will be as follows:
  137. ```python
  138. # grep "accuracy: " eval.log
  139. HR:0.6846,NDCG:0.410
  140. ```
  141. # [Model Description](#contents)
  142. ## [Performance](#contents)
  143. ### Evaluation Performance
  144. | Parameters | Ascend |
  145. | -------------------------- | ------------------------------------------------------------ |
  146. | Model Version | NCF |
  147. | Resource | Ascend 910 ;CPU 2.60GHz,56cores;Memory,314G |
  148. | uploaded Date | 10/23/2020 (month/day/year) |
  149. | MindSpore Version | 1.0.0 |
  150. | Dataset | ml-1m |
  151. | Training Parameters | epoch=25, steps=19418, batch_size = 256, lr=0.00382059 |
  152. | Optimizer | GradOperation |
  153. | Loss Function | Softmax Cross Entropy |
  154. | outputs | probability |
  155. | Speed | 1pc: 0.575 ms/step |
  156. | Total time | 1pc: 5 mins |
  157. ### Inference Performance
  158. | Parameters | Ascend |
  159. | ------------------- | --------------------------- |
  160. | Model Version | NCF |
  161. | Resource | Ascend 910 |
  162. | Uploaded Date | 10/23/2020 (month/day/year) |
  163. | MindSpore Version | 1.0.0 |
  164. | Dataset | ml-1m |
  165. | batch_size | 256 |
  166. | outputs | probability |
  167. | Accuracy | HR:0.6846,NDCG:0.410 |
  168. ## [How to use](#contents)
  169. ### Inference
  170. If you need to use the trained model to perform inference on multiple hardware platforms, such as GPU, Ascend 910 or Ascend 310, you can refer to this [Link](https://www.mindspore.cn/tutorial/zh-CN/master/advanced_use/network_migration.html). Following the steps below, this is a simple example:
  171. https://www.mindspore.cn/tutorial/zh-CN/master/use/multi_platform_inference.html
  172. ```
  173. # Load unseen dataset for inference
  174. dataset = dataset.create_dataset(cfg.data_path, 1, False)
  175. # Define model
  176. net = GoogleNet(num_classes=cfg.num_classes)
  177. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()), 0.01,
  178. cfg.momentum, weight_decay=cfg.weight_decay)
  179. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean',
  180. is_grad=False)
  181. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'})
  182. # Load pre-trained model
  183. param_dict = load_checkpoint(cfg.checkpoint_path)
  184. load_param_into_net(net, param_dict)
  185. net.set_train(False)
  186. # Make predictions on the unseen dataset
  187. acc = model.eval(dataset)
  188. print("accuracy: ", acc)
  189. ```
  190. ### Continue Training on the Pretrained Model
  191. ```
  192. # Load dataset
  193. dataset = create_dataset(cfg.data_path, cfg.epoch_size)
  194. batch_num = dataset.get_dataset_size()
  195. # Define model
  196. net = GoogleNet(num_classes=cfg.num_classes)
  197. # Continue training if set pre_trained to be True
  198. if cfg.pre_trained:
  199. param_dict = load_checkpoint(cfg.checkpoint_path)
  200. load_param_into_net(net, param_dict)
  201. lr = lr_steps(0, lr_max=cfg.lr_init, total_epochs=cfg.epoch_size,
  202. steps_per_epoch=batch_num)
  203. opt = Momentum(filter(lambda x: x.requires_grad, net.get_parameters()),
  204. Tensor(lr), cfg.momentum, weight_decay=cfg.weight_decay)
  205. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean', is_grad=False)
  206. model = Model(net, loss_fn=loss, optimizer=opt, metrics={'acc'},
  207. amp_level="O2", keep_batchnorm_fp32=False, loss_scale_manager=None)
  208. # Set callbacks
  209. config_ck = CheckpointConfig(save_checkpoint_steps=batch_num * 5,
  210. keep_checkpoint_max=cfg.keep_checkpoint_max)
  211. time_cb = TimeMonitor(data_size=batch_num)
  212. ckpoint_cb = ModelCheckpoint(prefix="train_googlenet_cifar10", directory="./",
  213. config=config_ck)
  214. loss_cb = LossMonitor()
  215. # Start training
  216. model.train(cfg.epoch_size, dataset, callbacks=[time_cb, ckpoint_cb, loss_cb])
  217. print("train success")
  218. ```
  219. # [Description of Random Situation](#contents)
  220. In dataset.py, we set the seed inside “create_dataset" function. We also use random seed in train.py.
  221. # [ModelZoo Homepage](#contents)
  222. Please check the official [homepage](https://gitee.com/mindspore/mindspore/tree/master/model_zoo).