{"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-27T11:52:48.409842Z","iopub.execute_input":"2022-07-27T11:52:48.410224Z","iopub.status.idle":"2022-07-27T11:52:48.421734Z","shell.execute_reply.started":"2022-07-27T11:52:48.410193Z","shell.execute_reply":"2022-07-27T11:52:48.420564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prediction Flow\n\n0. Selected useful feature (www.kaggle.com/competitions/tabular-playground-series-jul-2022/discussion/334808)\n1. Scaling data(RobustScaler &PowerTransformer )\n2. Repeat of clustering for making pre-clustering dataset (BayesianGaussianMixtureClassifier)←New!\n3. Check cluster number by elbow-K-means(K-means)\n4. Final clustering using the pre-clustering dataset (K-means)\n5. visualization\n\n**予測の流れ**\n\n0. 有用な特徴量の選択(www.kaggle.com/competitions/tabular-playground-series-jul-2022/discussion/334808)\n1. RobustScaler &PowerTransformerを用いたデータのスケーリング\n2. クラスタリングの反復、および結果を格納したデータセットの作成 (BayesianGaussianMixtureClassifier)←New!\n3. 結果を格納したデータセット、elbow-k-meansを用いたクラスター数確認 (K-means)\n4. 3で求めたクラスター数で改めてクラスタリング (K-means)\n5. データの可視化\n","metadata":{}},{"cell_type":"markdown","source":"The prediction result when a BaysianGaussianMixtureClassifier was applied were compared with the previous result(Score: 0.59850).\n\nBayesianGaussianMixtureClassifierを適用した場合の予測結果を前回(Score: 0.59850)と比較した。","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.decomposition import PCA\nfrom matplotlib import cm\nfrom sklearn.mixture import BayesianGaussianMixture\nfrom sklearn.preprocessing import RobustScaler, PowerTransformer\nfrom sklearn import preprocessing\nfrom sklearn.cluster import KMeans\nfrom sklearn import metrics","metadata":{"execution":{"iopub.status.busy":"2022-07-27T11:52:55.738473Z","iopub.execute_input":"2022-07-27T11:52:55.738851Z","iopub.status.idle":"2022-07-27T11:52:55.745751Z","shell.execute_reply.started":"2022-07-27T11:52:55.738821Z","shell.execute_reply":"2022-07-27T11:52:55.744597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import data、scaling data\ndata_path = '../input/tabular-playground-series-jul-2022/data.csv'\ndf = pd.read_csv(data_path)\n\ndata_for_submission=df[['id']]\ndf = df.drop(columns = \"id\")\n\n# www.kaggle.com/competitions/tabular-playground-series-jul-2022/discussion/334808\nuseful_cols = [\"f_07\",\"f_08\",\"f_09\",\"f_10\",\"f_11\",\"f_12\",\"f_13\",\"f_22\",\"f_23\",\"f_24\",\"f_25\",\"f_26\",\"f_27\",\"f_28\"]\n\ndf_uf = df[useful_cols]\n\nscaled_data=preprocessing.RobustScaler().fit_transform(df_uf)\nscaled_data=preprocessing.PowerTransformer().fit_transform(scaled_data)","metadata":{"execution":{"iopub.status.busy":"2022-07-27T11:52:59.452986Z","iopub.execute_input":"2022-07-27T11:52:59.453388Z","iopub.status.idle":"2022-07-27T11:53:02.528851Z","shell.execute_reply.started":"2022-07-27T11:52:59.453353Z","shell.execute_reply":"2022-07-27T11:53:02.527440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**#Clustering**\n\nRandom seeds have a great influence on the results when making predictions using machine learning.  Therefore, clustering is repeated 100 times and the results are summarized in a data set. The dataset without data of feature was used for final clustering, and the results were used as predictions.  Futhermore, in this time, I tried to apply BayesianGaussianMixtureClassifier for evaluating confidence of data clustered in first labeling.\n\n\n機械学習を用いた予測を行う上で、ランダムシードは結果に大きな影響を与える。よって今回はクラスタリングを100回繰り替えし、結果をデータセットにまとめる。結果をまとめたデータセット(最初にあたえられた特徴量は含んでいない)を最後にクラスタリングし、その結果を予測とした。さらに今回は最初のクラスタリングのラベルの信頼性をBayesianGaussianMixtureClassifierを用いることによって評価しました。","metadata":{}},{"cell_type":"code","source":"scaled_data=pd.DataFrame(scaled_data)\ncluster_result=pd.DataFrame(data_for_submission)\n\nfor randomseed in range(0,100):\n    gmm = BayesianGaussianMixture(n_components=7,random_state=randomseed).fit(scaled_data)\n    pred_probs = gmm.predict_proba(scaled_data)\n    pred_probs = pd.DataFrame(pred_probs, columns=range(1,8))\n    \n    max_cols=[]\n    for roop in range(0,pred_probs.shape[0]):\n        max_data=pred_probs.iloc[roop,:].max()\n        max_cols.append(max_data)\n    \n    max_cols=pd.DataFrame({'max_cols':max_cols})\n\n    df_pred_max=pd.concat([max_cols,pred_probs],axis=1)\n    df_pred_max=pd.concat([df_pred_max,scaled_data],axis=1)\n\n    df_pred_over09=df_pred_max.query('max_cols > 0.9')\n\n    df_pred_over09_input=df_pred_over09.iloc[:,8:df_pred_over09.shape[1]]\n    gmm = BayesianGaussianMixture(n_components=7,random_state=randomseed).fit(df_pred_over09_input)\n    pred_probs_result = gmm.predict(scaled_data)\n    prediction=pd.DataFrame({'predict':pred_probs_result})\n    \n    cluster_result=pd.concat([cluster_result,prediction],axis=1)\n    print(randomseed)\n\nfinal_cluster_result=pd.DataFrame(cluster_result)\nprint(final_cluster_result)","metadata":{"execution":{"iopub.status.busy":"2022-07-27T11:53:05.813034Z","iopub.execute_input":"2022-07-27T11:53:05.813740Z","iopub.status.idle":"2022-07-27T13:42:56.578599Z","shell.execute_reply.started":"2022-07-27T11:53:05.813705Z","shell.execute_reply":"2022-07-27T13:42:56.577321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The number of clusters was evaluated using the elbow method (k-means) in the dataset summarizing the results of clustering.\n\nクラスタリングの結果をまとめたデータセットをelbow法(k-mean)を用いて、クラスター数を評価した。","metadata":{}},{"cell_type":"code","source":"final_cluster_df= final_cluster_result.drop(columns = \"id\")\n\nscore=[]\nsum_of_squared_errors = []\nfor i in range(2, 15):\n    model = KMeans(n_clusters=i, random_state=0, init='random')\n    model.fit(final_cluster_df)\n    sum_of_squared_errors.append(model.inertia_)\n    prediction=model.predict(final_cluster_df)\n    \n    shscore=metrics.silhouette_score(final_cluster_df,prediction, metric='euclidean')\n    chscore=metrics.calinski_harabasz_score(final_cluster_df,prediction)\n    dbscore=metrics.davies_bouldin_score(final_cluster_df,prediction)\n    score.append([i,shscore,chscore,dbscore])\n    print(i)\n\nplt.plot(range(2, 15), sum_of_squared_errors, marker='o')\nplt.xlabel('number of clusters')\nplt.ylabel('sum of squared errors')\nplt.show()\n\nscore=pd.DataFrame(score)\nscore.columns = ['cluster_num','silhouette','calinski_harabasz','davies_bouldin'] \n\nprint(pd.DataFrame(score))\n\nplt.subplot(3,1,1)\nplt.plot(score.iloc[:,0],score.iloc[:,1],\n        color=cm.Set1.colors[1], label=\"silhouette_score\")\nplt.legend() \nplt.xticks(color='w')\n\nplt.subplot(3,1,2)\nplt.plot(score.iloc[:,0],score.iloc[:,2],\n        color=cm.Set1.colors[0], label=\"calinski_harabasz_score\")\nplt.legend()\nplt.xticks(color='w')\n\nplt.subplot(3,1,3)\nplt.plot(score.iloc[:,0],score.iloc[:,3],\n        color=cm.Set1.colors[2], label=\"davies_bouldin_score\")\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-07-27T13:47:50.713466Z","iopub.execute_input":"2022-07-27T13:47:50.714243Z","iopub.status.idle":"2022-07-27T14:15:48.645317Z","shell.execute_reply.started":"2022-07-27T13:47:50.714199Z","shell.execute_reply":"2022-07-27T14:15:48.643937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The number of clusters was set to 7 by the above analysis which are elbow plot, shelhouette_score, calinski_harabasz_score and davies_bouldin_score.\n\n上記の解析(elbow plot, shelhouette_score, calinski_harabasz_score and davies_bouldin_score)によりクラスター数を7に設定した。","metadata":{}},{"cell_type":"code","source":"model = KMeans(n_clusters=7, random_state=0, init='random')\nmodel.fit(final_cluster_df)\nfinal_prediction=model.predict(final_cluster_df)","metadata":{"execution":{"iopub.status.busy":"2022-07-27T14:41:38.574070Z","iopub.execute_input":"2022-07-27T14:41:38.574653Z","iopub.status.idle":"2022-07-27T14:41:40.861661Z","shell.execute_reply.started":"2022-07-27T14:41:38.574573Z","shell.execute_reply":"2022-07-27T14:41:40.860729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#visualization\nscaled_data=pd.DataFrame(scaled_data)\nfinal_cluster_df_plus=pd.concat([final_cluster_df.iloc[:,0:10],scaled_data],axis=1)\n\npca=PCA()\npca.fit(final_cluster_df_plus)\npca_row = pca.transform(final_cluster_df_plus)\npca_df = pd.DataFrame({\"PCA_1\" : pca_row[:,0], \"PCA_2\" : pca_row[:,1]})\n\npca_df['label']=final_prediction\nplt.figure(figsize=(6, 6))\nsns.scatterplot(data = pca_df, x = \"PCA_1\", y = \"PCA_2\", hue=\"label\", s=3)\nplt.show()\n    \nplt.figure(figsize=(6,6))\nsns.jointplot(data=pca_df, x=\"PCA_1\", y=\"PCA_2\", hue=\"label\", kind=\"kde\", fill=True,levels=3,alpha=1)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-27T14:41:49.269280Z","iopub.execute_input":"2022-07-27T14:41:49.269753Z","iopub.status.idle":"2022-07-27T14:43:17.005004Z","shell.execute_reply.started":"2022-07-27T14:41:49.269716Z","shell.execute_reply":"2022-07-27T14:43:17.003551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# submission\nsubmission = pd.read_csv(\"../input/tabular-playground-series-jul-2022/sample_submission.csv\")\n\nsubmission['Predicted'] = final_prediction\nsubmission.to_csv('submission.csv', index = False)\n\n#fin","metadata":{},"execution_count":null,"outputs":[]}]}