{"cells":[{"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import json\nfrom pandas.io.json import json_normalize\nimport matplotlib.pyplot as plt\nimport seaborn as sns # a good library to graphic plots\n\nfrom sklearn.cluster import KMeans\nfrom sklearn import preprocessing\n\npd.set_option('display.max_columns', 500)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def load_df(csv_path='/kaggle/input/ga-customer-revenue-prediction/train_v2.csv', nrows=None):\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    print(f\"Loaded {os.path.basename(csv_path)}. Shape: {df.shape}\")\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntrain_df = load_df(nrows=10000)\n#test_df = load_df(\"/kaggle/input/ga-customer-revenue-prediction/test_v2.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Number of unique visitors in train set : \",train_df.fullVisitorId.nunique(), \" out of rows : \",train_df.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ga=train_df.drop_duplicates(subset='fullVisitorId', keep='first', inplace=False)\nga1=ga.iloc[0:4295]\nga1.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ga2=ga1[['channelGrouping','device.deviceCategory','totals.visits','totals.hits','totals.pageviews']]\nprint(ga2.isnull().sum())\nga2.to_csv (r'ga.csv', index = None, header=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"const_cols = [c for c in train_df.columns if train_df[c].nunique(dropna=False)==1 ]\nprint(len(const_cols))\nprint(const_cols)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[const_cols].head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cols_to_drop = const_cols + ['hits', 'customDimensions']\n\ntrain_df1 = train_df.drop(cols_to_drop, axis=1)\nprint(train_df1.shape)\ntrain_df1.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df1.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df1.isnull().sum()/len(train_df1)*100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df1[pd.notnull(train_df1[\"trafficSource.adwordsClickInfo.isVideoAd\"])].head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cols_to_drop1=['totals.transactions', 'trafficSource.adContent', 'trafficSource.adwordsClickInfo.page', \n               'trafficSource.adwordsClickInfo.slot', 'trafficSource.adwordsClickInfo.gclId', \n               'trafficSource.adwordsClickInfo.adNetworkType', 'trafficSource.adwordsClickInfo.isVideoAd', \n               'totals.bounces', 'trafficSource.keyword', 'trafficSource.referralPath', 'trafficSource.isTrueDirect']\ntrain_df2 = train_df1.drop(cols_to_drop1, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df2.isnull().sum()/len(train_df2)*100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Impute 0 for missing target values\ntrain_df2[\"totals.transactionRevenue\"].fillna(0, inplace=True)\ntrain_df2[\"totals.totalTransactionRevenue\"].fillna(0, inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df2.loc[train_df1[\"totals.transactionRevenue\"] != 0].head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df2['totals.newVisits'].unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df2.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df2['totals.newVisits'].fillna(0, inplace=True)\ntrain_df2['totals.sessionQualityDim'].fillna(0, inplace=True)\ntrain_df2['totals.timeOnSite'].fillna(0, inplace=True)\ntrain_df2['totals.pageviews'].fillna(0, inplace=True)\n\ntrain_df2.isnull().sum()/len(train_df2)*100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df2['fullVisitorId'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df2.loc[train_df2['fullVisitorId']=='1572225825161580042']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df2.drop_duplicates(subset='fullVisitorId', keep='first', inplace=True)\nprint(train_df2.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cols_to_drop2=['date', 'visitId', 'visitNumber', \n               'visitStartTime', 'totals.transactionRevenue', \n               'totals.totalTransactionRevenue']\ntrain_df3 = train_df2.drop(cols_to_drop2, axis=1)\nprint(train_df3.shape)\ntrain_df3.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df3.set_index('fullVisitorId', inplace=True)\ntrain_df3.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df3.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df4=train_df3.copy()\n\n# label encode the categorical variables and convert the numerical variables to float\ncat_cols = [\"channelGrouping\", \"device.browser\", \n            \"device.deviceCategory\", \"device.operatingSystem\", \n            \"geoNetwork.city\", \"geoNetwork.continent\", \n            \"geoNetwork.country\", \"geoNetwork.metro\",\n            \"geoNetwork.networkDomain\", \"geoNetwork.region\", \n            \"geoNetwork.subContinent\", \"trafficSource.campaign\", \n            \"trafficSource.source\", \n            \"trafficSource.medium\"]\n\nfor col in cat_cols:\n    print(col)\n    lbl = preprocessing.LabelEncoder()\n    lbl.fit(list(train_df3[col].values.astype('str')))\n    train_df4[col] = lbl.transform(list(train_df3[col].values.astype('str')))\n    #test_df[col] = lbl.transform(list(test_df[col].values.astype('str')))\n\n\nnum_cols = [\"totals.hits\", \"totals.pageviews\", \"totals.timeOnSite\", 'totals.sessionQualityDim',  'totals.newVisits']    \nfor col in num_cols:\n    train_df4[col] = train_df3[col].astype(float)\n    #test_df[col] = test_df[col].astype(float)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df4.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df4.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"kmeans =  KMeans(n_clusters = 5)\nkmeans.fit(train_df4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"unique, counts = np.unique(kmeans.labels_, return_counts=True)\ndict(zip(unique, counts))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cluster = pd.DataFrame(kmeans.labels_, columns=['cluster'], index=train_df4.index)\ncluster.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_combine = pd.concat([train_df3, cluster], axis = 1)\ndf_combine.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_cols = [\"totals.hits\", \"totals.pageviews\", \"totals.timeOnSite\", 'totals.sessionQualityDim',  'totals.newVisits']    \nfor col in num_cols:\n    df_combine[col] = df_combine[col].astype(float)\n    \ndf_combine.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = sns.catplot(x=\"channelGrouping\", col=\"cluster\", data=df_combine, kind=\"count\", col_wrap=3, height=10)\ng.set_xticklabels(fontsize=25, rotation=70)\ng.set_yticklabels(fontsize=25)\ng.set_xlabels(fontsize=25)\ng.set_ylabels(fontsize=25)\ng.set_titles(size=25)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = sns.catplot(x=\"device.deviceCategory\", col=\"cluster\", data=df_combine, kind=\"count\", col_wrap=3, height=10)\ng.set_xticklabels(fontsize=25, rotation=70)\ng.set_yticklabels(fontsize=25)\ng.set_xlabels(fontsize=25)\ng.set_ylabels(fontsize=25)\ng.set_titles(size=25)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = sns.catplot(x=\"geoNetwork.continent\", col=\"cluster\", data=df_combine, kind=\"count\", col_wrap=3, height=10)\ng.set_xticklabels(fontsize=25, rotation=70)\ng.set_yticklabels(fontsize=25)\ng.set_xlabels(fontsize=25)\ng.set_ylabels(fontsize=25)\ng.set_titles(size=25)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(14,7))\nsns.boxplot(x=\"cluster\", y=\"totals.hits\", data=df_combine)\nplt.xticks(fontsize=16)\nplt.yticks(fontsize=16)\nplt.xlabel(\"cluster\",fontsize=16)\nplt.ylabel(\"totals.hits\",fontsize=16)\nplt.ylim(0,80)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(14,7))\nsns.boxplot(x=\"cluster\", y=\"totals.pageviews\", data=df_combine)\nplt.xticks(fontsize=16)\nplt.yticks(fontsize=16)\nplt.xlabel(\"cluster\",fontsize=16)\nplt.ylabel(\"totals.pageviews\",fontsize=16)\nplt.ylim(0,70)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(14,7))\nsns.boxplot(x=\"cluster\", y=\"totals.timeOnSite\", data=df_combine)\nplt.xticks(fontsize=16)\nplt.yticks(fontsize=16)\nplt.xlabel(\"cluster\",fontsize=16)\nplt.ylabel(\"totals.timeOnSite\",fontsize=16)\n#plt.ylim(0,70)\nplt.show()","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":1}