{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-10-26T01:04:17.285736Z","iopub.execute_input":"2022-10-26T01:04:17.286252Z","iopub.status.idle":"2022-10-26T01:04:17.312887Z","shell.execute_reply.started":"2022-10-26T01:04:17.286154Z","shell.execute_reply":"2022-10-26T01:04:17.312134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install gensim==3.4","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:04:17.631125Z","iopub.execute_input":"2022-10-26T01:04:17.631568Z","iopub.status.idle":"2022-10-26T01:05:00.828135Z","shell.execute_reply.started":"2022-10-26T01:04:17.631530Z","shell.execute_reply":"2022-10-26T01:05:00.827229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm.notebook import tqdm\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport lightgbm as lgb\nimport multiprocessing\n\nfrom gensim.models import Word2Vec\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler\nfrom sklearn.model_selection import KFold, ShuffleSplit, StratifiedKFold\nfrom sklearn.metrics import roc_auc_score, log_loss\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer\nfrom sklearn.decomposition import TruncatedSVD","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:00.829928Z","iopub.execute_input":"2022-10-26T01:05:00.830267Z","iopub.status.idle":"2022-10-26T01:05:02.991562Z","shell.execute_reply.started":"2022-10-26T01:05:00.830237Z","shell.execute_reply":"2022-10-26T01:05:02.989775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/deepshare-playground/train_behaviour.csv')\ntest_df = pd.read_csv('/kaggle/input/deepshare-playground/test_behaviour.csv')\nuser_df = pd.read_csv('/kaggle/input/deepshare-playground/user_info.csv')\nitem_df = pd.read_csv('/kaggle/input/deepshare-playground/item_info.csv')","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:02.993234Z","iopub.execute_input":"2022-10-26T01:05:02.993605Z","iopub.status.idle":"2022-10-26T01:05:07.164316Z","shell.execute_reply.started":"2022-10-26T01:05:02.993571Z","shell.execute_reply":"2022-10-26T01:05:07.162593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 1.TFIDF\n## 1.1 TFIDF的基本用法","metadata":{}},{"cell_type":"code","source":"\nmax_features = 10\ndocs = [\n    'petrol cars are cheaper than diesel cars',\n    'diesel is cheaper than petrol',\n    'The sky is blue',\n    'I love apple',\n]\ntfidf = TfidfVectorizer(max_features=max_features).fit(docs)","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.167125Z","iopub.execute_input":"2022-10-26T01:05:07.167565Z","iopub.status.idle":"2022-10-26T01:05:07.187298Z","shell.execute_reply.started":"2022-10-26T01:05:07.167519Z","shell.execute_reply":"2022-10-26T01:05:07.185677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfidf.get_feature_names() #只选择了max_features个词","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.189243Z","iopub.execute_input":"2022-10-26T01:05:07.189690Z","iopub.status.idle":"2022-10-26T01:05:07.230062Z","shell.execute_reply.started":"2022-10-26T01:05:07.189629Z","shell.execute_reply":"2022-10-26T01:05:07.228698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfidf.vocabulary_ #每一个词对应的在句子中的id","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.231521Z","iopub.execute_input":"2022-10-26T01:05:07.232431Z","iopub.status.idle":"2022-10-26T01:05:07.245298Z","shell.execute_reply.started":"2022-10-26T01:05:07.232396Z","shell.execute_reply":"2022-10-26T01:05:07.243960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"doc_tfidf = tfidf.transform(docs)","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.247892Z","iopub.execute_input":"2022-10-26T01:05:07.249018Z","iopub.status.idle":"2022-10-26T01:05:07.259481Z","shell.execute_reply.started":"2022-10-26T01:05:07.248973Z","shell.execute_reply":"2022-10-26T01:05:07.258073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"doc_tfidf.toarray() #doc中的每一句话都表示为一个max_features的向量","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.262093Z","iopub.execute_input":"2022-10-26T01:05:07.262563Z","iopub.status.idle":"2022-10-26T01:05:07.275534Z","shell.execute_reply.started":"2022-10-26T01:05:07.262521Z","shell.execute_reply":"2022-10-26T01:05:07.274203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#'I love apple'的 tf-idf表示，这里面只有apple和love是有效词，所以只有apple对应的0位置与love对应的7位置的值不为0\ndoc_tfidf.toarray()[3] ","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.276923Z","iopub.execute_input":"2022-10-26T01:05:07.277379Z","iopub.status.idle":"2022-10-26T01:05:07.289733Z","shell.execute_reply.started":"2022-10-26T01:05:07.277349Z","shell.execute_reply":"2022-10-26T01:05:07.288723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max_features = 10\ndocs = [\n    'petrol cars are cheaper than diesel cars',\n    'diesel is cheaper than petrol',\n    'The sky is blue',\n    'I love apple',\n]\ntfidf = TfidfVectorizer(ngram_range=(1,2),max_features=max_features).fit(docs)\n#这里的ngram_range会将连续n个词视作为1个词，这里的ngram_range=(1,2)，其效果如下","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.292886Z","iopub.execute_input":"2022-10-26T01:05:07.293184Z","iopub.status.idle":"2022-10-26T01:05:07.302407Z","shell.execute_reply.started":"2022-10-26T01:05:07.293159Z","shell.execute_reply":"2022-10-26T01:05:07.301690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfidf.get_feature_names() #只选择了max_features个词","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.303262Z","iopub.execute_input":"2022-10-26T01:05:07.303596Z","iopub.status.idle":"2022-10-26T01:05:07.318599Z","shell.execute_reply.started":"2022-10-26T01:05:07.303564Z","shell.execute_reply":"2022-10-26T01:05:07.317686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfidf.vocabulary_ #每一个词对应的在句子中的id","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.320199Z","iopub.execute_input":"2022-10-26T01:05:07.320590Z","iopub.status.idle":"2022-10-26T01:05:07.332672Z","shell.execute_reply.started":"2022-10-26T01:05:07.320553Z","shell.execute_reply":"2022-10-26T01:05:07.331637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"doc_tfidf = tfidf.transform(docs)","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.333941Z","iopub.execute_input":"2022-10-26T01:05:07.334296Z","iopub.status.idle":"2022-10-26T01:05:07.346421Z","shell.execute_reply.started":"2022-10-26T01:05:07.334262Z","shell.execute_reply":"2022-10-26T01:05:07.344615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"doc_tfidf.toarray() #doc中的每一句话都表示为一个max_features的向量","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.347756Z","iopub.execute_input":"2022-10-26T01:05:07.348212Z","iopub.status.idle":"2022-10-26T01:05:07.362245Z","shell.execute_reply.started":"2022-10-26T01:05:07.348164Z","shell.execute_reply":"2022-10-26T01:05:07.360762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#'I love apple'的 tf-idf表示，这里面只有apple是有效词，所以这里只有apple对应的0位置的值不为0\ndoc_tfidf.toarray()[3] ","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.363702Z","iopub.execute_input":"2022-10-26T01:05:07.364128Z","iopub.status.idle":"2022-10-26T01:05:07.376223Z","shell.execute_reply.started":"2022-10-26T01:05:07.364090Z","shell.execute_reply":"2022-10-26T01:05:07.375121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1.2 TFIDF在比赛中的应用","metadata":{}},{"cell_type":"code","source":"def tfidf(sentences, output_num, output_prefix='tfidf', seed=1024):\n    #进行tfidf计算\n    tfidf_enc = TfidfVectorizer(ngram_range=(1,3))\n    tfidf_vec = tfidf_enc.fit_transform(sentences)\n    #使用SVD进行降维\n    svd_tmp = TruncatedSVD(n_components=output_num, n_iter=20, random_state=seed)\n    svd_tmp = svd_tmp.fit_transform(tfidf_vec)\n    svd_tmp = pd.DataFrame(svd_tmp)\n    svd_tmp.columns = ['{}_tfidf_{}'.format(output_prefix, i) for i in range(output_num)]\n    return svd_tmp","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.377462Z","iopub.execute_input":"2022-10-26T01:05:07.377971Z","iopub.status.idle":"2022-10-26T01:05:07.388863Z","shell.execute_reply.started":"2022-10-26T01:05:07.377938Z","shell.execute_reply":"2022-10-26T01:05:07.387714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfidf_df = tfidf(item_df['item_desc'].values, output_num=64, output_prefix='tfidf')","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:07.389827Z","iopub.execute_input":"2022-10-26T01:05:07.390118Z","iopub.status.idle":"2022-10-26T01:05:29.020390Z","shell.execute_reply.started":"2022-10-26T01:05:07.390088Z","shell.execute_reply":"2022-10-26T01:05:29.018912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"item_df = pd.concat([item_df,tfidf_df],axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:29.021869Z","iopub.execute_input":"2022-10-26T01:05:29.022283Z","iopub.status.idle":"2022-10-26T01:05:29.051266Z","shell.execute_reply.started":"2022-10-26T01:05:29.022246Z","shell.execute_reply":"2022-10-26T01:05:29.049651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 发现item_df中有脏数据，需要对其进行去重\nitem_df = item_df.drop_duplicates(subset=['item_id'], keep='last', inplace=False)\nuser_df = user_df.drop_duplicates(subset=['user_id'], keep='last', inplace=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:29.053684Z","iopub.execute_input":"2022-10-26T01:05:29.054196Z","iopub.status.idle":"2022-10-26T01:05:29.096592Z","shell.execute_reply.started":"2022-10-26T01:05:29.054150Z","shell.execute_reply":"2022-10-26T01:05:29.095527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 把train&test拼在一起，方便后续的数据编码\ndf = pd.concat([train_df,test_df],axis=0).reset_index(drop=True)\n# 把user/item侧的特征进行merge，以扩充宽表特征\ndf = df.merge(user_df,on='user_id',how='left').reset_index(drop=True)\ndf = df.merge(item_df,on='item_id',how='left').reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:29.098135Z","iopub.execute_input":"2022-10-26T01:05:29.098533Z","iopub.status.idle":"2022-10-26T01:05:34.156630Z","shell.execute_reply.started":"2022-10-26T01:05:29.098495Z","shell.execute_reply":"2022-10-26T01:05:34.155043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_cols  =  ['user_fea4']\ncate_cols = ['user_id','item_id']+ [f'user_fea{i}' for i in range(1,4)] + [f'item_fea{i}' for i in range(1,10)]","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:34.158282Z","iopub.execute_input":"2022-10-26T01:05:34.159258Z","iopub.status.idle":"2022-10-26T01:05:34.164367Z","shell.execute_reply.started":"2022-10-26T01:05:34.159222Z","shell.execute_reply":"2022-10-26T01:05:34.163682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for col in tqdm(cate_cols):\n    map_dict = dict(zip(df[col].unique(), range(df[col].nunique())))\n    df[col] = df[col].map(map_dict)\n    df[f'{col}_count'] = df[col].map(df[col].value_counts())","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:34.165383Z","iopub.execute_input":"2022-10-26T01:05:34.165794Z","iopub.status.idle":"2022-10-26T01:05:37.545678Z","shell.execute_reply.started":"2022-10-26T01:05:34.165769Z","shell.execute_reply":"2022-10-26T01:05:37.544870Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2.Word2Vec\n## 2.1 Word2Vec在比赛中的使用","metadata":{}},{"cell_type":"code","source":"#embedding 特征\ndef emb(df, f1, f2):\n    emb_size = 8\n    print('====================================== {} {} ======================================'.format(f1, f2))\n    tmp = df.groupby(f1, as_index=False)[f2].agg({'{}_{}_list'.format(f1, f2): list})\n    sentences = tmp['{}_{}_list'.format(f1, f2)].values.tolist()\n    del tmp['{}_{}_list'.format(f1, f2)]\n    for i in range(len(sentences)):\n        sentences[i] = [str(x) for x in sentences[i]]\n    # window: 窗口大小\n    # sg: 如果是0， 则是CBOW模型，是1则是Skip-Gram模型，默认是0即CBOW模型\n    # hs: 如果是0， 则是Negative Sampling，是1的话并且负采样个数negative大于0， 则是Hierarchical Softmax。默认是0即Negative Sampling。\n    model = Word2Vec(sentences, size=emb_size)\n    emb_matrix = []\n    for seq in sentences:\n        vec = []\n        for w in seq:\n            if w in model:\n                vec.append(model[w])\n        if len(vec) > 0:\n            emb_matrix.append(np.mean(vec, axis=0))\n        else:\n            emb_matrix.append([0] * emb_size)\n    emb_matrix = np.array(emb_matrix)\n    for i in range(emb_size):\n        tmp['{}_{}_emb_{}'.format(f1, f2, i)] = emb_matrix[:,i]\n    del model, emb_matrix, sentences\n    return tmp","metadata":{"execution":{"iopub.status.busy":"2022-10-26T01:05:37.546884Z","iopub.execute_input":"2022-10-26T01:05:37.547197Z","iopub.status.idle":"2022-10-26T01:05:37.559582Z","shell.execute_reply.started":"2022-10-26T01:05:37.547170Z","shell.execute_reply":"2022-10-26T01:05:37.558010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"click_df = df[df['label']==1].reset_index(drop=True)\nclick_df = click_df.sort_values(by='day')\ndf = df.merge(emb(click_df,'user_id','item_id'), on='user_id', how='left')","metadata":{"execution":{"iopub.status.busy":"2022-10-25T08:46:27.951982Z","iopub.execute_input":"2022-10-25T08:46:27.953203Z","iopub.status.idle":"2022-10-25T08:46:49.122040Z","shell.execute_reply.started":"2022-10-25T08:46:27.953151Z","shell.execute_reply":"2022-10-25T08:46:49.120694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = df[df['label'].notna()].reset_index(drop=True)\ntest_df = df[df['label'].isna()].reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2022-10-25T08:47:20.290038Z","iopub.execute_input":"2022-10-25T08:47:20.290480Z","iopub.status.idle":"2022-10-25T08:47:25.482314Z","shell.execute_reply.started":"2022-10-25T08:47:20.290439Z","shell.execute_reply":"2022-10-25T08:47:25.481356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"drop_feature = ['ID','label', 'day', 'item_desc']\nfeature = [x for x in train_df.columns if x not in drop_feature]\nprint(len(feature),feature)","metadata":{"execution":{"iopub.status.busy":"2022-10-25T08:47:27.028112Z","iopub.execute_input":"2022-10-25T08:47:27.028527Z","iopub.status.idle":"2022-10-25T08:47:27.035318Z","shell.execute_reply.started":"2022-10-25T08:47:27.028495Z","shell.execute_reply":"2022-10-25T08:47:27.034423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {'num_leaves': 63, #结果对最终效果影响较大，越大值越好，太大会出现过拟合\n          'objective': 'binary', #定义的目标函数\n          'max_depth': -1,\n          'learning_rate': 0.1,\n          \"min_sum_hessian_in_leaf\": 6,\n          \"boosting\": \"gbdt\",\n          \"feature_fraction\": 1,  #提取的特征比率\n          \"bagging_freq\": 1,\n          \"bagging_fraction\": 1,\n          \"bagging_seed\": 11,\n#           \"lambda_l1\": 0.1,             #l1正则\n          # 'lambda_l2': 0.001,     #l2正则\n          \"verbosity\": -1,\n          \"nthread\": multiprocessing.cpu_count(),                #线程数量，-1表示全部线程，线程越多，运行的速度越快\n          'metric': {'binary_logloss', 'auc'},  ##评价函数选择\n          \"random_state\": 2077, #随机数种子，可以防止每次运行的结果不一致\n          # 'device': 'gpu' ##如果安装的事gpu版本的lightgbm,可以加快运算\n          }\n\nn_fold = 5\noof_pre = np.zeros(len(train_df))\ny_pre = np.zeros(len(test_df))\n\nkf = KFold(n_splits=n_fold)\nfor fold_, (trn_idx, val_idx) in enumerate(kf.split(train_df)):\n\n    trn_data = lgb.Dataset(train_df[feature].iloc[trn_idx], label=train_df['label'].iloc[trn_idx])\n    val_data = lgb.Dataset(train_df[feature].iloc[val_idx], label=train_df['label'].iloc[val_idx])\n\n    clf = lgb.train(params,\n                    trn_data,\n                    2000,\n                    valid_sets=[trn_data, val_data],\n                    verbose_eval=50,\n                    early_stopping_rounds=50)\n    # out of fold\n    oof_pre[val_idx] = clf.predict(train_df[feature].iloc[val_idx], num_iteration=clf.best_iteration)\n\n    y_pre += clf.predict(test_df[feature], num_iteration=clf.best_iteration) / n_fold","metadata":{"execution":{"iopub.status.busy":"2022-10-25T08:51:48.452154Z","iopub.execute_input":"2022-10-25T08:51:48.452557Z","iopub.status.idle":"2022-10-25T08:55:22.737647Z","shell.execute_reply.started":"2022-10-25T08:51:48.452526Z","shell.execute_reply":"2022-10-25T08:55:22.736324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"local_auc = roc_auc_score(train_df['label'], oof_pre)\nprint(f'Local AUC :{local_auc}')","metadata":{"execution":{"iopub.status.busy":"2022-10-25T08:55:22.738842Z","iopub.status.idle":"2022-10-25T08:55:22.739531Z","shell.execute_reply.started":"2022-10-25T08:55:22.739312Z","shell.execute_reply":"2022-10-25T08:55:22.739338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"res_df = pd.DataFrame()\nres_df['ID'] = test_df['ID']\nres_df['predict'] = y_pre\nres_df.to_csv('/kaggle/working/lgb-text-baseline.csv',index=False)","metadata":{},"execution_count":null,"outputs":[]}]}