{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.formula.api as sm\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn import preprocessing\nfrom scipy import stats\nimport lightgbm as lgb\nimport json\nimport gc\nfrom pandas.io.json import json_normalize\nimport time","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"testrows = None\n#based in SWK https://www.kaggle.com/sudalairajkumar/simple-exploration-baseline-ga-customer-revenue\ndef load_df(csv_path='../input/train.csv', nrows=None,isTest=False):\n    JSON_COLUMNS = ['device', 'geoNetwork', 'totals', 'trafficSource']\n    \n    df = pd.read_csv(csv_path, \n                     converters={column: json.loads for column in JSON_COLUMNS}, \n                     dtype={'fullVisitorId': 'str'}, # Important!!\n                     nrows=nrows)\n    \n    for column in JSON_COLUMNS:\n        column_as_df = json_normalize(df[column])\n        column_as_df.columns = [f\"{column}.{subcolumn}\" for subcolumn in column_as_df.columns]\n        df = df.drop(column, axis=1).merge(column_as_df, right_index=True, left_index=True)\n    df = df.loc[:,df.apply(pd.Series.nunique) != 1]\n    if isTest == False:\n        df['totals.transactionRevenue'].fillna(0,inplace=True)\n        df['totals.transactionRevenue'] = df['totals.transactionRevenue'].astype('float')\n    df['totals.pageviews'].fillna(0,inplace=True)\n    df['totals.pageviews'] = df['totals.pageviews'].astype('int64')\n    df['totals.hits'].fillna(0,inplace=True)\n    df['totals.hits'] = df['totals.hits'].astype('int64')\n    df['fullVisitorId'] = df['fullVisitorId'].astype('str')\n    return df\ntrain = load_df(nrows=testrows)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b8621920b0e60a88d70e2b46448ae9ac83f5dacc"},"cell_type":"code","source":"# list_device = ['device.browser','device.operatingSystem','device.deviceCategory','geoNetwork.country']\n# for device_feature in list_device:\n#     agg = train.groupby(['fullVisitorId'])[device_feature].size().reset_index(name=device_feature+'_size')\n#     train = train.merge(agg,how='left',on=['fullVisitorId'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a4a7594cdcf707b1ba0e968904bed0ec07fee7e"},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"16320e2b4028125164bc4db0b7922aefa6be5c52"},"cell_type":"code","source":"def getHour(timestamp):\n    struct_time = time.gmtime(timestamp)\n    return struct_time.tm_hour\n\ndef getMinutes(timestamp):\n    struct_time = time.gmtime(timestamp)\n    return struct_time.tm_min\n\ndef getSeconds(timestamp):\n    struct_time = time.gmtime(timestamp)\n    return struct_time.tm_sec\n\ndef getWeekDay(timestamp):\n    struct_time = time.gmtime(timestamp)\n    return struct_time.tm_wday\n\ndef getMonth(timestamp):\n    struct_time = time.gmtime(timestamp)\n    return struct_time.tm_mon\n\ntrain['visitStartMonth'] = train['visitStartTime'].apply(lambda x:getMonth(x))\ntrain['visitStartWeekDay'] = train['visitStartTime'].apply(lambda x:getWeekDay(x))\ntrain['visitStartTimeHour'] = train['visitStartTime'].apply(lambda x:getHour(x))\ntrain['visitStartTimeMinute'] = train['visitStartTime'].apply(lambda x:getMinutes(x))\ntrain['visitStartTimeHourRegion'] =  train['geoNetwork.country']+train['visitStartTimeHour'].astype('str')+train['geoNetwork.city']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b583f39e0e8683444736637c08876d2a0d7bcc23"},"cell_type":"code","source":"train['pageviewshigh'] = train['totals.pageviews'] > 8\ntrain['pagehitshigh'] = train['totals.hits'] > 8","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c8de081e6011dea8866c59024c2db9a9be588223"},"cell_type":"code","source":"def convert_category(train):\n    for index in train:\n        if train[index].dtype == 'object' and index != 'fullVisitorId':\n            le =  preprocessing.LabelEncoder()\n            train_val = list(train[index].values.astype(str))\n            le.fit(list(train[index].values.astype(str)))\n            train[index] = le.transform(train_val)\nconvert_category(train)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"effe10d9e46c2b20c92ad128a1142f8d12735718","scrolled":false},"cell_type":"code","source":"train.corr()['totals.transactionRevenue'].sort_values()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e357255d71ed23ee16701f54cf6631ad35d9b5c6"},"cell_type":"code","source":"def preprocess(x):\n    scaler = preprocessing.MinMaxScaler(feature_range=(0, 1), copy=False).fit(x)\n    scaler.transform(x)\n    return x\n\nx = preprocess(train.drop(['fullVisitorId','totals.transactionRevenue'],axis=1))\ny = np.log1p(train['totals.transactionRevenue'])\ndel train\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1124377b2d5d5f540e678c4913609807e284775d"},"cell_type":"code","source":"d_train = lgb.Dataset(x, y)\niterations = 8000\nwatchlist = [d_train]\n#parameters based on https://www.kaggle.com/pavansanagapati/simple-exploration-lgbm-model-lb-1-4221\nparams = {\"objective\" : \"regression\", \"metric\" : \"rmse\",\n              \"num_leaves\" : 50, \"learning_rate\" : 0.02, \n              \"bagging_fraction\" : 0.75, \"feature_fraction\" : 0.8, \"bagging_frequency\" : 9}\n\nmodel = lgb.train(params, train_set=d_train, num_boost_round=iterations, \n        valid_sets=watchlist, early_stopping_rounds=150, verbose_eval=200) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a7ffaa434387bd1695eaac3018cf9af6a84fe6bd"},"cell_type":"code","source":"test = load_df('../input/test.csv',nrows=testrows,isTest=True)\nfullVisitor = test[['fullVisitorId']]\nconvert_category(test)\nx_test = preprocess(test.drop(['fullVisitorId'],axis=1))\ndel test\ngc.collect()\npredict = model.predict(x_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"62e41c54eb3e19fb7ca8bea728c667ac72188901"},"cell_type":"code","source":"predict[predict <= 0.1] = 0\nfullVisitor['PredictedLogRevenue'] = np.expm1(predict)\nfullVisitor = fullVisitor.groupby(\"fullVisitorId\")[\"PredictedLogRevenue\"].sum().reset_index()\nfullVisitor.columns = [\"fullVisitorId\", \"PredictedLogRevenue\"]\nfullVisitor[\"PredictedLogRevenue\"] = np.log1p(fullVisitor[\"PredictedLogRevenue\"])\nfullVisitor[['fullVisitorId','PredictedLogRevenue']].to_csv(\"baseline_lgb.csv\", index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"15968505dda0282836a70c39cddf865f7cb60460"},"cell_type":"code","source":"fullVisitor[['fullVisitorId','PredictedLogRevenue']]","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}