{"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-24T06:32:26.567207Z","iopub.execute_input":"2022-07-24T06:32:26.567717Z","iopub.status.idle":"2022-07-24T06:32:26.604782Z","shell.execute_reply.started":"2022-07-24T06:32:26.567616Z","shell.execute_reply":"2022-07-24T06:32:26.603708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prediction Flow\n1. Scaling data(RobustScaler &PowerTransformer )\n2. Repeat of clustering for making pre-clustering dataset (BayesianGaussianMixture)\n3. Check cluster number by elbow-K-means(K-means)\n4. Final clustering using the pre-clustering dataset (K-means)\n5. visualization\n\n**予測の流れ**\n1. RobustScaler &PowerTransformerを用いたデータのスケーリング\n2. クラスタリングの反復、および結果を格納したデータセットの作成 (BayesianGaussianMixture)\n3. 結果を格納したデータセット、elbow-k-meansを用いたクラスター数確認 (K-means)\n4. 3で求めたクラスター数で改めてクラスタリング (K-means)\n5. データの可視化\n","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-24T06:32:26.606684Z","iopub.execute_input":"2022-07-24T06:32:26.607090Z","iopub.status.idle":"2022-07-24T06:32:28.321447Z","shell.execute_reply.started":"2022-07-24T06:32:26.607052Z","shell.execute_reply":"2022-07-24T06:32:28.319969Z"},"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\nscaled_data=preprocessing.RobustScaler().fit_transform(df)\nscaled_data=preprocessing.PowerTransformer().fit_transform(scaled_data)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T06:32:28.324083Z","iopub.execute_input":"2022-07-24T06:32:28.324654Z","iopub.status.idle":"2022-07-24T06:32:34.125611Z","shell.execute_reply.started":"2022-07-24T06:32:28.324603Z","shell.execute_reply":"2022-07-24T06:32:34.124225Z"},"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, in this time, 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.\n\n\n機械学習を用いた予測を行う上で、ランダムシードは結果に大きな影響を与える。よって今回はクラスタリングを100回繰り替えし、結果をデータセットにまとめる。結果をまとめたデータセット(最初にあたえられた特徴量は含んでいない)を最後にクラスタリングし、その結果を予測とした。","metadata":{}},{"cell_type":"code","source":" cluster_result=pd.DataFrame(data_for_submission)\n\nfor randomseed in range(0,100):\n    prediction = BayesianGaussianMixture(n_components=7,random_state=randomseed).fit_predict(scaled_data)\n    prediction = pd.DataFrame(prediction)\n    cluster_result=pd.concat([cluster_result,prediction],axis=1)\n    print(randomseed)\n\n    \nfinal_cluster_result=pd.DataFrame(cluster_result)\nprint(final_cluster_result)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T06:32:34.128940Z","iopub.execute_input":"2022-07-24T06:32:34.129690Z","iopub.status.idle":"2022-07-24T08:32:01.259308Z","shell.execute_reply.started":"2022-07-24T06:32:34.129653Z","shell.execute_reply":"2022-07-24T08:32:01.258032Z"},"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-24T08:44:43.917945Z","iopub.execute_input":"2022-07-24T08:44:43.918383Z","iopub.status.idle":"2022-07-24T09:18:29.048519Z","shell.execute_reply.started":"2022-07-24T08:44:43.918348Z","shell.execute_reply":"2022-07-24T09:18:29.047288Z"},"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-24T09:22:02.441278Z","iopub.execute_input":"2022-07-24T09:22:02.441770Z","iopub.status.idle":"2022-07-24T09:22:06.043108Z","shell.execute_reply.started":"2022-07-24T09:22:02.441730Z","shell.execute_reply":"2022-07-24T09:22:06.041167Z"},"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-24T09:22:12.396583Z","iopub.execute_input":"2022-07-24T09:22:12.397189Z","iopub.status.idle":"2022-07-24T09:23:38.513452Z","shell.execute_reply.started":"2022-07-24T09:22:12.397129Z","shell.execute_reply":"2022-07-24T09:23:38.511656Z"},"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":{"iopub.status.busy":"2022-07-24T08:32:01.417944Z","iopub.status.idle":"2022-07-24T08:32:01.418408Z","shell.execute_reply.started":"2022-07-24T08:32:01.418171Z","shell.execute_reply":"2022-07-24T08:32:01.418190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"To be continued.  Next, Semi-supervised learning\n\n続く 次は半教師あり学習","metadata":{}}]}