{"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","execution":{"iopub.status.busy":"2022-07-31T15:38:22.263641Z","iopub.execute_input":"2022-07-31T15:38:22.264139Z","iopub.status.idle":"2022-07-31T15:38:22.279013Z","shell.execute_reply.started":"2022-07-31T15:38:22.264099Z","shell.execute_reply":"2022-07-31T15:38:22.277737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install scikit-lego","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:22.313330Z","iopub.execute_input":"2022-07-31T15:38:22.314131Z","iopub.status.idle":"2022-07-31T15:38:35.975848Z","shell.execute_reply.started":"2022-07-31T15:38:22.314090Z","shell.execute_reply":"2022-07-31T15:38:35.974531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom sklego.mixture import BayesianGMMClassifier, GMMClassifier\nfrom sklearn.mixture import GaussianMixture, BayesianGaussianMixture\nfrom sklearn.preprocessing import RobustScaler, PowerTransformer, MaxAbsScaler\nfrom scipy.stats import shapiro\nfrom termcolor import colored, cprint\nfrom sklearn.metrics import accuracy_score","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:35.978415Z","iopub.execute_input":"2022-07-31T15:38:35.978940Z","iopub.status.idle":"2022-07-31T15:38:35.989910Z","shell.execute_reply.started":"2022-07-31T15:38:35.978878Z","shell.execute_reply":"2022-07-31T15:38:35.988583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data=pd.read_csv(\"../input/tabular-playground-series-jul-2022/data.csv\")\nss=pd.read_csv(\"../input/tabular-playground-series-jul-2022/sample_submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:35.991566Z","iopub.execute_input":"2022-07-31T15:38:35.993247Z","iopub.status.idle":"2022-07-31T15:38:37.484593Z","shell.execute_reply.started":"2022-07-31T15:38:35.993195Z","shell.execute_reply":"2022-07-31T15:38:37.483468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:37.487184Z","iopub.execute_input":"2022-07-31T15:38:37.487584Z","iopub.status.idle":"2022-07-31T15:38:37.536797Z","shell.execute_reply.started":"2022-07-31T15:38:37.487549Z","shell.execute_reply":"2022-07-31T15:38:37.535802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Univariate Normality Test\nfor col in data.columns[1:]:\n    stat, p_value = shapiro(data[col])\n    alpha = 0.05\n    if p_value > alpha:\n        result = colored('Accepted', 'green')\n    else:\n        result = colored('Rejected', 'red')    \n    print(col,result, p_value)","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:37.538666Z","iopub.execute_input":"2022-07-31T15:38:37.540374Z","iopub.status.idle":"2022-07-31T15:38:37.821866Z","shell.execute_reply.started":"2022-07-31T15:38:37.540317Z","shell.execute_reply":"2022-07-31T15:38:37.820532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# www.kaggle.com/competitions/tabular-playground-series-jul-2022/discussion/334808\nuseful_cols = [\n    \"f_07\",\n    \"f_08\",\n    \"f_09\",\n    \"f_10\",\n    \"f_11\",\n    \"f_12\",\n    \"f_13\",\n    \"f_22\",\n    \"f_23\",\n    \"f_24\",\n    \"f_25\",\n    \"f_26\",\n    \"f_27\",\n    \"f_28\",\n]","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:37.823519Z","iopub.execute_input":"2022-07-31T15:38:37.824347Z","iopub.status.idle":"2022-07-31T15:38:37.831134Z","shell.execute_reply.started":"2022-07-31T15:38:37.824304Z","shell.execute_reply":"2022-07-31T15:38:37.829597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Using PowerTransformer and Scaling to adjust for Outlier\ndata_scaled = pd.DataFrame(PowerTransformer().fit_transform(data), columns=data.columns)\ndata_scaled = pd.DataFrame(\n    RobustScaler().fit_transform(data_scaled), columns=data_scaled.columns\n)\n\n# Test Data for predictions later\ntest_data = data_scaled[useful_cols].copy()","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:37.833072Z","iopub.execute_input":"2022-07-31T15:38:37.834245Z","iopub.status.idle":"2022-07-31T15:38:42.206515Z","shell.execute_reply.started":"2022-07-31T15:38:37.834195Z","shell.execute_reply":"2022-07-31T15:38:42.205372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n# Fit Bayesian Gaussian Mixture\nprint(\"Fitting Bayesian Gaussian Mixture..\")\nbgm = BayesianGaussianMixture(\n    n_components=7,\n    max_iter=200,\n    n_init=3,\n    random_state=1,\n    verbose_interval=100,\n    init_params = 'kmeans'\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:42.210805Z","iopub.execute_input":"2022-07-31T15:38:42.211197Z","iopub.status.idle":"2022-07-31T15:38:42.219262Z","shell.execute_reply.started":"2022-07-31T15:38:42.211161Z","shell.execute_reply":"2022-07-31T15:38:42.218108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bgm_labels = bgm.fit_predict(data_scaled)\nbgm_proba = bgm.predict_proba(data_scaled)","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:38:42.221294Z","iopub.execute_input":"2022-07-31T15:38:42.222158Z","iopub.status.idle":"2022-07-31T15:43:51.809938Z","shell.execute_reply.started":"2022-07-31T15:38:42.222108Z","shell.execute_reply":"2022-07-31T15:43:51.808491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#https://www.kaggle.com/code/sifrun/gaussian-mixture-model-is-all-you-need-0-7355\n#Bayessian Gaussian Mixture Classifier\n\nn_components = 7\ndata_scaled[\"predict\"] = bgm_labels\ndata_scaled[\"predict_proba\"] = 0\n\nfor n in range(n_components):\n    data_scaled[f\"bgm_proba_{n}\"] = bgm_proba[:, n]\n    data_scaled.loc[data_scaled.predict == n, \"bgm_proba\"] = data_scaled[\n        f\"bgm_proba_{n}\"\n    ]\n\ntrain_index = np.array([])\nfor n in range(n_components):\n    median = data_scaled[data_scaled.predict == n][\"bgm_proba\"].median()\n\n    # Experiment with different thresholds\n    # Higher thereshold might overfit\n    n_inx = data_scaled[\n        (data_scaled.predict == n) & (data_scaled.bgm_proba > 0.675)\n    ].index\n\n    train_index = np.concatenate((train_index, n_inx))\n    print(\n        f\"class:{n}\",\n        f\"median: {round(median,4)}\",\n        \"Training data:\"\n        + str(round(len(n_inx) / len(data_scaled[(data_scaled.predict == n)]), 2) * 100)\n        + \"%\",\n    )\n\n\nprint(f\"\\nSize of Training data : {len(train_index)}\")","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:43:51.815710Z","iopub.execute_input":"2022-07-31T15:43:51.816842Z","iopub.status.idle":"2022-07-31T15:43:51.994160Z","shell.execute_reply.started":"2022-07-31T15:43:51.816781Z","shell.execute_reply":"2022-07-31T15:43:51.992969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = data_scaled.loc[train_index][useful_cols]\ny = data_scaled.loc[train_index][\"predict\"]","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:43:51.995458Z","iopub.execute_input":"2022-07-31T15:43:51.995808Z","iopub.status.idle":"2022-07-31T15:43:52.063776Z","shell.execute_reply.started":"2022-07-31T15:43:51.995776Z","shell.execute_reply":"2022-07-31T15:43:52.062731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n# https://www.kaggle.com/code/karlcini/bayesiangmmclassifier\n#https://www.kaggle.com/code/grandlee/tps-jul-2022-clustering/edit\n\nbgm = BayesianGMMClassifier(\n    n_components = 7,\n    covariance_type = 'full', # defalut = 'full'\n    max_iter = 1000, # default = 100,\n    tol =1e-3,\n    init_params = 'kmeans', #default = kmeans,'k-means++', 'random'\n    random_state = 1, \n    verbose = 10,\n    n_init = 3\n)\nbgm.fit(X, y)","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:43:52.065402Z","iopub.execute_input":"2022-07-31T15:43:52.065746Z","iopub.status.idle":"2022-07-31T15:47:18.707573Z","shell.execute_reply.started":"2022-07-31T15:43:52.065715Z","shell.execute_reply":"2022-07-31T15:47:18.706206Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = bgm.predict(X)\naccuracy_score(y, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:47:18.710442Z","iopub.execute_input":"2022-07-31T15:47:18.712356Z","iopub.status.idle":"2022-07-31T15:47:19.921978Z","shell.execute_reply.started":"2022-07-31T15:47:18.712299Z","shell.execute_reply":"2022-07-31T15:47:19.920813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = bgm.predict(test_data)","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:47:19.923839Z","iopub.execute_input":"2022-07-31T15:47:19.924582Z","iopub.status.idle":"2022-07-31T15:47:21.391679Z","shell.execute_reply.started":"2022-07-31T15:47:19.924536Z","shell.execute_reply":"2022-07-31T15:47:21.390740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pl = sns.countplot(x=predictions)\npl.set_title(\"Distribution of clusters\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:47:21.393547Z","iopub.execute_input":"2022-07-31T15:47:21.394377Z","iopub.status.idle":"2022-07-31T15:47:21.651819Z","shell.execute_reply.started":"2022-07-31T15:47:21.394331Z","shell.execute_reply":"2022-07-31T15:47:21.650370Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ss=pd.read_csv(\"../input/tabular-playground-series-jul-2022/sample_submission.csv\")\nss[\"Predicted\"] = predictions\nss.to_csv(\n    \"submission.csv\",\n    index=False,\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-31T15:47:21.653365Z","iopub.execute_input":"2022-07-31T15:47:21.653742Z","iopub.status.idle":"2022-07-31T15:47:21.854939Z","shell.execute_reply.started":"2022-07-31T15:47:21.653708Z","shell.execute_reply":"2022-07-31T15:47:21.853987Z"},"trusted":true},"execution_count":null,"outputs":[]}]}