{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":102335,"databundleVersionId":12518947,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":{"iopub.status.busy":"2025-07-02T01:19:07.734975Z","iopub.execute_input":"2025-07-02T01:19:07.735514Z","iopub.status.idle":"2025-07-02T01:19:07.750606Z","shell.execute_reply.started":"2025-07-02T01:19:07.735464Z","shell.execute_reply":"2025-07-02T01:19:07.748886Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"This notebook contains a simple implementation of a Random Forest model using the dataset from \"CMI - Detect Behavior with Sensor Data\".\nThe model is designed to classify Body-Focused Repetitive Behaviors (BFRBs) versus non-BFRBs.\n\nI've also included basic visualizations such as the confusion matrix, accuracy score, and feature importance plot to help understand the model's performance.\nThe code is written as concisely as possible and is intended for super beginners—I'm also a beginner, and this is my first competition!\nThis notebook can serve as a starting point or baseline for developing more advanced models, rather than as a final solution.\n\nI hope this helps fellow beginners as they get started—good luck and have fun!","metadata":{}},{"cell_type":"code","source":"###importing packages\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sklearn\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GroupShuffleSplit\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import confusion_matrix","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T01:19:07.752430Z","iopub.execute_input":"2025-07-02T01:19:07.752791Z","iopub.status.idle":"2025-07-02T01:19:07.764232Z","shell.execute_reply.started":"2025-07-02T01:19:07.752766Z","shell.execute_reply":"2025-07-02T01:19:07.763241Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"###Importing the dataset\ntrain0 = pd.read_csv('/kaggle/input/cmi-detect-behavior-with-sensor-data/train.csv')\n\ntrain = train0.drop([\"row_id\",\"sequence_id\",\"behavior\",\"phase\",\"gesture\"], axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T01:19:07.765387Z","iopub.execute_input":"2025-07-02T01:19:07.765691Z","iopub.status.idle":"2025-07-02T01:19:36.215418Z","shell.execute_reply.started":"2025-07-02T01:19:07.765669Z","shell.execute_reply":"2025-07-02T01:19:36.214323Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"### Splitting features and labels\ntrain_x_all = train.drop(columns=[\"sequence_type\"])\ntrain_y = LabelEncoder().fit_transform(train[\"sequence_type\"])\n\n###Endoding 'subject' and 'orientation'\nfor col in [\"subject\", \"orientation\"]:\n    train_x_all[col] = LabelEncoder().fit_transform(train_x_all[col])\n\n###splittind dataset for training and validation\n##Stratifying the dataset by 'subject'\ngss = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)\n\nfor train_idx, valid_idx in gss.split(train_x_all, train_y, groups=train[\"subject\"]):\n    x_train, x_valid = train_x_all.iloc[train_idx], train_x_all.iloc[valid_idx]\n    y_train, y_valid = train_y[train_idx], train_y[valid_idx]\n\n\n# Deleting Nan\ny_train = pd.Series(y_train, index=x_train.index)\ny_valid = pd.Series(y_valid, index=x_valid.index)\n\nx_train_dropna = x_train.dropna()\ny_train_dropna = y_train.loc[x_train_dropna.index]\n\nx_valid_dropna = x_valid.dropna()\ny_valid_dropna = y_valid.loc[x_valid_dropna.index]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T01:19:36.217515Z","iopub.execute_input":"2025-07-02T01:19:36.217951Z","iopub.status.idle":"2025-07-02T01:19:40.284711Z","shell.execute_reply.started":"2025-07-02T01:19:36.217910Z","shell.execute_reply":"2025-07-02T01:19:40.283169Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"###Training a RandomForest model\nclf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=0)\n\nclf.fit(x_train_dropna, y_train_dropna)\n\n###Prediction with the trained RandomForest model\ny_pred = clf.predict(x_valid_dropna)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T01:19:40.285925Z","iopub.execute_input":"2025-07-02T01:19:40.286222Z","iopub.status.idle":"2025-07-02T01:21:39.903154Z","shell.execute_reply.started":"2025-07-02T01:19:40.286193Z","shell.execute_reply":"2025-07-02T01:21:39.901893Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"###Creating a confusion matrix\ncm = confusion_matrix(y_valid_dropna, y_pred)\n\n###Visualizing the confusion matrix\n##Labels to represent the encoded class names\nlabels = ['Non-target', 'Target']\n\n##Visualizing the confusion matrix\nplt.figure(figsize=(8, 6))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=labels, yticklabels=labels)\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.title('Confusion Matrix')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T01:21:39.904768Z","iopub.execute_input":"2025-07-02T01:21:39.905547Z","iopub.status.idle":"2025-07-02T01:21:40.130042Z","shell.execute_reply.started":"2025-07-02T01:21:39.905510Z","shell.execute_reply":"2025-07-02T01:21:40.129118Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"###Calculating accuray from confusion matrix\naccuracy = cm.trace()/cm.sum()\n\nprint(accuracy)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T01:21:40.131677Z","iopub.execute_input":"2025-07-02T01:21:40.131958Z","iopub.status.idle":"2025-07-02T01:21:40.137232Z","shell.execute_reply.started":"2025-07-02T01:21:40.131936Z","shell.execute_reply":"2025-07-02T01:21:40.136103Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"###Visualizing feature importance\n## Extract the top 15 most important features\nimportances = pd.Series(clf.feature_importances_, index=x_train.columns)\nimportance_top_15 = importances.sort_values(ascending=False).head(15)\n\nplt.figure(figsize=(10, 6))\nplt.barh(y=range(len(importance_top_15)), width=importance_top_15)# Plot horizontal bar chart\nplt.yticks(ticks=range(len(importance_top_15)), labels=importance_top_15.index) # Set y-axis labels\nplt.gca().invert_yaxis()  # Show most important feature at the top\nplt.xlabel(\"Feature Importance\")\nplt.title(\"Top 15 Feature Importances\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T01:21:40.138292Z","iopub.execute_input":"2025-07-02T01:21:40.139385Z","iopub.status.idle":"2025-07-02T01:21:40.400560Z","shell.execute_reply.started":"2025-07-02T01:21:40.139335Z","shell.execute_reply":"2025-07-02T01:21:40.399641Z"}},"outputs":[],"execution_count":null}]}