README.en.ipynb 27.7 KB
Notebook
Newer Older
G
gongweibao 已提交
1 2 3 4 5 6 7 8 9 10
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Personalized Recommendation\n",
        "\n",
        "The source code of this tutorial is in [book/recommender_system](https://github.com/PaddlePaddle/book/tree/develop/recommender_system).\n",
        "\n",
G
gongweibao 已提交
11 12 13
        "For instructions on getting started with PaddlePaddle, see [PaddlePaddle installation guide](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/getstarted/build_and_install/docker_install_en.rst).\n",
        "\n",
        "\n",
G
gongweibao 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
        "## Background\n",
        "\n",
        "With the fast growth of e-commerce, online videos, and online reading business, users have to rely on recommender systems to avoid manually browsing tremendous volume of choices.  Recommender systems understand users' interest by mining user behavior and other properties of users and products.\n",
        "\n",
        "Some well know approaches include:\n",
        "\n",
        "- User behavior-based approach.  A well-known method is collaborative filtering. The underlying assumption is that if a person A has the same opinion as a person B on an issue, A is more likely to have B's opinion on a different issue than that of a randomly chosen person.\n",
        "\n",
        "- Content-based recommendation[[1](#reference)]. This approach infers feature vectors that represent products from their descriptions.  It also infers feature vectors that represent users' interests.  Then it measures the relevance of users and products by some distances between these feature vectors.\n",
        "\n",
        "- Hybrid approach[[2](#reference)]: This approach uses the content-based information to help address the cold start problem[[6](#reference)] in behavior-based approach.\n",
        "\n",
        "Among these options, collaborative filtering might be the most studied one.  Some of its variants include user-based[[3](#reference)], item-based [[4](#reference)], social network based[[5](#reference)], and model-based.\n",
        "\n",
        "This tutorial explains a deep learning based approach and how to implement it using PaddlePaddle.  We will train a model using a dataset that includes user information, movie information, and ratings.  Once we train the model, we will be able to get a predicted rating given a pair of user and movie IDs.\n",
        "\n",
        "\n",
        "## Model Overview\n",
        "\n",
        "To know more about deep learning based recommendation, let us start from going over the Youtube recommender system[[7](#参考文献)] before introducing our hybrid model.\n",
        "\n",
        "\n",
        "### YouTube's Deep Learning Recommendation Model\n",
        "\n",
        "YouTube is a video-sharing Web site with one of the largest user base in the world.  Its recommender system serves more than a billion users.  This system is composed of two major parts: candidate generation and ranking.  The former selects few hundreds of candidates from millions of videos, and the latter ranks and outputs the top 10.\n",
        "\n",
        "\u003cp align=\"center\"\u003e\n",
        "\u003cimg src=\"image/YouTube_Overview.en.png\" width=\"70%\" \u003e\u003cbr/\u003e\n",
        "Figure 1. YouTube recommender system overview.\n",
        "\u003c/p\u003e\n",
        "\n",
        "#### Candidate Generation Network\n",
        "\n",
        "Youtube models candidate generation as a multiclass classification problem with a huge number of classes equal to the number of videos.  The architecture of the model is as follows:\n",
        "\n",
        "\u003cp align=\"center\"\u003e\n",
        "\u003cimg src=\"image/Deep_candidate_generation_model_architecture.en.png\" width=\"70%\" \u003e\u003cbr/\u003e\n",
        "Figure. Deep candidate geeration model.\n",
        "\u003c/p\u003e\n",
        "\n",
        "The first stage of this model maps watching history and search queries into fixed-length representative features.  Then, an MLP (multi-layer perceptron, as described in the [Recognize Digits](https://github.com/PaddlePaddle/book/blob/develop/recognize_digits/README.md) tutorial) takes the concatenation of all representative vectors.  The output of the MLP represents the user' *intrinsic interests*.  At training time, it is used together with a softmax output layer for minimizing the classification error.   At serving time, it is used to compute the relevance of the user with all movies.\n",
        "\n",
        "For a user $U$, the predicted watching probability of video $i$ is\n",
        "\n",
        "$$P(\\omega=i|u)=\\frac{e^{v_{i}u}}{\\sum_{j \\in V}e^{v_{j}u}}$$\n",
        "\n",
        "where $u$ is the representative vector of user $U$, $V$ is the corpus of all videos, $v_i$ is the representative vector of the $i$-th video. $u$ and $v_i$ are vectors of the same length, so we can compute their dot product using a fully connected layer.\n",
        "\n",
        "This model could have a performance issue as the softmax output covers millions of classification labels.  To optimize performance, at the training time, the authors down-sample negative samples, so the actual number of classes is reduced to thousands.  At serving time, the authors ignore the normalization of the softmax outputs, because the results are just for ranking.\n",
        "\n",
        "\n",
        "#### Ranking Network\n",
        "\n",
        "The architecture of the ranking network is similar to that of the candidate generation network.  Similar to ranking models widely used in online advertising, it uses rich features like video ID, last watching time, etc.  The output layer of the ranking network is a weighted logistic regression, which rates all candidate videos.\n",
        "\n",
        "\n",
        "### Hybrid Model\n",
        "\n",
        "In the section, let us introduce our movie recommendation system.\n",
        "\n",
        "In our network, the input includes features of users and movies.  The user feature includes four properties: user ID, gender, occupation, and age.  Movie features include their IDs, genres, and titles.\n",
        "\n",
        "We use fully-connected layers to map user features into representative feature vectors and concatenate them.  The process of movie features is similar, except that for movie titles -- we feed titles into a text convolution network as described in the [sentiment analysis tutorial](https://github.com/PaddlePaddle/book/blob/develop/understand_sentiment/README.md))to get a fixed-length representative feature vector.\n",
        "\n",
        "Given the feature vectors of users and movies, we compute the relevance using cosine similarity.  We minimize the squared error at training time.\n",
        "\n",
        "\u003cp align=\"center\"\u003e\n",
        "\n",
        "\u003cimg src=\"image/rec_regression_network_en.png\" width=\"90%\" \u003e\u003cbr/\u003e\n",
        "Figure 3. A hybrid recommendation model.\n",
        "\u003c/p\u003e\n",
        "\n",
        "## Dataset\n",
        "\n",
G
gongweibao 已提交
88
        "We use the [MovieLens ml-1m](http://files.grouplens.org/datasets/movielens/ml-1m.zip) to train our model.  This dataset includes 10,000 ratings of 4,000 movies from 6,000 users to 4,000 movies.  Each rate is in the range of 1~5.  Thanks to GroupLens Research for collecting, processing and publishing the dataset.\n",
G
gongweibao 已提交
89
        "\n",
G
gongweibao 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        "`paddle.v2.datasets` package encapsulates multiple public datasets, including `cifar`, `imdb`, `mnist`, `moivelens` and `wmt14`, etc. There's no need for us to manually download and preprocess `MovieLens` dataset.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "# Run this block to show dataset's documentation\n",
        "help(paddle.v2.dataset.movielens)\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
G
gongweibao 已提交
118
        "\n",
G
gongweibao 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        "The raw `MoiveLens` contains movie ratings, relevant features from both movies and users.\n",
        "For instance, one movie's feature could be:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "movie_info = paddle.dataset.movielens.movie_info()\n",
        "print movie_info.values()[0]\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
G
gongweibao 已提交
148
        "\n",
G
gongweibao 已提交
149 150 151
        "```text\n",
        "\u003cMovieInfo id(1), title(Toy Story), categories(['Animation', \"Children's\", 'Comedy'])\u003e\n",
        "```\n",
G
gongweibao 已提交
152
        "\n",
G
gongweibao 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        "One user's feature could be:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "user_info = paddle.dataset.movielens.user_info()\n",
        "print user_info.values()[0]\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
G
gongweibao 已提交
181
        "\n",
G
gongweibao 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        "```text\n",
        "\u003cUserInfo id(1), gender(F), age(1), job(10)\u003e\n",
        "```\n",
        "\n",
        "In this dateset, the distribution of age is shown as follows:\n",
        "\n",
        "```text\n",
        "1: \"Under 18\"\n",
        "18: \"18-24\"\n",
        "25: \"25-34\"\n",
        "35: \"35-44\"\n",
        "45: \"45-49\"\n",
        "50: \"50-55\"\n",
        "56: \"56+\"\n",
        "```\n",
        "\n",
        "User's occupation is selected from the following options:\n",
        "\n",
        "```text\n",
        "0: \"other\" or not specified\n",
        "1: \"academic/educator\"\n",
        "2: \"artist\"\n",
        "3: \"clerical/admin\"\n",
        "4: \"college/grad student\"\n",
        "5: \"customer service\"\n",
        "6: \"doctor/health care\"\n",
        "7: \"executive/managerial\"\n",
        "8: \"farmer\"\n",
        "9: \"homemaker\"\n",
        "10: \"K-12 student\"\n",
        "11: \"lawyer\"\n",
        "12: \"programmer\"\n",
        "13: \"retired\"\n",
        "14: \"sales/marketing\"\n",
        "15: \"scientist\"\n",
        "16: \"self-employed\"\n",
        "17: \"technician/engineer\"\n",
        "18: \"tradesman/craftsman\"\n",
        "19: \"unemployed\"\n",
        "20: \"writer\"\n",
        "```\n",
        "\n",
        "Each record consists of three main components: user features, movie features and movie ratings.\n",
        "Likewise, as a simple example, consider the following:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "train_set_creator = paddle.dataset.movielens.train()\n",
        "train_sample = next(train_set_creator())\n",
        "uid = train_sample[0]\n",
        "mov_id = train_sample[len(user_info[uid].value())]\n",
        "print \"User %s rates Movie %s with Score %s\"%(user_info[uid], movie_info[mov_id], train_sample[-1])\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
G
gongweibao 已提交
256
        "\n",
G
gongweibao 已提交
257 258 259
        "```text\n",
        "User \u003cUserInfo id(1), gender(F), age(1), job(10)\u003e rates Movie \u003cMovieInfo id(1193), title(One Flew Over the Cuckoo's Nest), categories(['Drama'])\u003e with Score [5.0]\n",
        "```\n",
G
gongweibao 已提交
260
        "\n",
G
gongweibao 已提交
261
        "The output shows that user 1 gave movie `1193` a rating of 5.\n",
G
gongweibao 已提交
262
        "\n",
G
gongweibao 已提交
263
        "After issuing a command `python train.py`, training will start immediately. The details will be unpacked by the following sessions to see how it works.\n",
G
gongweibao 已提交
264
        "\n",
G
gongweibao 已提交
265
        "## Model Architecture\n",
G
gongweibao 已提交
266
        "\n",
G
gongweibao 已提交
267
        "### Initialize PaddlePaddle\n",
G
gongweibao 已提交
268
        "\n",
G
gongweibao 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
        "First, we must import and initialize PaddlePaddle (enable/disable GPU, set the number of trainers, etc).\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "%matplotlib inline\n",
        "\n",
        "import matplotlib.pyplot as plt\n",
        "from IPython import display\n",
        "import cPickle\n",
        "\n",
        "import paddle.v2 as paddle\n",
        "\n",
        "paddle.init(use_gpu=False)\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "### Model Configuration\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "uid = paddle.layer.data(\n",
        "        name='user_id',\n",
        "        type=paddle.data_type.integer_value(\n",
        "            paddle.dataset.movielens.max_user_id() + 1))\n",
        "usr_emb = paddle.layer.embedding(input=uid, size=32)\n",
        "\n",
        "usr_gender_id = paddle.layer.data(\n",
        "        name='gender_id', type=paddle.data_type.integer_value(2))\n",
        "usr_gender_emb = paddle.layer.embedding(input=usr_gender_id, size=16)\n",
        "\n",
        "usr_age_id = paddle.layer.data(\n",
        "        name='age_id',\n",
        "        type=paddle.data_type.integer_value(\n",
        "            len(paddle.dataset.movielens.age_table)))\n",
        "usr_age_emb = paddle.layer.embedding(input=usr_age_id, size=16)\n",
        "\n",
        "usr_job_id = paddle.layer.data(\n",
        "        name='job_id',\n",
        "        type=paddle.data_type.integer_value(paddle.dataset.movielens.max_job_id(\n",
        "        ) + 1))\n",
        "usr_job_emb = paddle.layer.embedding(input=usr_job_id, size=16)\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "As shown in the above code, the input is four dimension integers for each user, that is,  `user_id`,`gender_id`, `age_id` and `job_id`. In order to deal with these features conveniently, we use the language model in NLP to transform these discrete values into embedding vaules `usr_emb`, `usr_gender_emb`, `usr_age_emb` and `usr_job_emb`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "usr_combined_features = paddle.layer.fc(\n",
        "        input=[usr_emb, usr_gender_emb, usr_age_emb, usr_job_emb],\n",
        "        size=200,\n",
        "        act=paddle.activation.Tanh())\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "Then, employing user features as input, directly connecting to a fully-connected layer, which is used to reduce dimension to 200.\n",
        "\n",
        "Furthermore, we do a similar transformation for each movie feature. The model configuration is:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "mov_id = paddle.layer.data(\n",
        "    name='movie_id',\n",
        "    type=paddle.data_type.integer_value(\n",
        "        paddle.dataset.movielens.max_movie_id() + 1))\n",
        "mov_emb = paddle.layer.embedding(input=mov_id, size=32)\n",
        "\n",
        "mov_categories = paddle.layer.data(\n",
        "    name='category_id',\n",
        "    type=paddle.data_type.sparse_binary_vector(\n",
        "        len(paddle.dataset.movielens.movie_categories())))\n",
        "\n",
        "mov_categories_hidden = paddle.layer.fc(input=mov_categories, size=32)\n",
        "\n",
        "\n",
        "movie_title_dict = paddle.dataset.movielens.get_movie_title_dict()\n",
        "mov_title_id = paddle.layer.data(\n",
        "    name='movie_title',\n",
        "    type=paddle.data_type.integer_value_sequence(len(movie_title_dict)))\n",
        "mov_title_emb = paddle.layer.embedding(input=mov_title_id, size=32)\n",
        "mov_title_conv = paddle.networks.sequence_conv_pool(\n",
        "    input=mov_title_emb, hidden_size=32, context_len=3)\n",
        "\n",
        "mov_combined_features = paddle.layer.fc(\n",
        "    input=[mov_emb, mov_categories_hidden, mov_title_conv],\n",
        "    size=200,\n",
        "    act=paddle.activation.Tanh())\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "Movie title, a sequence of words represented by an integer word index sequence, will be feed into a `sequence_conv_pool` layer, which will apply convolution and pooling on time dimension. Because pooling is done on time dimension, the output will be a fixed-length vector regardless the length of the input sequence.\n",
        "\n",
        "Finally, we can use cosine similarity to calculate the similarity between user characteristics and movie features.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "inference = paddle.layer.cos_sim(a=usr_combined_features, b=mov_combined_features, size=1, scale=5)\n",
        "cost = paddle.layer.regression_cost(\n",
        "        input=inference,\n",
        "        label=paddle.layer.data(\n",
        "        name='score', type=paddle.data_type.dense_vector(1)))\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "## Model Training\n",
        "\n",
        "### Define Parameters\n",
        "\n",
        "First, we define the model parameters according to the previous model configuration `cost`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "# Create parameters\n",
        "parameters = paddle.parameters.create(cost)\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "### Create Trainer\n",
        "\n",
        "Before jumping into creating a training module, algorithm setting is also necessary. Here we specified Adam optimization algorithm via `paddle.optimizer`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "trainer = paddle.trainer.SGD(cost=cost, parameters=parameters,\n",
        "                             update_equation=paddle.optimizer.Adam(learning_rate=1e-4))\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "```text\n",
        "[INFO 2017-03-06 17:12:13,378 networks.py:1472] The input order is [user_id, gender_id, age_id, job_id, movie_id, category_id, movie_title, score]\n",
        "[INFO 2017-03-06 17:12:13,379 networks.py:1478] The output order is [__regression_cost_0__]\n",
        "```\n",
        "\n",
        "### Training\n",
        "\n",
        "`paddle.dataset.movielens.train` will yield records during each pass, after shuffling, a batch input is generated for training.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "reader=paddle.reader.batch(\n",
        "    paddle.reader.shuffle(\n",
        "        paddle.dataset.movielens.trai(), buf_size=8192),\n",
        "        batch_size=256)\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "`feeding` is devoted to specifying the correspondence between each yield record and `paddle.layer.data`. For instance, the first column of data generated by `movielens.train` corresponds to `user_id` feature.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "feeding = {\n",
        "    'user_id': 0,\n",
        "    'gender_id': 1,\n",
        "    'age_id': 2,\n",
        "    'job_id': 3,\n",
        "    'movie_id': 4,\n",
        "    'category_id': 5,\n",
        "    'movie_title': 6,\n",
        "    'score': 7\n",
        "}\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "Callback function `event_handler` will be called during training when a pre-defined event happens.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "step=0\n",
        "\n",
        "train_costs=[],[]\n",
        "test_costs=[],[]\n",
        "\n",
        "def event_handler(event):\n",
        "    global step\n",
        "    global train_costs\n",
        "    global test_costs\n",
        "    if isinstance(event, paddle.event.EndIteration):\n",
        "        need_plot = False\n",
        "        if step % 10 == 0:  # every 10 batches, record a train cost\n",
        "            train_costs[0].append(step)\n",
        "            train_costs[1].append(event.cost)\n",
        "\n",
        "        if step % 1000 == 0: # every 1000 batches, record a test cost\n",
        "            result = trainer.test(reader=paddle.batch(\n",
        "                  paddle.dataset.movielens.test(), batch_size=256))\n",
        "            test_costs[0].append(step)\n",
        "            test_costs[1].append(result.cost)\n",
        "\n",
        "        if step % 100 == 0: # every 100 batches, update cost plot\n",
        "            plt.plot(*train_costs)\n",
        "            plt.plot(*test_costs)\n",
        "            plt.legend(['Train Cost', 'Test Cost'], loc='upper left')\n",
        "            display.clear_output(wait=True)\n",
        "            display.display(plt.gcf())\n",
        "            plt.gcf().clear()\n",
        "        step += 1\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "Finally, we can invoke `trainer.train` to start training:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "editable": true
      },
      "source": [
        "trainer.train(\n",
        "    reader=reader,\n",
        "    event_handler=event_handler,\n",
        "    feeding=feeding,\n",
        "    num_passes=200)\n"
      ],
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n"
          ]
        }
      ],
      "execution_count": 1
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
G
gongweibao 已提交
699 700 701 702 703 704 705
        "\n",
        "## Conclusion\n",
        "\n",
        "This tutorial goes over traditional approaches in recommender system and a deep learning based approach.  We also show that how to train and use the model with PaddlePaddle.  Deep learning has been well used in computer vision and NLP, we look forward to its new successes in recommender systems.\n",
        "\n",
        "## Reference\n",
        "\n",
G
gongweibao 已提交
706 707
        "1. [Peter Brusilovsky](https://en.wikipedia.org/wiki/Peter_Brusilovsky) (2007). *The Adaptive Web*. p. 325.\n",
        "2. Robin Burke , [Hybrid Web Recommender Systems](http://www.dcs.warwick.ac.uk/~acristea/courses/CS411/2010/Book%20-%20The%20Adaptive%20Web/HybridWebRecommenderSystems.pdf), pp. 377-408, The Adaptive Web, Peter Brusilovsky, Alfred Kobsa, Wolfgang Nejdl (Ed.), Lecture Notes in Computer Science, Springer-Verlag, Berlin, Germany, Lecture Notes in Computer Science, Vol. 4321, May 2007, 978-3-540-72078-2.\n",
G
gongweibao 已提交
708
        "3. P. Resnick, N. Iacovou, etc. “[GroupLens: An Open Architecture for Collaborative Filtering of Netnews](http://ccs.mit.edu/papers/CCSWP165.html)”, Proceedings of ACM Conference on Computer Supported Cooperative Work, CSCW 1994. pp.175-186.\n",
G
gongweibao 已提交
709
        "4. Sarwar, Badrul, et al. \"[Item-based collaborative filtering recommendation algorithms.](http://files.grouplens.org/papers/www10_sarwar.pdf)\" *Proceedings of the 10th International Conference on World Wide Web*. ACM, 2001.\n",
G
gongweibao 已提交
710
        "5. Kautz, Henry, Bart Selman, and Mehul Shah. \"[Referral Web: Combining Social networks and collaborative filtering.](http://www.cs.cornell.edu/selman/papers/pdf/97.cacm.refweb.pdf)\" Communications of the ACM 40.3 (1997): 63-65. APA\n",
G
gongweibao 已提交
711
        "6. Yuan, Jianbo, et al. [\"Solving Cold-Start Problem in Large-scale Recommendation Engines: A Deep Learning Approach.\"](https://arxiv.org/pdf/1611.05480v1.pdf) *arXiv preprint arXiv:1611.05480* (2016).\n",
G
gongweibao 已提交
712 713 714
        "7. Covington P, Adams J, Sargin E. [Deep neural networks for youtube recommendations](https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/45530.pdf)[C]//Proceedings of the 10th ACM Conference on Recommender Systems. ACM, 2016: 191-198.\n",
        "\n",
        "\u003cbr/\u003e\n",
G
gongweibao 已提交
715
        "This tutorial is contributed by \u003ca xmlns:cc=\"http://creativecommons.org/ns#\" href=\"http://book.paddlepaddle.org\" property=\"cc:attributionName\" rel=\"cc:attributionURL\"\u003ePaddlePaddle\u003c/a\u003e, and licensed under a \u003ca rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-sa/4.0/\"\u003eCreative Commons Attribution-NonCommercial-ShareAlike 4.0 International License\u003c/a\u003e.\n"
G
gongweibao 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}