{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# FASHION RECOMMENDER SYSTEM / BASKET ANALYSIS","metadata":{}},{"cell_type":"markdown","source":"## 1. Importing Libraries and Data","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom PIL import Image\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\npd.set_option('display.width', 500)\npd.set_option('display.expand_frame_repr', False)\nfrom mlxtend.frequent_patterns import apriori, association_rules","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:33:21.825800Z","iopub.execute_input":"2023-09-30T11:33:21.826483Z","iopub.status.idle":"2023-09-30T11:33:21.883352Z","shell.execute_reply.started":"2023-09-30T11:33:21.826445Z","shell.execute_reply":"2023-09-30T11:33:21.882000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reading the 'articles' file.\n\ndf_articles = pd.read_csv('/kaggle/input/h-and-m-personalized-fashion-recommendations/articles.csv')\n\ndf_ladies = df_articles[\n    df_articles['index_group_name'] == 'Ladieswear'] \n\ndf_ladies['article_id'].nunique()\n\nladieswear_article_ids = df_ladies['article_id'].tolist()\n\nlen(ladieswear_article_ids)","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:33:21.885319Z","iopub.execute_input":"2023-09-30T11:33:21.885824Z","iopub.status.idle":"2023-09-30T11:33:23.118922Z","shell.execute_reply.started":"2023-09-30T11:33:21.885792Z","shell.execute_reply":"2023-09-30T11:33:23.117820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reading the 'transactions_train' file.\n\ndf_trs = pd.read_csv('/kaggle/input/h-and-m-personalized-fashion-recommendations/transactions_train.csv')\n\n\n\n# Selecting the latest season.\n\nfrom datetime import datetime\ndf_trs['t_dat'] = pd.to_datetime(df_trs['t_dat'])\ncutoff_date = datetime(2020, 3, 21)\ndf_trs = df_trs[df_trs['t_dat'] > cutoff_date]\n\n\ndf_trs.isnull().any()\ndf_trs.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:33:23.120429Z","iopub.execute_input":"2023-09-30T11:33:23.120927Z","iopub.status.idle":"2023-09-30T11:34:40.754913Z","shell.execute_reply.started":"2023-09-30T11:33:23.120898Z","shell.execute_reply":"2023-09-30T11:34:40.753968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Retrieving the rows containing the relevant article IDs from the 'df_trs' dataset.\n\nfiltered_data = df_trs[df_trs['article_id'].isin(ladieswear_article_ids)]\n\nfiltered_data.shape\n\nfiltered_data.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:34:40.757244Z","iopub.execute_input":"2023-09-30T11:34:40.757558Z","iopub.status.idle":"2023-09-30T11:34:41.395030Z","shell.execute_reply.started":"2023-09-30T11:34:40.757533Z","shell.execute_reply":"2023-09-30T11:34:41.394158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fetching the rows where \"article_id\" occurs 10 or more times.\n\nfiltered_data = filtered_data[filtered_data['article_id'].map(filtered_data['article_id'].value_counts()) >= 10]\n\nfiltered_data.shape\n","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:34:41.396064Z","iopub.execute_input":"2023-09-30T11:34:41.396790Z","iopub.status.idle":"2023-09-30T11:34:42.421834Z","shell.execute_reply.started":"2023-09-30T11:34:41.396759Z","shell.execute_reply":"2023-09-30T11:34:42.420947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filtered_data['sepet_id'] = filtered_data['customer_id'].astype(str) + '_' + filtered_data['t_dat'].astype(str)\n\nfiltered_data.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:34:42.423271Z","iopub.execute_input":"2023-09-30T11:34:42.423608Z","iopub.status.idle":"2023-09-30T11:34:57.849218Z","shell.execute_reply.started":"2023-09-30T11:34:42.423580Z","shell.execute_reply":"2023-09-30T11:34:57.846743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Finding the customers who have more than 10 items in their shopping cart\n\nmultiple_product_baskets = filtered_data.groupby('sepet_id').filter(lambda x: len(x) >= 10)\n\nprint(f\"Sepet Sayısı: {multiple_product_baskets['sepet_id'].nunique()}, Ürün Sayısı: {multiple_product_baskets['article_id'].nunique()}\")","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:34:57.854016Z","iopub.execute_input":"2023-09-30T11:34:57.855932Z","iopub.status.idle":"2023-09-30T11:36:02.475059Z","shell.execute_reply.started":"2023-09-30T11:34:57.855772Z","shell.execute_reply":"2023-09-30T11:36:02.473148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result_df = filtered_data[filtered_data['sepet_id'].isin(multiple_product_baskets['sepet_id'].unique())]\nresult_df.head()\nresult_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:36:02.477068Z","iopub.execute_input":"2023-09-30T11:36:02.478337Z","iopub.status.idle":"2023-09-30T11:36:04.350202Z","shell.execute_reply.started":"2023-09-30T11:36:02.478298Z","shell.execute_reply":"2023-09-30T11:36:04.348921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. Basket Analysis","metadata":{}},{"cell_type":"code","source":"# Creating a pivot table.\n\nbasket = result_df.groupby(['sepet_id', 'article_id'])['article_id'].count().unstack().fillna(0).applymap(lambda x: 1 if x > 0 else 0).astype(bool)\nbasket.head()\nbasket.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:36:04.351858Z","iopub.execute_input":"2023-09-30T11:36:04.352600Z","iopub.status.idle":"2023-09-30T11:44:39.753836Z","shell.execute_reply.started":"2023-09-30T11:36:04.352572Z","shell.execute_reply":"2023-09-30T11:44:39.752439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Frequent itemsets\n\nfrequent_itemsets = apriori(basket,\n                            min_support=0.0037,\n                            use_colnames=True)\n\nfrequent_itemsets.sort_values(\"support\", ascending=False)","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:44:40.903805Z","iopub.execute_input":"2023-09-30T11:44:40.904199Z","iopub.status.idle":"2023-09-30T11:45:11.602716Z","shell.execute_reply.started":"2023-09-30T11:44:40.904172Z","shell.execute_reply":"2023-09-30T11:45:11.601863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Rules\n\nrules = association_rules(frequent_itemsets,\n                          metric=\"lift\",\n                          min_threshold=1)\n\nprint(rules)","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:45:11.604807Z","iopub.execute_input":"2023-09-30T11:45:11.605598Z","iopub.status.idle":"2023-09-30T11:45:11.652021Z","shell.execute_reply.started":"2023-09-30T11:45:11.605566Z","shell.execute_reply":"2023-09-30T11:45:11.650718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ARL recommender\n\ndef arl_recommender(rules_df, main_article_id, rec_count=5):\n    sorted_rules = rules_df.sort_values(\"lift\", ascending=False)\n    recommendation_list = []\n    for i, antecedents_set in enumerate(sorted_rules[\"antecedents\"]):\n        if main_article_id in antecedents_set:\n            recommendation_list.append(list(sorted_rules.iloc[i][\"consequents\"])[0])\n\n    return recommendation_list[:rec_count]","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:45:11.653444Z","iopub.execute_input":"2023-09-30T11:45:11.653844Z","iopub.status.idle":"2023-09-30T11:45:11.667057Z","shell.execute_reply.started":"2023-09-30T11:45:11.653815Z","shell.execute_reply":"2023-09-30T11:45:11.665739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Taking photos of other products that match the product code according to the rules.\n\nrecommended_articles = arl_recommender(rules, 599580055)\nprint(recommended_articles)\n\nimage_path = \"../input/h-and-m-personalized-fashion-recommendations\"\nmain_article_id = 599580055\n\ncols = (len(recommended_articles) + 1)\nrows = (len(recommended_articles) + cols - 1) // cols\n\n_df = df_ladies[df_ladies['article_id'].isin(recommended_articles)]\narticle_ids = _df.article_id.values[0:cols*rows]\n\nplt.figure(figsize=(2 + 3 * cols, 2 + 4 * rows))\nfor i in range(cols * rows):\n    plt.subplot(rows, cols, i + 1)\n    plt.axis('off')\n    \n    if i == 0:\n        article_id = (\"0\" + str(main_article_id))[-10:]\n        plt.title(f\"Main Article {article_id}\")\n    else:\n        article_id = (\"0\" + str(article_ids[i-1]))[-10:]\n        plt.title(f\"Recommended Article {article_id}\")\n    \n    image = Image.open(f\"{image_path}/images/{article_id[:3]}/{article_id}.jpg\")\n    plt.imshow(image)\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-30T11:45:11.668581Z","iopub.execute_input":"2023-09-30T11:45:11.669470Z","iopub.status.idle":"2023-09-30T11:45:13.002443Z","shell.execute_reply.started":"2023-09-30T11:45:11.669430Z","shell.execute_reply":"2023-09-30T11:45:13.001424Z"},"trusted":true},"execution_count":null,"outputs":[]}]}