{"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Imports\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier\nfrom sklearn import metrics\n\n# Collect data\ntrain = pd.read_csv('train.csv')\ntest = pd.read_csv('test.csv')\nprint('Data loaded')\n\n# Prep data\ny = train.os_family\ntrain = train.drop(['os_family'], axis=1)\n\nX = train\ntest = test.drop(['idx'], axis=1)\n\nX_train, X_val, y_train, y_val = train_test_split(X, y, train_size=0.95, random_state=0, stratify=y)\n\n# Select numerical columns\nnumerical_cols = [cname for cname in X_train.columns if X_train[cname].dtype in ['int64', 'float64']]\n\n# Preprocessing for numerical data\nnumerical_transformer = SimpleImputer(strategy='constant')\nX_train = X_train[numerical_cols].copy()\ntest = test[numerical_cols].copy()\n\npreprocessor = ColumnTransformer(transformers=[('num', numerical_transformer, numerical_cols)], n_jobs=6)\n\nmodel = XGBClassifier(n_estimators=1000, learning_rate=0.1, n_jobs=6)\n\nmy_pipeline = Pipeline(steps=[('preprocessor', preprocessor), ('model', model)])\n\nprint('Fitting')\nmy_pipeline.fit(X_train, y_train)\n\nprint('Validating')\npreds = my_pipeline.predict(X_val)\n\nscore = metrics.accuracy_score(y_val, preds)\nprint('Accuracy is:', score)\nprint(metrics.classification_report(y_val, preds))\n\n# Accuracy for 0.1 is: 0.9214188129332591\n\n#                precision    recall  f1-score   support\n#\n#       android       0.94      0.92      0.93     11412\n#           ios       0.90      0.92      0.91      8326\n# windows phone       0.00      0.00      0.00        25\n#\n#      accuracy                           0.92     19763\n#     macro avg       0.61      0.61      0.61     19763\n#  weighted avg       0.92      0.92      0.92     19763\n\n# Predict\n\nprint('Predicting')\nprediction = my_pipeline.predict(test)\nprint('Predictions made')\n\n# Export\nr = 0\n\nwith open('rood_result.csv', 'w') as result:\n        result.write('idx,os_family\\n')\n        for row in prediction:\n                result.write(str(r) + ',' + str(row) + '\\n')\n                r += 1\n\n###############################################################\n# After creating my top 3 XGBoost submissions I combined the results (into majority.csv) and did a\n# majority rule algorithm. The three variations were based on one feature selection, one PCA, and no preprocessing.\nresult = pd.read_csv('majority.csv')\n\n# Select the OS picked 2 out of 3 times. Since my models never predicted Windows phone, I didn't worry about a tie\nresult = result.mode(axis=1)\n\nprint(result.head())","metadata":{},"execution_count":null,"outputs":[]}]}