Commit 5660ba94 authored by Vihangi Yasuththara's avatar Vihangi Yasuththara

Carlini_Attack

parent 1af1567b
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "TPU"
},
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rK_SzMqlmnxM"
},
"outputs": [],
"source": [
"# Import necessary libraries\n",
"import pandas as pd\n",
"import numpy as np\n",
"import tensorflow as tf\n",
"from tensorflow.keras.models import load_model\n",
"from sklearn.preprocessing import StandardScaler\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix, classification_report\n",
"import time"
]
},
{
"cell_type": "code",
"source": [
"# Load and preprocess data\n",
"data = pd.read_csv('/content/drive/MyDrive/disease_preprocess4 (1).csv')\n",
"X = data.drop('HeartDisease', axis=1)\n",
"y = data['HeartDisease']"
],
"metadata": {
"id": "wqv74HAOm7dW"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Split the data\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n"
],
"metadata": {
"id": "cynqZpMBnNrM"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Standardize the data\n",
"scaler = StandardScaler()\n",
"X_train_scaled = scaler.fit_transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)"
],
"metadata": {
"id": "QOc6KlAom_t6"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Load the model\n",
"model = load_model('/content/drive/MyDrive/1D_CNN_model_Final_1.h5')"
],
"metadata": {
"id": "jV6o7PgHnTT9"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Get predictions and print evaluation metrics\n",
"y_pred = model.predict(X_test_scaled) > 0.5\n",
"print(confusion_matrix(y_test, y_pred))\n",
"print(classification_report(y_test, y_pred))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "0AZO9ULwnjcB",
"outputId": "160478df-964d-45bf-9017-6960e934aa30"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1931/1931 [==============================] - 10s 5ms/step\n",
"[[48627 8147]\n",
" [ 2117 2880]]\n",
" precision recall f1-score support\n",
"\n",
" 0 0.96 0.86 0.90 56774\n",
" 1 0.26 0.58 0.36 4997\n",
"\n",
" accuracy 0.83 61771\n",
" macro avg 0.61 0.72 0.63 61771\n",
"weighted avg 0.90 0.83 0.86 61771\n",
"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Highlight: Define X_train_combined as X_train_scaled if they are meant to be the same\n",
"X_train_combined = X_train_scaled # Added this line to define X_train_combined\n",
"\n",
"\n"
],
"metadata": {
"id": "fQP6MSUxoCjK"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def carlini_attack_binary(model, X, y, batch_size=100, epsilon=0.1, max_iterations=50, learning_rate=0.01):\n",
" # Process in batches\n",
" num_batches = int(np.ceil(len(X) / batch_size))\n",
" perturbed_Xs = []\n",
"\n",
" for i in range(num_batches):\n",
" start = i * batch_size\n",
" end = min((i + 1) * batch_size, len(X))\n",
" X_batch = tf.identity(X[start:end])\n",
" y_batch = tf.convert_to_tensor(y[start:end], dtype=tf.float32)\n",
" y_batch = tf.reshape(y_batch, (-1, 1)) # Ensure y_batch shape matches prediction shape\n",
"\n",
" for _ in range(max_iterations):\n",
" with tf.GradientTape() as tape:\n",
" tape.watch(X_batch)\n",
" prediction = model(X_batch)\n",
" loss = tf.keras.losses.binary_crossentropy(y_batch, prediction)\n",
"\n",
" gradients = tape.gradient(loss, X_batch)\n",
" X_batch -= learning_rate * gradients\n",
" X_batch = tf.clip_by_value(X_batch, X[start:end] - epsilon, X[start:end] + epsilon)\n",
" X_batch = tf.clip_by_value(X_batch, 0, 1)\n",
"\n",
" perturbed_Xs.append(X_batch)\n",
"\n",
" # Concatenate all batch results\n",
" perturbed_X = tf.concat(perturbed_Xs, axis=0)\n",
" return perturbed_X\n"
],
"metadata": {
"id": "dmdD2-Voupnf"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def carlini_wagner_attack(model, x, y, c=1, lr=0.01, iterations=100):\n",
" x_adv = tf.Variable(x, dtype=tf.float32) # Make sure x is in the correct format\n",
" target = tf.constant(y, dtype=tf.float32) # Make sure y is in the correct format\n",
" binary_crossentropy = tf.keras.losses.BinaryCrossentropy()\n",
"\n",
" optimizer = tf.optimizers.Adam(learning_rate=lr)\n",
"\n",
" for i in range(iterations):\n",
" with tf.GradientTape() as tape:\n",
" tape.watch(x_adv)\n",
" prediction = model(x_adv)\n",
" loss = c * binary_crossentropy(target, prediction) + tf.norm(x_adv - x)\n",
"\n",
" gradients = tape.gradient(loss, x_adv)\n",
" optimizer.apply_gradients([(gradients, x_adv)])\n",
" x_adv.assign(tf.clip_by_value(x_adv, 0, 1))\n",
"\n",
" return x_adv.numpy()"
],
"metadata": {
"id": "RtJOawHoy4IF"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Generate adversarial examples\n",
"X_test_tensor = tf.convert_to_tensor(X_test_scaled, dtype=tf.float32)"
],
"metadata": {
"id": "j3aUTzX6pajr"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"X_test_adv = carlini_attack_binary(model, X_test_tensor, y_test)"
],
"metadata": {
"id": "bVSlRZ_UzZY7"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Evaluate the model on adversarial examples\n",
"adv_accuracy = model.evaluate(X_test_adv, y_test)\n",
"print(\"Model accuracy on adversarial examples:\", adv_accuracy[1])"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "up-k1SJg7duy",
"outputId": "fed08c23-4917-42df-e98a-6753ee60a078"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1931/1931 [==============================] - 13s 6ms/step - loss: 12.9010 - accuracy: 0.0815\n",
"Model accuracy on adversarial examples: 0.08146217465400696\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# Evaluate the model on clean data\n",
"org_accuracy = model.evaluate(X_test_scaled, y_test)\n",
"print(\"Model accuracy on clean data:\", org_accuracy[1])"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "U2cLsLFZ7mpD",
"outputId": "6a4da8d4-602f-4a60-94fd-cd521b64454f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1931/1931 [==============================] - 9s 5ms/step - loss: 0.3520 - accuracy: 0.8338\n",
"Model accuracy on clean data: 0.8338378667831421\n"
]
}
]
}
]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment