{"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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_filepath = '/kaggle/input/facebook-v-predicting-check-ins/train.csv.zip'\ntest_filepath = '/kaggle/input/facebook-v-predicting-check-ins/test.csv.zip'\ndf = pd.read_csv(train_filepath)\ndf = df.set_index('row_id')\nholdout_df = pd.read_csv(test_filepath)\nholdout_df = holdout_df.set_index('row_id')\nholdout_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_sample = df.sample(n=100000)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_cols = ['x', 'y', 'accuracy', 'time']\ny_cols = ['place_id']\n\nX = df[X_cols]\ny = df[y_cols]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.cluster import KMeans\nmodel = KMeans(n_clusters=6)\nmodel.fit(X)\nclusters = model.predict(X)\nclustering_df = X.copy()\nclustering_df['cluster'] = clusters\nclustering_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":false},"cell_type":"code","source":"first_pl = Pipeline(steps=[\n    ('std_scaler', StandardScaler()),\n    ('kmeans', KMeans(n_clusters=5))\n])\nfirst_pl.fit(X)\nnew_clusters = first_pl.predict(X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":false,"_kg_hide-input":false},"cell_type":"code","source":"clustering_df = X.copy()\nclustering_df['cluster'] = new_clusters\nfor cluster in range(0,5):\n    current_cluster = clustering_df[clustering_df['cluster'] == cluster]\n    print('CLUSTER: ', cluster)\n    plt.figure()\n    plt.scatter(current_cluster['time'], current_cluster['accuracy'])\n    plt.xlabel('time')\n    plt.ylabel('accuracy')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"feature_df = X.copy()\nfeature_df.head()\nfeature_df['grid_loc'] = df['x'] * 1000 + (9 * 1000 * round(df['y']))\nfeature_df.sort_values(by='grid_loc', ascending=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure()\nplt.scatter(feature_df['grid_loc'], y.values)\nplt.xlabel('Grid Location')\nplt.ylabel('Place ID')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.base import BaseEstimator, TransformerMixin\n\nclass GridConverter(BaseEstimator, TransformerMixin):\n    def __init__(self):\n        return None\n\n    def fit(self, X, y=None):\n        return self\n\n    def transform(self, X):\n        x_coord, y_coord, accuracy, time = 0, 1, 2, 3\n        new_col = X[:,x_coord] * 1000 + (9 * 1000 * X[:, y_coord])\n        return np.c_[X, new_col]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.neighbors import KNeighborsClassifier\nsecond_pl = Pipeline(steps=[\n    ('std_scaler', StandardScaler()),\n    ('grid_converter', GridConverter()),\n    ('knn', KNeighborsClassifier(n_neighbors=5))\n])\n\nsecond_pl.fit(X, y)\npredictions = second_pl.predict(holdout_df)\npredictions_df = holdout_df.copy()\npredictions_df['predictions'] = predictions\npredictions_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_df = predictions_df['predictions']\nnew_df.rename({'predictions': 'place_id'})\nnew_df.to_csv('/kaggle/working/df.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_df","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}