{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.16","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpu1vmV38","dataSources":[{"sourceId":91048,"databundleVersionId":10710872,"sourceType":"competition"}],"dockerImageVersionId":30841,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\n\n# Load the training data.The notebook was written on kaggle thus the data path has been used like this\ntrain_df = pd.read_csv('/kaggle/input/beginners-hypothesis-25/BH25/Training_Data/train.csv')\ntrain_df = train_df[:5000]#we train data on half of the dataset due to accelerator and time limitations","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2 #to extract the videos into frames\n#a function to convert a vedio into frames\ndef process_video(video_path):\n    cap = cv2.VideoCapture(video_path)\n    frames = []\n    while True:\n        ret, frame = cap.read()#ret for availability of frame and and frame to store the frame\n        if not ret:\n            break\n        frame = cv2.resize(frame, (64, 64))#standardization\n        frames.append(frame)\n    cap.release()\n    frames = np.array(frames)  # Shape: (20, 64, 64, 3)\n    return frames.flatten()  # Flattenning to 1D array\n    \nvideo_features = []\nfor idx, row in train_df.iterrows():#running the above function for every training video\n    video_path = f\"/kaggle/input/beginners-hypothesis-25/BH25/Training_Data/Train_Videos/{row['video_id']}.mp4\"\n    video_features.append(process_video(video_path))\n\nvideo_features = np.array(video_features)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n# Encoding categorical attributes using the Label Encoder\ndef encode_categorical_columns(df, columns):\n    label_encoders = {}\n    for col in columns:\n        le = LabelEncoder()\n        df[col] = le.fit_transform(df[col])\n        label_encoders[col] = le\n    return df, label_encoders\n\ncategorical_columns = ['element', 'motion', 'power']\ntrain_df, label_encoders = encode_categorical_columns(train_df, categorical_columns)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ny_speed = train_df[['speed']]\ny_summary = train_df['video_summary'].apply(lambda x: eval(x))  # Convert string tuples to actual tuples\ny_categorical = train_df[categorical_columns]\n# Spliting data for training and validation\nX_train_speed, X_val_speed, y_train_speed, y_val_speed = train_test_split(video_features, y_speed, test_size=0.2, random_state=42)\nX_train_cat, X_val_cat, y_train_cat, y_val_cat = train_test_split(video_features, y_categorical, test_size=0.2, random_state=42)\nX_train_summary, X_val_summary, y_train_summary, y_val_summary = train_test_split(video_features, y_summary, test_size=0.2, random_state=42)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.svm import SVR #using svm for our model\n\n\n# Training SVM regression models for speed\nmodel_continuous = SVR(kernel = 'linear', C = 1)#we use linear because through training on previous models like decision tree,xgboost,linear regression,ridge,lasso,we find that data is more accurate for linear. C=1 is a small value of C to allow a certain value of freedom\nmodel_continuous.fit(X_train_speed, y_train_speed)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.svm import SVC#using svm classifier for classification tyoe of data\n\nmodels_categorical = {}\nfor col in categorical_columns:\n     model=SVC(kernel = 'linear', C = 1)\n     model.fit(X_train_cat, y_train_cat[col])\n     models_categorical[col] = model","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Training for video_summary using separate models for x and y here\n\nx_values, y_values = zip(*y_train_summary)\n\nmodel_summary_x = SVR(kernel = 'linear', C = 1)\nmodel_summary_x.fit(X_train_summary, x_values)\n\nmodel_summary_y =SVR(kernel = 'linear', C = 1)\nmodel_summary_y.fit(X_train_summary, y_values)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\ntest_folder = '/kaggle/input/beginners-hypothesis-25/BH25/Testing_Data/'\n\ntest_features = []\nvideo_ids = []\n\n# using the above created process video to prepare the test data\n\nfor video_id in sorted(\n    [f for f in os.listdir(test_folder) if f.endswith(\".mp4\")], key=lambda x: int(x.split('.')[0])):\n    video_path = os.path.join(test_folder, video_id)\n    video_ids.append(video_id.split('.')[0]) \n    test_features.append(process_video(video_path))\n\n\ntest_features = np.array(test_features)  # Shape: (num_test_samples, 20*64*64*3)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#predicting our regression datas\ny_test_speed = model_continuous.predict(test_features)\ny_test_summary_x = model_summary_x.predict(test_features)\ny_test_summary_y = model_summary_y.predict(test_features)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_categorical = {}\n#predicting our classification data\nfor col in categorical_columns:\n    y_categorical[col] = models_categorical[col].predict(test_features)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# decoding the label encoding to prepare our csv submission file\n\ndecoded_categorical = {}\nfor col, predictions in y_categorical.items():\n    rounded_predictions = np.rint(predictions).astype(int)#converting the predictions into rounded integer values\n    valid_classes = range(len(label_encoders[col].classes_))#finding out the total number of categories in various types of categorial data for example no of elements in the element\n    rounded_predictions = np.clip(rounded_predictions, min(valid_classes), max(valid_classes))#filtering our data for any out of range output\n    decoded_categorical[col] = label_encoders[col].inverse_transform(rounded_predictions)#reversing our encoding","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"speed_predictions = y_test_speed.flatten()  # Ensuring that we have a 1d array firr regression values\nsummary_x_predictions = y_test_summary_x.flatten()\nsummary_y_predictions = y_test_summary_y.flatten()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output_df = pd.DataFrame({\n    'video_id': video_ids,                      \n    'element': decoded_categorical['element'],  \n    'motion': decoded_categorical['motion'],\n    'power': decoded_categorical['power'],\n    'speed': speed_predictions,               \n    'video_summary': list(zip(summary_x_predictions, summary_y_predictions)) \n})","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output_df.to_csv(\"submission.csv\", index=False)\n\n# This is the submission file to be submitted","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}