{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":83967,"databundleVersionId":9359709,"sourceType":"competition"}],"dockerImageVersionId":30761,"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_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score, classification_report\nimport numpy as np\n\n# Step 1: Load the Test Data\nfile_path = '/kaggle/input/data-poisoning-detection-challenge-01/test.csv'\ndf = pd.read_csv(file_path)\n\n# Prepare the data\nX = df.drop(columns=['index', 'Label'])  # Features: all columns except 'index' and 'Label'\ny = df['Label']  # Target: 'Label'\n\n# Step 2: Corrupt the Labels in the Test Data\n# Introduce label corruption: flip labels for a random 20% of the samples to simulate poisoning\nnp.random.seed(42)  # For reproducibility\ncorruption_fraction = 0.2\nnum_corrupted = int(len(df) * corruption_fraction)\ncorrupted_indices = np.random.choice(df.index, size=num_corrupted, replace=False)\n\n# Flip the labels at the corrupted indices\ndf.loc[corrupted_indices, 'Label'] = df.loc[corrupted_indices, 'Label'].apply(lambda x: 'normal' if x == 'attack' else 'Attack')\n\n# Prepare the corrupted data for model training\nX_train, X_test, y_train, y_test = train_test_split(X, df['Label'], test_size=0.2, random_state=42)\n\n# Step 3: Train the Model to Detect Poisoned Labels\ndetector_model = DecisionTreeClassifier(random_state=42)\ndetector_model.fit(X_train, y_train)\n\n# Step 4: Predict Using the Detector Model\npredicted_labels = detector_model.predict(X_test)\n\n# Step 5: Evaluate the Model\naccuracy = accuracy_score(y_test, predicted_labels)\nprint(f'Accuracy of Detection: {accuracy:.2f}')\nprint(classification_report(y_test, predicted_labels))\n\n","metadata":{"execution":{"iopub.status.busy":"2024-09-04T01:48:09.272388Z","iopub.execute_input":"2024-09-04T01:48:09.272832Z","iopub.status.idle":"2024-09-04T01:48:58.183511Z","shell.execute_reply.started":"2024-09-04T01:48:09.272790Z","shell.execute_reply":"2024-09-04T01:48:58.182361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score, classification_report\n\n# Step 1: Load the Data\nfile_path = '/kaggle/input/data-poisoning-detection-challenge-01/test.csv'\ndf = pd.read_csv(file_path)\n\n# Step 2: Introduce Label Flipping\nnp.random.seed(42)  # For reproducibility\ncorruption_fraction = 0.2  # Fraction of data to corrupt\nnum_corrupted = int(len(df) * corruption_fraction)  # Number of samples to corrupt\n\n# Randomly select indices to corrupt\ncorrupted_indices = np.random.choice(df.index, size=num_corrupted, replace=False)\n\n# Flip the labels at the corrupted indices\ndf.loc[corrupted_indices, 'Label'] = df.loc[corrupted_indices, 'Label'].apply(lambda x: 'normal' if x == 'Attack' else 'attack')\n\n# Step 3: Prepare Data for Detection\nX = df.drop(columns=['index', 'Label'])  # Features: all columns except 'index' and 'Label'\ny = df['Label']  # Target: 'Label'\n\n# Step 4: Train a KNN Classifier\nknn = KNeighborsClassifier(n_neighbors=5)\nknn.fit(X, y)\n\n# Step 5: Compute Consistency of Each Sample's Label with Its Neighbors\nneighbors = knn.kneighbors(X, return_distance=False)\nconsistent_count = []\n\nfor i, neighbor_indices in enumerate(neighbors):\n    neighbor_labels = y.iloc[neighbor_indices]\n    consistency_score = (neighbor_labels == y.iloc[i]).mean()  # Proportion of neighbors with the same label\n    consistent_count.append(consistency_score)\n\n# Step 6: Flag Samples with Low Consistency as Potentially Poisoned\nconsistency_threshold = 0.5  # Threshold to identify potentially poisoned samples\ndf['ConsistencyScore'] = consistent_count\ndf['PotentiallyPoisoned'] = df['ConsistencyScore'] < consistency_threshold\n\n# Step 7: Evaluate Detection Accuracy\ny_true = df.index.isin(corrupted_indices).astype(int)  # True labels for corruption: 1 if corrupted, else 0\ny_pred = df['PotentiallyPoisoned'].astype(int)  # Predicted labels for corruption\naccuracy = accuracy_score(y_true, y_pred)\n\nprint(f'Accuracy of Poisoning Detection: {accuracy:.2f}')\nprint(classification_report(y_true, y_pred))\n","metadata":{"execution":{"iopub.status.busy":"2024-09-04T01:57:08.193669Z","iopub.execute_input":"2024-09-04T01:57:08.194168Z","iopub.status.idle":"2024-09-04T02:10:27.951067Z","shell.execute_reply.started":"2024-09-04T01:57:08.194094Z","shell.execute_reply":"2024-09-04T02:10:27.949657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Step 3: Load the New Data (a.csv) for Prediction\nnew_file_path = '/kaggle/input/data-poisoning-detection-challenge-01/train.csv'\ndf_new = pd.read_csv(new_file_path)\n\n# Prepare the new data for prediction\nX_new = df_new.drop(columns=['index', 'Label'])  # Features: all columns except 'index' and 'Label'\n\n# Step 4: Predict Potentially Poisoned Samples\npredicted_labels = knn.predict(X_new)\n\n# Step 5: Create the Output for Submission\n# Since we don't know the true labels, we'll assume predictions are correct for comparison\noutput_df = pd.DataFrame({'index': df_new['index'], 'Label': (predicted_labels != df_new['Label']).astype(int)})\n\n# Step 6: Save the Output to CSV\noutput_df.to_csv('submission.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-09-04T02:19:31.825372Z","iopub.execute_input":"2024-09-04T02:19:31.825833Z","iopub.status.idle":"2024-09-04T02:40:49.609603Z","shell.execute_reply.started":"2024-09-04T02:19:31.825791Z","shell.execute_reply":"2024-09-04T02:40:49.608397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls","metadata":{"execution":{"iopub.status.busy":"2024-09-04T03:04:49.219779Z","iopub.execute_input":"2024-09-04T03:04:49.220273Z","iopub.status.idle":"2024-09-04T03:04:50.429576Z","shell.execute_reply.started":"2024-09-04T03:04:49.220227Z","shell.execute_reply":"2024-09-04T03:04:50.427804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}