{"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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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":"2021-06-15T12:17:09.561553Z","iopub.execute_input":"2021-06-15T12:17:09.562055Z","iopub.status.idle":"2021-06-15T12:17:09.565757Z","shell.execute_reply.started":"2021-06-15T12:17:09.562021Z","shell.execute_reply":"2021-06-15T12:17:09.565010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# This is a simple exploration of the train label \n\n* Train a simple Word2Vec model for 2 dimensions and get the average embeddings of each the labels\n* Cluster them by DBSCAN\n* Visualize each cluster using scatter plot","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom gensim.models import word2vec\nfrom sklearn.cluster import KMeans, DBSCAN\nimport plotly.express as px\nimport seaborn as sns\n\nimport tensorflow_hub as hub\nimport tensorflow as tf\nimport numpy as np\n\nimport plotly.offline as pyo\nimport plotly.express as px\n","metadata":{"execution":{"iopub.status.busy":"2021-06-15T12:17:09.567128Z","iopub.execute_input":"2021-06-15T12:17:09.567619Z","iopub.status.idle":"2021-06-15T12:17:09.590912Z","shell.execute_reply.started":"2021-06-15T12:17:09.567571Z","shell.execute_reply":"2021-06-15T12:17:09.589790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv(\"../input/coleridgeinitiative-show-us-the-data/train.csv\")\ntrain_df","metadata":{"execution":{"iopub.status.busy":"2021-06-15T12:17:09.592677Z","iopub.execute_input":"2021-06-15T12:17:09.593017Z","iopub.status.idle":"2021-06-15T12:17:09.691876Z","shell.execute_reply.started":"2021-06-15T12:17:09.592982Z","shell.execute_reply":"2021-06-15T12:17:09.690803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Form corpus","metadata":{}},{"cell_type":"code","source":"# Frame the corpus which is the unique train labels\n\ntrain_unique_label = np.unique(train_df.cleaned_label.values.astype('str'))\ncorpus = []\nfor label in train_unique_label:\n    corpus.append(label.split( ))","metadata":{"execution":{"iopub.status.busy":"2021-06-15T12:17:09.693587Z","iopub.execute_input":"2021-06-15T12:17:09.693877Z","iopub.status.idle":"2021-06-15T12:17:09.736854Z","shell.execute_reply.started":"2021-06-15T12:17:09.693850Z","shell.execute_reply":"2021-06-15T12:17:09.735730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Word2Vec Train function","metadata":{}},{"cell_type":"code","source":"def train_w2vec(corpus, dim, epochs):\n    '''\n    Function to train a simple word2Vec model\n    '''\n    model = word2vec.Word2Vec(vector_size = dim, min_count= 1)\n    model.build_vocab(corpus)\n    model.train(corpus, epochs=epochs, total_examples=model.corpus_count)\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2021-06-15T12:17:09.738378Z","iopub.execute_input":"2021-06-15T12:17:09.738750Z","iopub.status.idle":"2021-06-15T12:17:09.744198Z","shell.execute_reply.started":"2021-06-15T12:17:09.738718Z","shell.execute_reply":"2021-06-15T12:17:09.743093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Function to Get average embeddings","metadata":{}},{"cell_type":"code","source":"def get_avg_label_embedding(corpus, dim, model):\n    '''\n    Function to get the average word embeddings when the label is more than 1 word\n    '''\n\n    label_embedding = []\n    for label in corpus:\n        embedding_sum=np.zeros(shape=(dim, ))\n        for tok in label:\n            temp = model.wv[tok].copy()\n            \n            embedding_sum+=temp\n            \n        avg_embedding = embedding_sum/len(label)\n        label_embedding.append(avg_embedding.tolist())\n    \n    label_embedding = np.array(label_embedding)\n    \n    return label_embedding\n","metadata":{"execution":{"iopub.status.busy":"2021-06-15T12:17:09.745365Z","iopub.execute_input":"2021-06-15T12:17:09.745702Z","iopub.status.idle":"2021-06-15T12:17:09.761783Z","shell.execute_reply.started":"2021-06-15T12:17:09.745664Z","shell.execute_reply":"2021-06-15T12:17:09.760320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train and get embedding","metadata":{}},{"cell_type":"code","source":"# Train the word2Vec model for few epochs\ndim = 2\nmodel = train_w2vec(corpus, dim, epochs=100)\nlabel_embedding = get_avg_label_embedding(corpus, dim, model)\n\nlabel_embedding.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-15T12:17:09.763235Z","iopub.execute_input":"2021-06-15T12:17:09.763614Z","iopub.status.idle":"2021-06-15T12:17:10.039697Z","shell.execute_reply.started":"2021-06-15T12:17:09.763582Z","shell.execute_reply":"2021-06-15T12:17:10.038610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Cluster the data using DBSCAN","metadata":{}},{"cell_type":"code","source":"DBSCAN_cluster = DBSCAN(min_samples=1, eps=0.08)\nDBSCAN_cluster.fit(label_embedding)\nclusters = DBSCAN_cluster.labels_\n\nprint(f\"Total clusters formed are : {len(clusters)}\")","metadata":{"execution":{"iopub.status.busy":"2021-06-15T12:17:10.041657Z","iopub.execute_input":"2021-06-15T12:17:10.041958Z","iopub.status.idle":"2021-06-15T12:17:10.052019Z","shell.execute_reply.started":"2021-06-15T12:17:10.041927Z","shell.execute_reply":"2021-06-15T12:17:10.050691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualize\n-> However over the points for name of the dataset","metadata":{}},{"cell_type":"code","source":"# Set notebook mode to work in offline\npyo.init_notebook_mode()\n\n# Create traces\ntrace0 = px.scatter(x = label_embedding[:, 0], \n                    y = label_embedding[:, 1], \n                    color = clusters, \n                    hover_name=train_unique_label\n)\n\ntrace0.show()","metadata":{"execution":{"iopub.status.busy":"2021-06-15T12:17:10.055575Z","iopub.execute_input":"2021-06-15T12:17:10.055932Z","iopub.status.idle":"2021-06-15T12:17:10.277493Z","shell.execute_reply.started":"2021-06-15T12:17:10.055890Z","shell.execute_reply":"2021-06-15T12:17:10.276565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"With a quick hover on the points it looks like the cluster are good and similar domains are grouped together with few data points which are not clustered right. However you can play around with it by trying\n\n* Different epochs for Word2Vec, \n* Train for more Dimensions and reduce them using t-sne or PCA\n* Play with different cluster distance mertrics for DBSCAN clusters or different cluster algorithms","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}