{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "initial_id", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:05.163862Z", "start_time": "2024-12-02T15:09:03.260703Z" }, "collapsed": true }, "outputs": [], "source": [ "import itertools\n", "import numpy as np\n", "import pandas as pd\n", "from sklearn.preprocessing import LabelEncoder" ] }, { "cell_type": "markdown", "id": "7352ff562a374adb", "metadata": {}, "source": [ "## Preprocess" ] }, { "cell_type": "code", "execution_count": 2, "id": "daae2a4dccfedf88", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:15.109798Z", "start_time": "2024-12-02T15:09:05.188680Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Question Counts 210226\n", "Answers Counts 206435\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IdTitleBodyTagsPostTypeIdCreationDateOwnerUserIdParentId
0437734Effect of sex at specific point with confidenc...<p>Assume I model PEFR (related to lung ...|r|regression|confidence-interval|12019-11-24T19:50:42.807266724NaN
1622877Poisson process for small sample size<p>Suppose I have a data set that contai...|regression|poisson-distribution|poisson-proce...12023-08-01T15:57:49.950314344NaN
5517792Did I correctly apply the factorisation theore...<p>Suppose that we have a density <sp...|probability|estimation|inference|estimators|s...12021-04-01T18:01:50.420310650NaN
6344644IBM SPSS Damped Trend time series analysis met...<p>I have been doing a time series analy...|time-series|spss|trend|12018-05-05T13:34:35.617207140NaN
7620838Mixed model development for repeated measures ...<p>I have longitudinal data for multiple...|mixed-model|lme4-nlme|repeated-measures|multi...12023-07-07T23:34:22.930391974NaN
\n", "
" ], "text/plain": [ " Id Title \\\n", "0 437734 Effect of sex at specific point with confidenc... \n", "1 622877 Poisson process for small sample size \n", "5 517792 Did I correctly apply the factorisation theore... \n", "6 344644 IBM SPSS Damped Trend time series analysis met... \n", "7 620838 Mixed model development for repeated measures ... \n", "\n", " Body \\\n", "0 <p>Assume I model PEFR (related to lung ... \n", "1 <p>Suppose I have a data set that contai... \n", "5 <p>Suppose that we have a density <sp... \n", "6 <p>I have been doing a time series analy... \n", "7 <p>I have longitudinal data for multiple... \n", "\n", " Tags PostTypeId \\\n", "0 |r|regression|confidence-interval| 1 \n", "1 |regression|poisson-distribution|poisson-proce... 1 \n", "5 |probability|estimation|inference|estimators|s... 1 \n", "6 |time-series|spss|trend| 1 \n", "7 |mixed-model|lme4-nlme|repeated-measures|multi... 1 \n", "\n", " CreationDate OwnerUserId ParentId \n", "0 2019-11-24T19:50:42.807 266724 NaN \n", "1 2023-08-01T15:57:49.950 314344 NaN \n", "5 2021-04-01T18:01:50.420 310650 NaN \n", "6 2018-05-05T13:34:35.617 207140 NaN \n", "7 2023-07-07T23:34:22.930 391974 NaN " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "posts = pd.read_csv('csvs/Posts.csv')\n", "posts.dropna(subset=['Body', 'OwnerUserId'], how='any', inplace=True)\n", "\n", "# Shuffle\n", "posts = posts.sample(frac=1, random_state=42, replace=False, ignore_index=True)\n", "\n", "questions = posts[posts['PostTypeId']==1]\n", "answers = posts[posts['PostTypeId']==2]\n", "\n", "print('Question Counts', len(questions))\n", "print('Answers Counts', len(answers))\n", "questions.head()" ] }, { "cell_type": "code", "execution_count": 3, "id": "1f48885a95573c3", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:16.092779Z", "start_time": "2024-12-02T15:09:15.257949Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IdTitleBodyTagsPostTypeIdCreationDateOwnerUserIdParentId
0437734Effect of sex at specific point with confidenc...&lt;p&gt;Assume I model PEFR (related to lung ...[r, regression, confidence-interval]12019-11-24T19:50:42.807266724NaN
1622877Poisson process for small sample size&lt;p&gt;Suppose I have a data set that contai...[regression, poisson-distribution, poisson-pro...12023-08-01T15:57:49.950314344NaN
5517792Did I correctly apply the factorisation theore...&lt;p&gt;Suppose that we have a density &lt;sp...[probability, estimation, inference, estimator...12021-04-01T18:01:50.420310650NaN
6344644IBM SPSS Damped Trend time series analysis met...&lt;p&gt;I have been doing a time series analy...[time-series, spss, trend]12018-05-05T13:34:35.617207140NaN
7620838Mixed model development for repeated measures ...&lt;p&gt;I have longitudinal data for multiple...[mixed-model, lme4-nlme, repeated-measures, mu...12023-07-07T23:34:22.930391974NaN
\n", "
" ], "text/plain": [ " Id Title \\\n", "0 437734 Effect of sex at specific point with confidenc... \n", "1 622877 Poisson process for small sample size \n", "5 517792 Did I correctly apply the factorisation theore... \n", "6 344644 IBM SPSS Damped Trend time series analysis met... \n", "7 620838 Mixed model development for repeated measures ... \n", "\n", " Body \\\n", "0 <p>Assume I model PEFR (related to lung ... \n", "1 <p>Suppose I have a data set that contai... \n", "5 <p>Suppose that we have a density <sp... \n", "6 <p>I have been doing a time series analy... \n", "7 <p>I have longitudinal data for multiple... \n", "\n", " Tags PostTypeId \\\n", "0 [r, regression, confidence-interval] 1 \n", "1 [regression, poisson-distribution, poisson-pro... 1 \n", "5 [probability, estimation, inference, estimator... 1 \n", "6 [time-series, spss, trend] 1 \n", "7 [mixed-model, lme4-nlme, repeated-measures, mu... 1 \n", "\n", " CreationDate OwnerUserId ParentId \n", "0 2019-11-24T19:50:42.807 266724 NaN \n", "1 2023-08-01T15:57:49.950 314344 NaN \n", "5 2021-04-01T18:01:50.420 310650 NaN \n", "6 2018-05-05T13:34:35.617 207140 NaN \n", "7 2023-07-07T23:34:22.930 391974 NaN " ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "questions.loc[:, 'Tags'] = questions['Tags'].str.split('|').apply(lambda x: x[1:-1])\n", "questions.head()" ] }, { "cell_type": "code", "execution_count": 4, "id": "42a4b75299719d52", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:16.870012Z", "start_time": "2024-12-02T15:09:16.184978Z" } }, "outputs": [], "source": [ "questions_ids = np.concatenate([np.full(count, i) \n", " for i, count in enumerate(questions['Tags'].apply(len).values)])\n", "all_tags = list(itertools.chain(*(questions['Tags'].values)))" ] }, { "cell_type": "code", "execution_count": 5, "id": "9b790352a2990970", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:17.991099Z", "start_time": "2024-12-02T15:09:16.947033Z" } }, "outputs": [ { "data": { "text/plain": [ "(652198,)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tag_label_encoder1 = LabelEncoder()\n", "all_tag_ids = tag_label_encoder1.fit_transform(all_tags)\n", "all_tag_ids.shape" ] }, { "cell_type": "code", "execution_count": 6, "id": "a7b6eb11f97145df", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:18.064642Z", "start_time": "2024-12-02T15:09:18.055165Z" } }, "outputs": [], "source": [ "selected_tags = ['regression', 'hypothesis-testing', 'distributions', 'neural-networks', 'classification', 'clustering']\n", "selected_tag_ids = tag_label_encoder1.transform(selected_tags)" ] }, { "cell_type": "code", "execution_count": 7, "id": "6612b2e89985b151", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:18.146649Z", "start_time": "2024-12-02T15:09:18.114610Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "67940\n" ] }, { "data": { "text/plain": [ "(60783,)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Select questions with only one of selected_tags\n", "mask = np.isin(all_tag_ids, selected_tag_ids)\n", "print(mask.sum())\n", "questions_with_selected_tags, counts = np.unique(questions_ids[mask], return_counts=True)\n", "questions_with_selected_tags = questions_with_selected_tags[counts==1]\n", "questions_with_selected_tags.shape" ] }, { "cell_type": "code", "execution_count": 8, "id": "f8335fdbad91449e", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:18.279119Z", "start_time": "2024-12-02T15:09:18.248060Z" } }, "outputs": [], "source": [ "mask = np.isin(questions_ids, questions_with_selected_tags)\n", "questions_ids = questions_ids[mask]\n", "all_tag_ids = all_tag_ids[mask]\n", "mask = np.isin(all_tag_ids, selected_tag_ids)\n", "questions_ids = questions_ids[mask]\n", "all_tag_ids = all_tag_ids[mask]" ] }, { "cell_type": "code", "execution_count": 9, "id": "acc2ccdc88ca5ebb", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:18.328543Z", "start_time": "2024-12-02T15:09:18.319728Z" } }, "outputs": [ { "data": { "text/plain": [ "(array([ 185, 193, 386, 635, 973, 1237]),\n", " array([ 5365, 3541, 8514, 9210, 6904, 27249]))" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "np.unique(all_tag_ids, return_counts=True)" ] }, { "cell_type": "code", "execution_count": 10, "id": "6dfaf5e25aee9ed5", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:18.424326Z", "start_time": "2024-12-02T15:09:18.381400Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(60783, 9)\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IdTitleBodyTagsPostTypeIdCreationDateOwnerUserIdParentIdTag
0437734Effect of sex at specific point with confidenc...&lt;p&gt;Assume I model PEFR (related to lung ...[r, regression, confidence-interval]12019-11-24T19:50:42.807266724NaNregression
1622877Poisson process for small sample size&lt;p&gt;Suppose I have a data set that contai...[regression, poisson-distribution, poisson-pro...12023-08-01T15:57:49.950314344NaNregression
11178240linear regression accounting for standard erro...&lt;p&gt;I am trying to figure out what is the...[regression, errors-in-variables]12015-10-22T20:46:44.13719758NaNregression
14600361Problematic Residual plot&lt;p&gt;&lt;a href=&quot;https://i.stack.imgu...[regression, residuals]12022-12-29T16:21:35.377376392NaNregression
17625541Does skipgram model uses backpropagation?&lt;p&gt;I just started to get interested in n...[machine-learning, neural-networks, natural-la...12023-08-30T06:56:57.460302098NaNneural-networks
\n", "
" ], "text/plain": [ " Id Title \\\n", "0 437734 Effect of sex at specific point with confidenc... \n", "1 622877 Poisson process for small sample size \n", "11 178240 linear regression accounting for standard erro... \n", "14 600361 Problematic Residual plot \n", "17 625541 Does skipgram model uses backpropagation? \n", "\n", " Body \\\n", "0 <p>Assume I model PEFR (related to lung ... \n", "1 <p>Suppose I have a data set that contai... \n", "11 <p>I am trying to figure out what is the... \n", "14 <p><a href="https://i.stack.imgu... \n", "17 <p>I just started to get interested in n... \n", "\n", " Tags PostTypeId \\\n", "0 [r, regression, confidence-interval] 1 \n", "1 [regression, poisson-distribution, poisson-pro... 1 \n", "11 [regression, errors-in-variables] 1 \n", "14 [regression, residuals] 1 \n", "17 [machine-learning, neural-networks, natural-la... 1 \n", "\n", " CreationDate OwnerUserId ParentId Tag \n", "0 2019-11-24T19:50:42.807 266724 NaN regression \n", "1 2023-08-01T15:57:49.950 314344 NaN regression \n", "11 2015-10-22T20:46:44.137 19758 NaN regression \n", "14 2022-12-29T16:21:35.377 376392 NaN regression \n", "17 2023-08-30T06:56:57.460 302098 NaN neural-networks " ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "questions = questions.iloc[questions_ids]\n", "questions['Tag'] = tag_label_encoder1.inverse_transform(all_tag_ids)\n", "\n", "print(questions.shape)\n", "questions.head()" ] }, { "cell_type": "code", "execution_count": 11, "id": "b78a91701107f9cd", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:18.554427Z", "start_time": "2024-12-02T15:09:18.536519Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(60783, 9)\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IdTitleBodyTagsPostTypeIdCreationDateOwnerUserIdParentIdTag
0437734Effect of sex at specific point with confidenc...&lt;p&gt;Assume I model PEFR (related to lung ...[r, regression, confidence-interval]12019-11-24T19:50:42.807266724NaNregression
1622877Poisson process for small sample size&lt;p&gt;Suppose I have a data set that contai...[regression, poisson-distribution, poisson-pro...12023-08-01T15:57:49.950314344NaNregression
11178240linear regression accounting for standard erro...&lt;p&gt;I am trying to figure out what is the...[regression, errors-in-variables]12015-10-22T20:46:44.13719758NaNregression
14600361Problematic Residual plot&lt;p&gt;&lt;a href=&quot;https://i.stack.imgu...[regression, residuals]12022-12-29T16:21:35.377376392NaNregression
17625541Does skipgram model uses backpropagation?&lt;p&gt;I just started to get interested in n...[machine-learning, neural-networks, natural-la...12023-08-30T06:56:57.460302098NaNneural-networks
\n", "
" ], "text/plain": [ " Id Title \\\n", "0 437734 Effect of sex at specific point with confidenc... \n", "1 622877 Poisson process for small sample size \n", "11 178240 linear regression accounting for standard erro... \n", "14 600361 Problematic Residual plot \n", "17 625541 Does skipgram model uses backpropagation? \n", "\n", " Body \\\n", "0 <p>Assume I model PEFR (related to lung ... \n", "1 <p>Suppose I have a data set that contai... \n", "11 <p>I am trying to figure out what is the... \n", "14 <p><a href="https://i.stack.imgu... \n", "17 <p>I just started to get interested in n... \n", "\n", " Tags PostTypeId \\\n", "0 [r, regression, confidence-interval] 1 \n", "1 [regression, poisson-distribution, poisson-pro... 1 \n", "11 [regression, errors-in-variables] 1 \n", "14 [regression, residuals] 1 \n", "17 [machine-learning, neural-networks, natural-la... 1 \n", "\n", " CreationDate OwnerUserId ParentId Tag \n", "0 2019-11-24T19:50:42.807 266724 NaN regression \n", "1 2023-08-01T15:57:49.950 314344 NaN regression \n", "11 2015-10-22T20:46:44.137 19758 NaN regression \n", "14 2022-12-29T16:21:35.377 376392 NaN regression \n", "17 2023-08-30T06:56:57.460 302098 NaN neural-networks " ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(questions.shape)\n", "questions.head()" ] }, { "cell_type": "code", "execution_count": 12, "id": "a8c894ecef5eba68", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:18.819935Z", "start_time": "2024-12-02T15:09:18.805296Z" } }, "outputs": [ { "data": { "text/plain": [ "OwnerUserId\n", "408603 222\n", "247274 106\n", "28986 99\n", "1005 95\n", "108150 84\n", "Name: count, dtype: int64" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "user_ask_counts = questions['OwnerUserId'].value_counts()\n", "user_ask_counts.head()" ] }, { "cell_type": "code", "execution_count": 13, "id": "29e54f2c7af6e472", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:19.139229Z", "start_time": "2024-12-02T15:09:19.023915Z" } }, "outputs": [ { "data": { "text/plain": [ "(34153, 9)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "user_id_with_counts_gt_1 = user_ask_counts.index[user_ask_counts > 1]\n", "selected_question_idx = []\n", "for idx, owner_user_id in zip(questions.index, questions['OwnerUserId']):\n", " if owner_user_id in user_id_with_counts_gt_1:\n", " selected_question_idx.append(idx)\n", "questions = questions.loc[selected_question_idx]\n", "questions.shape" ] }, { "cell_type": "code", "execution_count": 14, "id": "3e2dd2b2022619c6", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:19.313893Z", "start_time": "2024-12-02T15:09:19.299332Z" } }, "outputs": [ { "data": { "text/plain": [ "Tag\n", "regression 15530\n", "hypothesis-testing 4858\n", "distributions 4697\n", "neural-networks 4103\n", "classification 3042\n", "clustering 1923\n", "Name: count, dtype: int64" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "questions['Tag'].value_counts()" ] }, { "cell_type": "code", "execution_count": 15, "id": "dfaaf16f245957ea", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:19.475081Z", "start_time": "2024-12-02T15:09:19.469247Z" } }, "outputs": [], "source": [ "import re\n", "\n", "def clean_text_html(raw_text: str):\n", " text = re.sub(r'<.*?>', '', raw_text)\n", " text = text.replace(' ', ' ')\n", " text = re.sub(r'\\s+', ' ', text)\n", " return text.rstrip()" ] }, { "cell_type": "code", "execution_count": 16, "id": "ff094f35b736db56", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:22.591039Z", "start_time": "2024-12-02T15:09:19.558750Z" } }, "outputs": [], "source": [ "questions['Body'] = questions['Body'].apply(clean_text_html)" ] }, { "cell_type": "code", "execution_count": 17, "id": "10921285f215489f", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:22.618084Z", "start_time": "2024-12-02T15:09:22.605847Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IdTitleBodyTagsPostTypeIdCreationDateOwnerUserIdParentIdTag
1622877Poisson process for small sample sizeSuppose I have a data set that contains insura...[regression, poisson-distribution, poisson-pro...12023-08-01T15:57:49.950314344NaNregression
17625541Does skipgram model uses backpropagation?I just started to get interested in natural la...[machine-learning, neural-networks, natural-la...12023-08-30T06:56:57.460302098NaNneural-networks
46501441Inference in a system in which (almost) all re...We conducted a number of tests on individual s...[regression, correlation, inference, least-squ...12020-12-18T10:53:32.023107859NaNregression
50572092A faster way of finding unbiased estimators fo...No access to computers or calculators is avail...[regression, self-study, multiple-regression, ...12022-04-19T05:43:00.277347256NaNregression
73533957Would it be wrong if I picked a model with les...I have some data containing a list of 2000 que...[machine-learning, classification, accuracy]12021-07-09T11:49:29.693327301NaNclassification
\n", "
" ], "text/plain": [ " Id Title \\\n", "1 622877 Poisson process for small sample size \n", "17 625541 Does skipgram model uses backpropagation? \n", "46 501441 Inference in a system in which (almost) all re... \n", "50 572092 A faster way of finding unbiased estimators fo... \n", "73 533957 Would it be wrong if I picked a model with les... \n", "\n", " Body \\\n", "1 Suppose I have a data set that contains insura... \n", "17 I just started to get interested in natural la... \n", "46 We conducted a number of tests on individual s... \n", "50 No access to computers or calculators is avail... \n", "73 I have some data containing a list of 2000 que... \n", "\n", " Tags PostTypeId \\\n", "1 [regression, poisson-distribution, poisson-pro... 1 \n", "17 [machine-learning, neural-networks, natural-la... 1 \n", "46 [regression, correlation, inference, least-squ... 1 \n", "50 [regression, self-study, multiple-regression, ... 1 \n", "73 [machine-learning, classification, accuracy] 1 \n", "\n", " CreationDate OwnerUserId ParentId Tag \n", "1 2023-08-01T15:57:49.950 314344 NaN regression \n", "17 2023-08-30T06:56:57.460 302098 NaN neural-networks \n", "46 2020-12-18T10:53:32.023 107859 NaN regression \n", "50 2022-04-19T05:43:00.277 347256 NaN regression \n", "73 2021-07-09T11:49:29.693 327301 NaN classification " ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "questions.head()" ] }, { "cell_type": "code", "execution_count": 18, "id": "9c8b5d859adf2fe7", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:22.739984Z", "start_time": "2024-12-02T15:09:22.695937Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IdTitleBodyTagYearOwnerUserIdTags
0622877Poisson process for small sample sizeSuppose I have a data set that contains insura...regression2023314344[regression, poisson-distribution, poisson-pro...
1625541Does skipgram model uses backpropagation?I just started to get interested in natural la...neural-networks2023302098[machine-learning, neural-networks, natural-la...
2501441Inference in a system in which (almost) all re...We conducted a number of tests on individual s...regression2020107859[regression, correlation, inference, least-squ...
3572092A faster way of finding unbiased estimators fo...No access to computers or calculators is avail...regression2022347256[regression, self-study, multiple-regression, ...
4533957Would it be wrong if I picked a model with les...I have some data containing a list of 2000 que...classification2021327301[machine-learning, classification, accuracy]
\n", "
" ], "text/plain": [ " Id Title \\\n", "0 622877 Poisson process for small sample size \n", "1 625541 Does skipgram model uses backpropagation? \n", "2 501441 Inference in a system in which (almost) all re... \n", "3 572092 A faster way of finding unbiased estimators fo... \n", "4 533957 Would it be wrong if I picked a model with les... \n", "\n", " Body Tag Year \\\n", "0 Suppose I have a data set that contains insura... regression 2023 \n", "1 I just started to get interested in natural la... neural-networks 2023 \n", "2 We conducted a number of tests on individual s... regression 2020 \n", "3 No access to computers or calculators is avail... regression 2022 \n", "4 I have some data containing a list of 2000 que... classification 2021 \n", "\n", " OwnerUserId Tags \n", "0 314344 [regression, poisson-distribution, poisson-pro... \n", "1 302098 [machine-learning, neural-networks, natural-la... \n", "2 107859 [regression, correlation, inference, least-squ... \n", "3 347256 [regression, self-study, multiple-regression, ... \n", "4 327301 [machine-learning, classification, accuracy] " ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "questions['Year'] = questions['CreationDate'].apply(lambda x: int(x[:4]))\n", "questions = questions[['Id', 'Title', 'Body', 'Tag', 'Year', 'OwnerUserId', 'Tags']]\n", "questions.reset_index(drop=True, inplace=True)\n", "questions.head()" ] }, { "cell_type": "code", "execution_count": 19, "id": "9d04f49d17dfc1a8", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:24.689251Z", "start_time": "2024-12-02T15:09:22.797595Z" } }, "outputs": [], "source": [ "questions.to_csv('CroVal.csv', index=False)" ] }, { "cell_type": "markdown", "id": "b3f1e9a5f85e7914", "metadata": {}, "source": [ "## Question-User Links" ] }, { "cell_type": "code", "execution_count": 20, "id": "380cc31c31d492ed", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:24.999097Z", "start_time": "2024-12-02T15:09:24.991021Z" } }, "outputs": [], "source": [ "data = {}" ] }, { "cell_type": "code", "execution_count": 21, "id": "b006f380b608da92", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:25.147540Z", "start_time": "2024-12-02T15:09:25.131782Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of question-user links: 34153\n" ] } ], "source": [ "question_ids = np.arange(questions.shape[0], dtype=np.uint16)\n", "\n", "user_id_encoder = LabelEncoder()\n", "user_ids = user_id_encoder.fit_transform(questions['OwnerUserId'].values).astype(np.uint16)\n", "assert len(user_ids) == len(question_ids)\n", "print('Number of question-user links:', len(question_ids))\n", "\n", "data['question-user'] = (question_ids, user_ids)" ] }, { "cell_type": "markdown", "id": "7b938fec4998c22", "metadata": {}, "source": [ "## Question-Tag Links" ] }, { "cell_type": "code", "execution_count": 22, "id": "3e8613f44eb40ece", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:25.315143Z", "start_time": "2024-12-02T15:09:25.182811Z" } }, "outputs": [], "source": [ "question_ids = np.concatenate([np.full(count, i)\n", " for i, count in enumerate(questions['Tags'].apply(len).values)])\n", "all_tags = list(itertools.chain(*(questions['Tags'].values)))" ] }, { "cell_type": "code", "execution_count": 23, "id": "37e8f87c035aa8fe", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:25.490973Z", "start_time": "2024-12-02T15:09:25.350607Z" } }, "outputs": [ { "data": { "text/plain": [ "(118712,)" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tag_label_encoder = LabelEncoder()\n", "all_tag_ids = tag_label_encoder.fit_transform(all_tags)\n", "all_tag_ids.shape" ] }, { "cell_type": "code", "execution_count": 24, "id": "e0774b0351720c1e", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:25.571892Z", "start_time": "2024-12-02T15:09:25.526063Z" } }, "outputs": [], "source": [ "selected_tags = np.unique(questions['Tag'])\n", "selected_tag_ids = tag_label_encoder.transform(selected_tags)" ] }, { "cell_type": "code", "execution_count": 25, "id": "9cdff6755217f598", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:25.618365Z", "start_time": "2024-12-02T15:09:25.605755Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of tags: 1335\n", "Number of question-tag links: 84559\n" ] } ], "source": [ "mask = ~np.isin(all_tag_ids, selected_tag_ids)\n", "question_ids = question_ids[mask]\n", "all_tag_ids = all_tag_ids[mask]\n", "\n", "tag_label_encoder = LabelEncoder()\n", "all_tag_ids = tag_label_encoder.fit_transform(all_tag_ids)\n", "print('Number of tags:', len(tag_label_encoder.classes_))\n", "\n", "print('Number of question-tag links:', len(question_ids))\n", "data['question-tag'] = (question_ids, all_tag_ids)" ] }, { "cell_type": "code", "execution_count": null, "id": "b9da239efcbdf395", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:25.661530Z", "start_time": "2024-12-02T15:09:25.657476Z" } }, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "58734f48c8c4dcfd", "metadata": {}, "source": [ "## Question-Question Links" ] }, { "cell_type": "code", "execution_count": 26, "id": "353f026c274f42ed", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:25.848989Z", "start_time": "2024-12-02T15:09:25.727095Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IdCreationDatePostIdRelatedPostIdLinkTypeId
061405262017-02-10T08:09:54.907261056826641
1133001592020-02-24T03:34:51.2874480974411561
238052802015-03-04T21:44:24.3931403691401631
339530362015-04-30T14:11:47.800149074350191
4112644712018-11-25T16:21:16.0533786113774443
\n", "
" ], "text/plain": [ " Id CreationDate PostId RelatedPostId LinkTypeId\n", "0 6140526 2017-02-10T08:09:54.907 261056 82664 1\n", "1 13300159 2020-02-24T03:34:51.287 448097 441156 1\n", "2 3805280 2015-03-04T21:44:24.393 140369 140163 1\n", "3 3953036 2015-04-30T14:11:47.800 149074 35019 1\n", "4 11264471 2018-11-25T16:21:16.053 378611 377444 3" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "post_links = pd.read_csv('csvs/PostLinks.csv')\n", "post_links.head()" ] }, { "cell_type": "code", "execution_count": 27, "id": "92aa15c1433a2dbf", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:25.919007Z", "start_time": "2024-12-02T15:09:25.908831Z" } }, "outputs": [], "source": [ "src_post_ids = post_links['PostId'].values\n", "dst_post_ids = post_links['RelatedPostId'].values\n", "mask = (np.isin(src_post_ids, questions['Id'].values) & \n", " np.isin(dst_post_ids, questions['Id'].values))\n", "src_post_ids = src_post_ids[mask]\n", "dst_post_ids = dst_post_ids[mask]" ] }, { "cell_type": "code", "execution_count": 28, "id": "c74c23bb7d5eecbb", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:26.015226Z", "start_time": "2024-12-02T15:09:25.987311Z" } }, "outputs": [], "source": [ "post_id_map = dict(zip(questions['Id'].values, range(len(questions))))\n", "src_post_ids = np.array([post_id_map[_] for _ in src_post_ids], dtype=np.uint16)\n", "post_id_map = dict(zip(questions['Id'].values, range(len(questions))))\n", "dst_post_ids = np.array([post_id_map[_] for _ in dst_post_ids], dtype=np.uint16)" ] }, { "cell_type": "code", "execution_count": 29, "id": "bd61cd75abb0ceab", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:09:26.045364Z", "start_time": "2024-12-02T15:09:26.037949Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of question-question links: 6743\n" ] } ], "source": [ "print('Number of question-question links:', src_post_ids.shape[0])\n", "data['question-question'] = (src_post_ids, dst_post_ids)" ] }, { "cell_type": "markdown", "id": "e38c5a9bbae43870", "metadata": {}, "source": [ "## Labels and Years" ] }, { "cell_type": "code", "execution_count": 30, "id": "cbd4f798db752644", "metadata": { "ExecuteTime": { "end_time": "2024-12-02T15:11:02.198886Z", "start_time": "2024-12-02T15:11:02.194669Z" } }, "outputs": [], "source": [ "question_years = questions['Year'].values.astype(np.int16)\n", "\n", "label_encoder = LabelEncoder()\n", "question_labels = label_encoder.fit_transform(questions['Tag']).astype(np.int8)\n", "\n", "data['question_years'] = question_years\n", "data['question_labels'] = question_labels" ] }, { "cell_type": "markdown", "id": "5b96baa7b9600d32", "metadata": {}, "source": [ "### Node Features\n", "\n", "We generate embeddings as features for each node in the graph. Node embeddings are generated by passing the title and body through a Sentence-BERT model and obtaining a 384-embedding vector for each movie node.\n", "\n", "\n", "According to [Sentence-Transformers docs](https://www.sbert.net/docs/pretrained_models.html), the **all-MiniLM-L6-v2** model provides the best quality. So we use it to generate node features.\n", "\n", "all-MiniLM-L6-v2\n", "\n", "Description:\tAll-round model tuned for many use-cases. Trained on a large and diverse dataset of over 1 billion training pairs.\n", "Base Model:\tnreimers/MiniLM-L6-H384-uncased\n", "Max Sequence Length:\t256\n", "Dimensions:\t384\n", "Normalized Embeddings:\ttrue\n", "Suitable Score Functions:\tdot-product (util.dot_score), cosine-similarity (util.cos_sim), euclidean distance\n", "Size:\t80 MB\n", "Pooling:\tMean Pooling\n", "Training Data:\t1B+ training pairs. For details, see model card.\n", "Model Card:\thttps://huggingface.co/sentence-transformers/all-MiniLM-L6-v2\n" ] }, { "cell_type": "code", "execution_count": 31, "id": "65607ae67568281d", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.10/dist-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] }, { "data": { "text/plain": [ "SentenceTransformer(\n", " (0): Transformer({'max_seq_length': 256, 'do_lower_case': False}) with Transformer model: BertModel \n", " (1): Pooling({'word_embedding_dimension': 384, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})\n", " (2): Normalize()\n", ")" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import torch\n", "from sentence_transformers import SentenceTransformer\n", "\n", "device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n", "model = SentenceTransformer('../sentence-transformers/all-MiniLM-L6-v2', device=device)\n", "model" ] }, { "cell_type": "code", "execution_count": 32, "id": "d13d815aaee99d99", "metadata": {}, "outputs": [], "source": [ "text = questions['Title'] + ' ' + questions['Body']" ] }, { "cell_type": "code", "execution_count": 33, "id": "1e482784", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Batches: 100%|██████████| 9/9 [00:31<00:00, 3.49s/it]\n" ] } ], "source": [ "feats = model.encode(text, batch_size=4096, show_progress_bar=True, convert_to_numpy=True)" ] }, { "cell_type": "code", "execution_count": 34, "id": "96bac537", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'question-user': (array([ 0, 1, 2, ..., 34150, 34151, 34152], dtype=uint16),\n", " array([7927, 7752, 3986, ..., 67, 3988, 4143], dtype=uint16)),\n", " 'question-tag': (array([ 0, 0, 0, ..., 34150, 34150, 34152]),\n", " array([920, 921, 397, ..., 981, 419, 331])),\n", " 'question-question': (array([8581, 678, 5604, ..., 4463, 4463, 4053], dtype=uint16),\n", " array([11735, 9756, 18156, ..., 19652, 19652, 19002], dtype=uint16)),\n", " 'question_years': array([2023, 2023, 2020, ..., 2010, 2017, 2016], dtype=int16),\n", " 'question_labels': array([5, 4, 5, ..., 2, 5, 4], dtype=int8),\n", " 'question_feats': array([[-0.02393158, 0.06053483, 0.03126719, ..., -0.10800511,\n", " -0.00546587, 0.03609833],\n", " [-0.05885282, -0.11182664, 0.02024328, ..., 0.07537424,\n", " 0.05215778, -0.04128488],\n", " [-0.06636419, -0.0513887 , -0.01564158, ..., -0.00976081,\n", " 0.01578866, -0.04567946],\n", " ...,\n", " [-0.12249381, -0.03751755, 0.03033727, ..., -0.03496004,\n", " -0.04555019, 0.03692898],\n", " [ 0.00232019, 0.0414363 , 0.06341822, ..., -0.0623777 ,\n", " 0.07806651, -0.00320921],\n", " [-0.05833942, -0.08774115, 0.02993867, ..., -0.00308282,\n", " 0.06190689, -0.04922426]], dtype=float32)}" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data['question_feats'] = feats\n", "data" ] }, { "cell_type": "code", "execution_count": 35, "id": "8d0053d6", "metadata": {}, "outputs": [], "source": [ "import pickle\n", "\n", "with open('croval.pkl', 'wb') as f:\n", " pickle.dump(data, f)" ] } ], "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.10.12" } }, "nbformat": 4, "nbformat_minor": 5 }