804 lines
23 KiB
Text
804 lines
23 KiB
Text
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Collecting ml_metrics\n",
|
|
" Downloading ml_metrics-0.1.4.tar.gz (5.0 kB)\n",
|
|
"Requirement already satisfied: numpy in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from ml_metrics) (1.24.2)\n",
|
|
"Requirement already satisfied: pandas in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from ml_metrics) (2.0.0)\n",
|
|
"Requirement already satisfied: tzdata>=2022.1 in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from pandas->ml_metrics) (2023.3)\n",
|
|
"Requirement already satisfied: python-dateutil>=2.8.2 in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from pandas->ml_metrics) (2.8.2)\n",
|
|
"Requirement already satisfied: pytz>=2020.1 in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from pandas->ml_metrics) (2023.3)\n",
|
|
"Requirement already satisfied: six>=1.5 in /home/shoney/devnlp/.venv/lib/python3.9/site-packages (from python-dateutil>=2.8.2->pandas->ml_metrics) (1.16.0)\n",
|
|
"Building wheels for collected packages: ml-metrics\n",
|
|
" Building wheel for ml-metrics (setup.py) ... \u001b[?25ldone\n",
|
|
"\u001b[?25h Created wheel for ml-metrics: filename=ml_metrics-0.1.4-py3-none-any.whl size=7844 sha256=64666abeb3d0e3c053380dc33e8580a115a4fe6239401464b56bce42a3e678cd\n",
|
|
" Stored in directory: /home/shoney/.cache/pip/wheels/c6/b2/69/0691b3d4de7c8d0c604cd7de94f4b2d4478a04ce3b6e4bab15\n",
|
|
"Successfully built ml-metrics\n",
|
|
"Installing collected packages: ml-metrics\n",
|
|
"Successfully installed ml-metrics-0.1.4\n",
|
|
"\u001b[33mWARNING: You are using pip version 21.2.3; however, version 23.0.1 is available.\n",
|
|
"You should consider upgrading via the '/home/shoney/devnlp/.venv/bin/python -m pip install --upgrade pip' command.\u001b[0m\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"!python -m pip install ml_metrics"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import torch\n",
|
|
"import torch.nn.functional as F\n",
|
|
"\n",
|
|
"from torch import nn\n",
|
|
"from torch.utils.data import Dataset\n",
|
|
"from torch.utils.data import DataLoader\n",
|
|
"\n",
|
|
"import heapq\n",
|
|
"import math\n",
|
|
"\n",
|
|
"import scipy.sparse as sp\n",
|
|
"import numpy as np\n",
|
|
"import pandas as pd\n",
|
|
"\n",
|
|
"import ml_metrics as metrics"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"https://grouplens.org/datasets/movielens/"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 3,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/html": [
|
|
"<div>\n",
|
|
"<style scoped>\n",
|
|
" .dataframe tbody tr th:only-of-type {\n",
|
|
" vertical-align: middle;\n",
|
|
" }\n",
|
|
"\n",
|
|
" .dataframe tbody tr th {\n",
|
|
" vertical-align: top;\n",
|
|
" }\n",
|
|
"\n",
|
|
" .dataframe thead th {\n",
|
|
" text-align: right;\n",
|
|
" }\n",
|
|
"</style>\n",
|
|
"<table border=\"1\" class=\"dataframe\">\n",
|
|
" <thead>\n",
|
|
" <tr style=\"text-align: right;\">\n",
|
|
" <th></th>\n",
|
|
" <th>userId</th>\n",
|
|
" <th>movieId</th>\n",
|
|
" <th>rating</th>\n",
|
|
" <th>timestamp</th>\n",
|
|
" </tr>\n",
|
|
" </thead>\n",
|
|
" <tbody>\n",
|
|
" <tr>\n",
|
|
" <th>0</th>\n",
|
|
" <td>1</td>\n",
|
|
" <td>1</td>\n",
|
|
" <td>4.0</td>\n",
|
|
" <td>964982703</td>\n",
|
|
" </tr>\n",
|
|
" <tr>\n",
|
|
" <th>1</th>\n",
|
|
" <td>1</td>\n",
|
|
" <td>3</td>\n",
|
|
" <td>4.0</td>\n",
|
|
" <td>964981247</td>\n",
|
|
" </tr>\n",
|
|
" <tr>\n",
|
|
" <th>2</th>\n",
|
|
" <td>1</td>\n",
|
|
" <td>6</td>\n",
|
|
" <td>4.0</td>\n",
|
|
" <td>964982224</td>\n",
|
|
" </tr>\n",
|
|
" <tr>\n",
|
|
" <th>3</th>\n",
|
|
" <td>1</td>\n",
|
|
" <td>47</td>\n",
|
|
" <td>5.0</td>\n",
|
|
" <td>964983815</td>\n",
|
|
" </tr>\n",
|
|
" <tr>\n",
|
|
" <th>4</th>\n",
|
|
" <td>1</td>\n",
|
|
" <td>50</td>\n",
|
|
" <td>5.0</td>\n",
|
|
" <td>964982931</td>\n",
|
|
" </tr>\n",
|
|
" </tbody>\n",
|
|
"</table>\n",
|
|
"</div>"
|
|
],
|
|
"text/plain": [
|
|
" userId movieId rating timestamp\n",
|
|
"0 1 1 4.0 964982703\n",
|
|
"1 1 3 4.0 964981247\n",
|
|
"2 1 6 4.0 964982224\n",
|
|
"3 1 47 5.0 964983815\n",
|
|
"4 1 50 5.0 964982931"
|
|
]
|
|
},
|
|
"execution_count": 3,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"movie_data = pd.read_csv('datasets/movies/ml-latest-small/ratings.csv', \n",
|
|
" sep=',', header=0)\n",
|
|
"\n",
|
|
"movie_data.head()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 4,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"(100836, 4)"
|
|
]
|
|
},
|
|
"execution_count": 4,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"movie_data.shape"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"610"
|
|
]
|
|
},
|
|
"execution_count": 5,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"NUM_USERS = movie_data['userId'].max()\n",
|
|
"\n",
|
|
"NUM_USERS"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"193609"
|
|
]
|
|
},
|
|
"execution_count": 6,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"NUM_ITEMS = movie_data['movieId'].max()\n",
|
|
"\n",
|
|
"NUM_ITEMS"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"TEST_USER_IDS = [5, 24, 45, 67, 89, 123, 239, 345, 456, 598]"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/html": [
|
|
"<div>\n",
|
|
"<style scoped>\n",
|
|
" .dataframe tbody tr th:only-of-type {\n",
|
|
" vertical-align: middle;\n",
|
|
" }\n",
|
|
"\n",
|
|
" .dataframe tbody tr th {\n",
|
|
" vertical-align: top;\n",
|
|
" }\n",
|
|
"\n",
|
|
" .dataframe thead th {\n",
|
|
" text-align: right;\n",
|
|
" }\n",
|
|
"</style>\n",
|
|
"<table border=\"1\" class=\"dataframe\">\n",
|
|
" <thead>\n",
|
|
" <tr style=\"text-align: right;\">\n",
|
|
" <th></th>\n",
|
|
" <th>userId</th>\n",
|
|
" <th>movieId</th>\n",
|
|
" <th>rating</th>\n",
|
|
" <th>timestamp</th>\n",
|
|
" </tr>\n",
|
|
" </thead>\n",
|
|
" <tbody>\n",
|
|
" <tr>\n",
|
|
" <th>516</th>\n",
|
|
" <td>5</td>\n",
|
|
" <td>1</td>\n",
|
|
" <td>4.0</td>\n",
|
|
" <td>847434962</td>\n",
|
|
" </tr>\n",
|
|
" <tr>\n",
|
|
" <th>517</th>\n",
|
|
" <td>5</td>\n",
|
|
" <td>21</td>\n",
|
|
" <td>4.0</td>\n",
|
|
" <td>847435238</td>\n",
|
|
" </tr>\n",
|
|
" <tr>\n",
|
|
" <th>518</th>\n",
|
|
" <td>5</td>\n",
|
|
" <td>34</td>\n",
|
|
" <td>4.0</td>\n",
|
|
" <td>847434881</td>\n",
|
|
" </tr>\n",
|
|
" <tr>\n",
|
|
" <th>519</th>\n",
|
|
" <td>5</td>\n",
|
|
" <td>36</td>\n",
|
|
" <td>4.0</td>\n",
|
|
" <td>847435292</td>\n",
|
|
" </tr>\n",
|
|
" <tr>\n",
|
|
" <th>520</th>\n",
|
|
" <td>5</td>\n",
|
|
" <td>39</td>\n",
|
|
" <td>3.0</td>\n",
|
|
" <td>847434961</td>\n",
|
|
" </tr>\n",
|
|
" </tbody>\n",
|
|
"</table>\n",
|
|
"</div>"
|
|
],
|
|
"text/plain": [
|
|
" userId movieId rating timestamp\n",
|
|
"516 5 1 4.0 847434962\n",
|
|
"517 5 21 4.0 847435238\n",
|
|
"518 5 34 4.0 847434881\n",
|
|
"519 5 36 4.0 847435292\n",
|
|
"520 5 39 3.0 847434961"
|
|
]
|
|
},
|
|
"execution_count": 8,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"test_movie_users = movie_data[movie_data['userId'].isin(TEST_USER_IDS)]\n",
|
|
"\n",
|
|
"test_movie_users.head()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 9,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def load_ratings_matrix(movie_data):\n",
|
|
"\n",
|
|
" ratings_matrix = sp.dok_matrix((NUM_USERS + 1, NUM_ITEMS + 1), dtype=np.float32)\n",
|
|
"\n",
|
|
" for index, row in movie_data.iterrows():\n",
|
|
" user, item, rating = int(row['userId']), int(row['movieId']), float(row['rating'])\n",
|
|
" \n",
|
|
" ratings_matrix[user, item] = rating\n",
|
|
" \n",
|
|
" random_user = np.random.randint(1, NUM_USERS)\n",
|
|
" \n",
|
|
" return ratings_matrix"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 10,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"(611, 193610)"
|
|
]
|
|
},
|
|
"execution_count": 10,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"ratings_matrix = load_ratings_matrix(movie_data)\n",
|
|
"\n",
|
|
"ratings_matrix.shape"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 11,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"class RecommenderNN(nn.Module):\n",
|
|
"\n",
|
|
" def __init__(self, n_users, n_items, layers=[24, 16], dropout=0.2):\n",
|
|
"\n",
|
|
" super().__init__()\n",
|
|
"\n",
|
|
" assert (layers[0] % 2 == 0), \"layers[0] must be an even number\"\n",
|
|
"\n",
|
|
" self.dropout = dropout\n",
|
|
"\n",
|
|
" embedding_dim = int(layers[0] / 2)\n",
|
|
"\n",
|
|
" self.user_embedding = torch.nn.Embedding(n_users, embedding_dim)\n",
|
|
" self.item_embedding = torch.nn.Embedding(n_items, embedding_dim)\n",
|
|
"\n",
|
|
" self.fc_layers = torch.nn.ModuleList()\n",
|
|
"\n",
|
|
" for _, (in_size, out_size) in enumerate(zip(layers[:-1], layers[1:])):\n",
|
|
" self.fc_layers.append(torch.nn.Linear(in_size, out_size))\n",
|
|
"\n",
|
|
" # Output of the last layer is just 1 for predicting ratings values\n",
|
|
" self.output_layer = torch.nn.Linear(layers[-1], 1)\n",
|
|
"\n",
|
|
" def forward(self, users, items):\n",
|
|
" user_embedding = self.user_embedding(users)\n",
|
|
" item_embedding = self.item_embedding(items)\n",
|
|
"\n",
|
|
" # Concatenate user and item embeddings, this is the input to the NN\n",
|
|
" x = torch.cat([user_embedding, item_embedding], 1)\n",
|
|
" \n",
|
|
" for idx, _ in enumerate(range(len(self.fc_layers))):\n",
|
|
" x = self.fc_layers[idx](x)\n",
|
|
" x = F.relu(x)\n",
|
|
" x = F.dropout(x, p=self.dropout, training=self.training)\n",
|
|
" \n",
|
|
" rating = self.output_layer(x)\n",
|
|
"\n",
|
|
" return rating\n",
|
|
"\n",
|
|
" def predict(self, users, items):\n",
|
|
" output_scores = self.forward(users, items)\n",
|
|
"\n",
|
|
" return output_scores.cpu().detach().numpy()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 12,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def generate_training_instances(ratings_matrix):\n",
|
|
" \n",
|
|
" user_item_ratings = {}\n",
|
|
" index = 0\n",
|
|
" \n",
|
|
" for user, item in ratings_matrix.keys():\n",
|
|
" \n",
|
|
" user_item_ratings[index] = (user, item, ratings_matrix[user, item])\n",
|
|
" index += 1\n",
|
|
" \n",
|
|
" return user_item_ratings"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 13,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"100836"
|
|
]
|
|
},
|
|
"execution_count": 13,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"train_user_item_ratings = generate_training_instances(ratings_matrix)\n",
|
|
"\n",
|
|
"len(train_user_item_ratings)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 14,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"((1, 1, 4.0), (1, 47, 5.0))"
|
|
]
|
|
},
|
|
"execution_count": 14,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"train_user_item_ratings[0], train_user_item_ratings[3]"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 15,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def train(model, train_data_loader, criterion, optimizer, epoch):\n",
|
|
" \n",
|
|
" model.train()\n",
|
|
" \n",
|
|
" epoch_loss = []\n",
|
|
" \n",
|
|
" for users_items_rating in train_data_loader:\n",
|
|
" \n",
|
|
" users, items, ratings = users_items_rating\n",
|
|
" \n",
|
|
" predictions = model(users, items)\n",
|
|
" \n",
|
|
" # Convert to float and change dim from [batch_size] to [batch_size, 1]\n",
|
|
" ratings = ratings.float().view(predictions.size())\n",
|
|
" \n",
|
|
" loss = criterion(predictions, ratings)\n",
|
|
" \n",
|
|
" optimizer.zero_grad()\n",
|
|
" loss.backward()\n",
|
|
" \n",
|
|
" optimizer.step()\n",
|
|
" \n",
|
|
" epoch_loss.append(loss.item())\n",
|
|
" \n",
|
|
" epoch_loss = np.mean(epoch_loss)\n",
|
|
"\n",
|
|
" print(\"Epoch completed\", epoch)\n",
|
|
" \n",
|
|
" print(\"Train Loss: {%.4f}\" % (epoch_loss))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 16,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def load_zero_rated(ratings_matrix, user_id, user_item_ratings): \n",
|
|
" \n",
|
|
" for i in range(100):\n",
|
|
" potential_zero_item = np.random.randint(1, NUM_ITEMS)\n",
|
|
" \n",
|
|
" while (user_id, potential_zero_item) in ratings_matrix:\n",
|
|
" potential_zero_item = np.random.randint(1, NUM_ITEMS)\n",
|
|
" \n",
|
|
" user_item_ratings['users'] = \\\n",
|
|
" np.append(user_item_ratings['users'], np.array([user_id]))\n",
|
|
" \n",
|
|
" user_item_ratings['items'] = \\\n",
|
|
" np.append(user_item_ratings['items'], np.array([potential_zero_item]))\n",
|
|
" \n",
|
|
" user_item_ratings['ratings'] = \\\n",
|
|
" np.append(user_item_ratings['ratings'], np.array([0]))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 17,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def generate_test_instances(ratings_matrix, test_movie_users):\n",
|
|
"\n",
|
|
" test_list = []\n",
|
|
"\n",
|
|
" for user_id in TEST_USER_IDS:\n",
|
|
" \n",
|
|
" user_item_ratings_df = test_movie_users[test_movie_users['userId'] == user_id]\n",
|
|
" user_item_ratings_df = user_item_ratings_df[user_item_ratings_df['rating'] >= 4]\n",
|
|
" \n",
|
|
" user_item_ratings = {}\n",
|
|
" \n",
|
|
" user_item_ratings['users'] = user_item_ratings_df['userId'].values[5:15]\n",
|
|
" user_item_ratings['items'] = user_item_ratings_df['movieId'].values[5:15]\n",
|
|
" user_item_ratings['ratings'] = user_item_ratings_df['rating'].values[5:15]\n",
|
|
" \n",
|
|
" load_zero_rated(ratings_matrix, user_id, user_item_ratings)\n",
|
|
" \n",
|
|
" test_list.append(user_item_ratings)\n",
|
|
" \n",
|
|
" return test_list"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 18,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"10"
|
|
]
|
|
},
|
|
"execution_count": 18,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"test_list = generate_test_instances(ratings_matrix, test_movie_users)\n",
|
|
"\n",
|
|
"len(test_list)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 19,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"{'users': array([5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n",
|
|
" 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n",
|
|
" 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n",
|
|
" 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n",
|
|
" 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]),\n",
|
|
" 'items': array([ 58, 110, 232, 247, 261, 290, 296, 367,\n",
|
|
" 457, 474, 41345, 182631, 18197, 161233, 1394, 28011,\n",
|
|
" 153917, 106034, 66187, 75510, 49438, 113499, 147983, 87947,\n",
|
|
" 1317, 74295, 35966, 161110, 32435, 173278, 79787, 10751,\n",
|
|
" 193599, 29238, 75645, 76407, 63576, 24895, 101984, 16391,\n",
|
|
" 142290, 173458, 9300, 35324, 107225, 140507, 37249, 3218,\n",
|
|
" 160625, 165951, 179351, 119584, 88598, 53641, 134842, 34138,\n",
|
|
" 95809, 8508, 182036, 93082, 682, 78318, 147539, 74603,\n",
|
|
" 103683, 5886, 91604, 4666, 88695, 112021, 117019, 133707,\n",
|
|
" 37857, 118359, 137635, 162022, 2682, 30608, 182844, 190418,\n",
|
|
" 107332, 20338, 168671, 61775, 42716, 8339, 117789, 139293,\n",
|
|
" 124305, 116739, 161583, 182707, 89498, 68145, 45189, 86044,\n",
|
|
" 8997, 4850, 95155, 103539, 5542, 180133, 139242, 15780,\n",
|
|
" 172943, 100142, 75835, 57258, 158875, 111896]),\n",
|
|
" 'ratings': array([5., 4., 4., 5., 4., 5., 5., 4., 4., 4., 0., 0., 0., 0., 0., 0., 0.,\n",
|
|
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
|
|
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
|
|
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
|
|
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
|
|
" 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n",
|
|
" 0., 0., 0., 0., 0., 0., 0., 0.])}"
|
|
]
|
|
},
|
|
"execution_count": 19,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"test_list[0]"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 20,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def evaluate(model, test_list):\n",
|
|
"\n",
|
|
" model.eval()\n",
|
|
" \n",
|
|
" apks = []\n",
|
|
"\n",
|
|
" for user_item_ratings in test_list:\n",
|
|
" \n",
|
|
" users = torch.tensor(user_item_ratings['users'])\n",
|
|
" items = torch.tensor(user_item_ratings['items'])\n",
|
|
" ratings = user_item_ratings['ratings']\n",
|
|
"\n",
|
|
" predictions = model.predict(users, items)\n",
|
|
" \n",
|
|
" item_score_map = {}\n",
|
|
" \n",
|
|
" for i, item in enumerate(user_item_ratings['items']):\n",
|
|
" item_score_map[item] = predictions[i]\n",
|
|
" \n",
|
|
" rank_list = heapq.nlargest(100, item_score_map, key=item_score_map.get)\n",
|
|
" \n",
|
|
" items_list = items.detach().numpy().tolist()\n",
|
|
" rank_list = list(rank_list)\n",
|
|
"\n",
|
|
" apk = metrics.apk(items_list[:10], rank_list[:10])\n",
|
|
" \n",
|
|
" apks.append(apk)\n",
|
|
" \n",
|
|
" \n",
|
|
" print(\"Evaluation mean APK : {%.4f}\" % np.mean(apks))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 21,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"model = RecommenderNN(NUM_USERS + 1, NUM_ITEMS + 1, [32, 16, 8], dropout=0.2)\n",
|
|
"\n",
|
|
"criterion = torch.nn.MSELoss()\n",
|
|
"\n",
|
|
"optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.00001)\n",
|
|
"\n",
|
|
"num_epochs = 15"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 22,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"train_data_loader = DataLoader(\n",
|
|
" train_user_item_ratings, batch_size=100, shuffle=True, num_workers=0)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 23,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Epoch completed 1\n",
|
|
"Train Loss: {3.8352}\n",
|
|
"Evaluation mean APK : {0.3372}\n",
|
|
"Epoch completed 2\n",
|
|
"Train Loss: {1.9782}\n",
|
|
"Evaluation mean APK : {0.5797}\n",
|
|
"Epoch completed 3\n",
|
|
"Train Loss: {1.6262}\n",
|
|
"Evaluation mean APK : {0.6027}\n",
|
|
"Epoch completed 4\n",
|
|
"Train Loss: {1.3538}\n",
|
|
"Evaluation mean APK : {0.6400}\n",
|
|
"Epoch completed 5\n",
|
|
"Train Loss: {1.1500}\n",
|
|
"Evaluation mean APK : {0.6572}\n",
|
|
"Epoch completed 6\n",
|
|
"Train Loss: {1.0243}\n",
|
|
"Evaluation mean APK : {0.6789}\n",
|
|
"Epoch completed 7\n",
|
|
"Train Loss: {0.9205}\n",
|
|
"Evaluation mean APK : {0.6739}\n",
|
|
"Epoch completed 8\n",
|
|
"Train Loss: {0.8565}\n",
|
|
"Evaluation mean APK : {0.6737}\n",
|
|
"Epoch completed 9\n",
|
|
"Train Loss: {0.8117}\n",
|
|
"Evaluation mean APK : {0.6656}\n",
|
|
"Epoch completed 10\n",
|
|
"Train Loss: {0.7896}\n",
|
|
"Evaluation mean APK : {0.6895}\n",
|
|
"Epoch completed 11\n",
|
|
"Train Loss: {0.7712}\n",
|
|
"Evaluation mean APK : {0.6838}\n",
|
|
"Epoch completed 12\n",
|
|
"Train Loss: {0.7581}\n",
|
|
"Evaluation mean APK : {0.6748}\n",
|
|
"Epoch completed 13\n",
|
|
"Train Loss: {0.7449}\n",
|
|
"Evaluation mean APK : {0.6870}\n",
|
|
"Epoch completed 14\n",
|
|
"Train Loss: {0.7389}\n",
|
|
"Evaluation mean APK : {0.6726}\n",
|
|
"Epoch completed 15\n",
|
|
"Train Loss: {0.7302}\n",
|
|
"Evaluation mean APK : {0.6421}\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"for epoch in range(1, num_epochs + 1):\n",
|
|
" \n",
|
|
" train(model, train_data_loader, criterion, optimizer, epoch)\n",
|
|
" evaluate(model, test_list)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
}
|
|
],
|
|
"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.9.7"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 2
|
|
}
|