{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"! pip install xlearn","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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)\nimport xlearn as xl\nimport gc\nfrom sklearn.datasets import dump_svmlight_file\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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"base_path = '/kaggle/input/outbrain-click-prediction/'\nsuffix = '.csv.zip'\nget_path = lambda name: base_path + name + suffix\nfile_names = [\n    'clicks_train',\n    'clicks_test',\n    'events',\n    'page_views_sample',\n    'promoted_content',\n    'sample_submission',\n    'documents_entities',\n    'documents_topics',\n    'documents_categories',\n    'documents_meta',\n    \n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"file_names\nsample_sub = pd.read_csv(get_path(file_names[5]))\n\n\n# files = []\n\n# for fn in file_names:\n#     files.append(pd.read_csv(get_path(fn)))\n    \n\n# for idx, name in enumerate(file_names, start=0):\n#     print('\\n')\n#     print(name)\n#     print(files[idx].head())\n# click_train = pd.read_csv(get_path(file_names[0]))\n# click_train\n# event = pd.read_csv(get_path(file_names[2]))\n\n# test_f = pd.merge(left=click_train, right=event, how='inner', on='display_id')\n\n# test_f.head()\n# test_f\n# test_f.memory_usage()\n# ct = files[0]\n# ct.loc[ct['ad_id'] == 1]\n# ev = files[2]\n# ev.loc[ev['display_id'].isin([805481, 3040931])]\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"event = pd.read_csv(get_path(file_names[2]))\nprom_cont = pd.read_csv(get_path(file_names[4]))\ndoc_data = []\nfor fn in file_names[6:]:\n    doc_data.append(pd.read_csv(get_path(fn)).dropna())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Saving Data With CHUNK_SIZE data record chuck size","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_OF_CHUNK = 1\nCHUNK_SIZE = 50_000\n\nfor i in range(0,NUM_OF_CHUNK):\n    click_train = pd.read_csv(get_path(file_names[0]), nrows=CHUNK_SIZE, skiprows=range(1, CHUNK_SIZE*(i)+1));\n    print(click_train)\n    clk_tr_ev = click_train.merge(right=event, on='display_id')\n    clk_tr_ev_doc_data = clk_tr_ev\n    for dd in doc_data:\n        clk_tr_ev_doc_data = clk_tr_ev.merge(right=dd, on='document_id')\n    clk_tr_ev_doc_data_ad_data = clk_tr_ev_doc_data.merge(right=prom_cont, on='ad_id')\n    data_train = clk_tr_ev_doc_data_ad_data\n    \n    features = ['display_id',\n                'ad_id','uuid',\n                'document_id_x',\n                'timestamp',\n                'platform',\n                'geo_location',\n                'source_id',\n                'publisher_id',\n                'publish_time',\n                'document_id_y',\n                'campaign_id',\n                'advertiser_id'\n               ]\n    label = 'clicked'\n    \n    print('joined tables')\n    \n    \n    \n    Xdf = pd.get_dummies(data_train[features], sparse=True)\n    ydf = data_train[label]\n    \n    print('before values')\n    \n    X = Xdf.values\n    y = ydf.values\n    \n    \n    print('writing to file')\n    dump_svmlight_file(X, y, '/kaggle/working/train'+str(i+1)+'.libsvm')\n#     data_train.to_csv('/kaggle/working/click_data_train_' +str(i+1)+ '.csv')\n    try:\n        del data_train\n        del clk_tr_ev_doc_data_ad_data\n        del clk_tr_ev_doc_data\n        del clk_tr_ev\n        del dd\n        del click_train\n        del X\n        del y\n        del Xdf\n        del ydf\n        print('collected all')\n    except:\n        print('not collected all')\n    gc.collect()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"CODE MODEL:","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"get_train_file_path = lambda i: '/kaggle/working/train'+str(i)+'.libsvm'\n\nffm_model = xl.create_ffm()\nffm_model.setTrain(get_train_file_path(1))\nffm_model.setValidate(get_train_file_path(2))\nparam = {'task':'binary', 'lr':0.2,\n         'lambda':0.002, 'metric':'acc'}\n\nffm_model.fit(param, './kaggle/working/model.out')\n\n# todo: data test ham ijad beshe\n# Prediction task\nffm_model.setTest('UNFINISHED=> test_file_path')  # Test data\nffm_model.setSigmoid()  # Convert output to 0-1\n\n# Start to predict\n# The output result will be stored in output.txt\nffm_model.predict(\"./kaggle/working/model.out\", \"./kaggle/working/output.txt\")","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}