{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":3362,"databundleVersionId":31148}],"dockerImageVersionId":31259,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport cv2\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout, Activation, Conv2D, MaxPooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:17:40.858342Z","iopub.execute_input":"2026-03-27T11:17:40.859213Z","iopub.status.idle":"2026-03-27T11:17:52.959051Z","shell.execute_reply.started":"2026-03-27T11:17:40.859161Z","shell.execute_reply":"2026-03-27T11:17:52.958103Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:17:52.960670Z","iopub.execute_input":"2026-03-27T11:17:52.961340Z","iopub.status.idle":"2026-03-27T11:18:04.097160Z","shell.execute_reply.started":"2026-03-27T11:17:52.961283Z","shell.execute_reply":"2026-03-27T11:18:04.096374Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Liste les GPUs visibles par TensorFlow\ngpus = tf.config.list_physical_devices('GPU')\n\nif gpus:\n    print(f\"✅ GPU détecté : {gpus}\")\n    # Affiche le nom spécifique du GPU\n    print(f\"Détails : {tf.test.gpu_device_name()}\")\nelse:\n    print(\"❌ Aucun GPU détecté. Vérifie les paramètres de ta session Kaggle (Settings > Accelerator).\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:04.098459Z","iopub.execute_input":"2026-03-27T11:18:04.098867Z","iopub.status.idle":"2026-03-27T11:18:05.024016Z","shell.execute_reply.started":"2026-03-27T11:18:04.098839Z","shell.execute_reply":"2026-03-27T11:18:05.023035Z"},"jupyter":{"source_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"main_dir = \"/kaggle/working/\"\ntrain_dir = \"train\"\npath = os.path.join(main_dir,train_dir)\n\nfor p in os.listdir(path):\n    category = p.split(\".\")[0]\n    img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)\n    new_img_array = cv2.resize(img_array, dsize=(200, 200))\n    plt.imshow(new_img_array,cmap='gray')\n    break","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:05.025273Z","iopub.execute_input":"2026-03-27T11:18:05.025552Z","iopub.status.idle":"2026-03-27T11:18:05.320052Z","shell.execute_reply.started":"2026-03-27T11:18:05.025528Z","shell.execute_reply":"2026-03-27T11:18:05.319276Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = []\ny = []\nconvert = lambda category : int(category == 'dog')\ndef create_test_data(path):\n    for p in os.listdir(path):\n        category = p.split(\".\")[0]\n        category = convert(category)\n        img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)\n        new_img_array = cv2.resize(img_array, dsize=(200, 200))\n        X.append(new_img_array)\n        y.append(category)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:05.321951Z","iopub.execute_input":"2026-03-27T11:18:05.322179Z","iopub.status.idle":"2026-03-27T11:18:05.328677Z","shell.execute_reply.started":"2026-03-27T11:18:05.322159Z","shell.execute_reply":"2026-03-27T11:18:05.327813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"create_test_data(path)\nX = np.array(X).reshape(-1, 200,200,1)\ny = np.array(y)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:05.329719Z","iopub.execute_input":"2026-03-27T11:18:05.330108Z","iopub.status.idle":"2026-03-27T11:18:21.602908Z","shell.execute_reply.started":"2026-03-27T11:18:05.330073Z","shell.execute_reply":"2026-03-27T11:18:21.601933Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images_label_0 = X[y == 0]\nimages_label_1 = X[y == 1]\n\n\nmean_val_0 = np.mean(images_label_0)\nmean_val_1 = np.mean(images_label_1)\n\nmedian_val_0 = np.median(images_label_0)\nmedian_val_1 = np.median(images_label_1)\n\nstd_0 = np.std(images_label_0)\nstd_1 = np.std(images_label_1)\n\nprint(f\"Label Chat\\nIntensité moyenne (: {mean_val_0:.2f})\\nIntensité médiane (: {median_val_0:.2f})\\nStandard Deviation (: {std_0:.2f})\")\nprint(\" \")\nprint(f\"Label Chien\\nIntensité moyenne (: {mean_val_1:.2f})\\nIntensité médiane (: {median_val_1:.2f})\\nStandard Deviation : {std_1:.2f})\") ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:21.604135Z","iopub.execute_input":"2026-03-27T11:18:21.604515Z","iopub.status.idle":"2026-03-27T11:18:31.427677Z","shell.execute_reply.started":"2026-03-27T11:18:21.604481Z","shell.execute_reply":"2026-03-27T11:18:31.426883Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = X/255","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:31.428895Z","iopub.execute_input":"2026-03-27T11:18:31.429214Z","iopub.status.idle":"2026-03-27T11:18:33.926450Z","shell.execute_reply.started":"2026-03-27T11:18:31.429181Z","shell.execute_reply":"2026-03-27T11:18:33.925796Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(X.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:33.927399Z","iopub.execute_input":"2026-03-27T11:18:33.927616Z","iopub.status.idle":"2026-03-27T11:18:33.932348Z","shell.execute_reply.started":"2026-03-27T11:18:33.927596Z","shell.execute_reply":"2026-03-27T11:18:33.931093Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(\n    np.array(X), np.array(y), \n    test_size=0.2, \n    random_state=42, \n    shuffle=True\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:33.933406Z","iopub.execute_input":"2026-03-27T11:18:33.933769Z","iopub.status.idle":"2026-03-27T11:18:38.980521Z","shell.execute_reply.started":"2026-03-27T11:18:33.933732Z","shell.execute_reply":"2026-03-27T11:18:38.979843Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model=keras.Sequential([\n    layers.RandomFlip('horizontal'),\n    layers.RandomContrast(0.5),\n    layers.Conv2D(64,(3,3), activation = 'relu', input_shape = X.shape[1:]),\n    layers.MaxPooling2D(pool_size = (2,2)),\n    layers.Conv2D(64,(3,3), activation = 'relu'),\n    layers.MaxPooling2D(pool_size = (2,2)),\n    layers.Flatten(),\n    layers.Dense(units=64, activation ='relu'),\n    layers.Dropout(rate=0.3),\n    layers.Dense(units=24, activation= 'relu'),\n    #layers.Dropout(rate=0.3),\n    #layers.Dense(units=6,activation= 'relu'),\n    layers.Dense (units=1, activation= 'sigmoid')\n                 \n])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:38.981481Z","iopub.execute_input":"2026-03-27T11:18:38.981814Z","iopub.status.idle":"2026-03-27T11:18:39.040350Z","shell.execute_reply.started":"2026-03-27T11:18:38.981789Z","shell.execute_reply":"2026-03-27T11:18:39.039372Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer= Adam (learning_rate=0.0005, epsilon=0.01),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:39.041379Z","iopub.execute_input":"2026-03-27T11:18:39.041833Z","iopub.status.idle":"2026-03-27T11:18:39.060331Z","shell.execute_reply.started":"2026-03-27T11:18:39.041805Z","shell.execute_reply":"2026-03-27T11:18:39.059716Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stopping = EarlyStopping(\n  \t  min_delta=0.01, # minimium amount of change to count as an improvement\n   \t  patience=5, # how many epochs to wait before stopping\n   \t  restore_best_weights=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:39.061266Z","iopub.execute_input":"2026-03-27T11:18:39.061775Z","iopub.status.idle":"2026-03-27T11:18:39.065431Z","shell.execute_reply.started":"2026-03-27T11:18:39.061749Z","shell.execute_reply":"2026-03-27T11:18:39.064504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"epochs = 25\nhistory = model.fit(X_train, y_train, \n                    epochs=epochs, \n                    batch_size=32, \n                    validation_data=(X_val,y_val),\n                    callbacks=early_stopping)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:18:39.068034Z","iopub.execute_input":"2026-03-27T11:18:39.068238Z","iopub.status.idle":"2026-03-27T11:20:54.432782Z","shell.execute_reply.started":"2026-03-27T11:18:39.068219Z","shell.execute_reply":"2026-03-27T11:20:54.431772Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(history.history['val_loss'], color='r', label=\"Validation loss\")\nax1.set_xticks(np.arange(1, epochs, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\nax1.legend(['Train Loss','Val Loss'])\n\nax2.plot(history.history['accuracy'], color='b', label=\"Training\")\nax2.plot(history.history['val_accuracy'], color='r',label=\"Validation\")\nax2.set_xticks(np.arange(1, epochs, 1))\nax2.legend(['Train Accuracy', 'Val Accuracy'])\n\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:20:54.434007Z","iopub.execute_input":"2026-03-27T11:20:54.434396Z","iopub.status.idle":"2026-03-27T11:20:54.837546Z","shell.execute_reply.started":"2026-03-27T11:20:54.434359Z","shell.execute_reply":"2026-03-27T11:20:54.836738Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred_probs = model.predict(X_val)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:20:54.838656Z","iopub.execute_input":"2026-03-27T11:20:54.838948Z","iopub.status.idle":"2026-03-27T11:20:58.539280Z","shell.execute_reply.started":"2026-03-27T11:20:54.838923Z","shell.execute_reply":"2026-03-27T11:20:58.538248Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = (y_pred_probs > 0.5).astype(int)\ny_true = y_val","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:20:58.541294Z","iopub.execute_input":"2026-03-27T11:20:58.541685Z","iopub.status.idle":"2026-03-27T11:20:58.545938Z","shell.execute_reply.started":"2026-03-27T11:20:58.541657Z","shell.execute_reply":"2026-03-27T11:20:58.545129Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(confusion_matrix(y_pred,y_true))\nprint(classification_report(y_pred,y_true))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:20:58.547140Z","iopub.execute_input":"2026-03-27T11:20:58.547531Z","iopub.status.idle":"2026-03-27T11:20:58.577939Z","shell.execute_reply.started":"2026-03-27T11:20:58.547500Z","shell.execute_reply":"2026-03-27T11:20:58.577284Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"indices = np.random.choice(len(X_val), 10, replace=False)\nsample_images = X_val[indices]\nsample_labels = y_val[indices]\n\nplt.figure(figsize=(20, 10))\nclass_names= {1:'Chien', 0: 'Chat'}\n\nfor i in range(10):\n    plt.subplot(2, 5, i + 1)\n    plt.imshow(sample_images[i], cmap='gray')\n    p_idx = 1 if y_pred_probs[i] > 0.5 else 0\n    t_idx = int(sample_labels[i])  \n        \n    color = 'green' if p_idx == t_idx else 'red'\n    plt.axis('off')\n    plt.title(f\"Pred:{class_names[p_idx]} \\nProbabilité Chien: ({100*np.max(y_pred_probs[i]):.2f}%)\\nRéel: {class_names[t_idx]}\", color=color)\n    plt.axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-27T11:20:58.578790Z","iopub.execute_input":"2026-03-27T11:20:58.579031Z","iopub.status.idle":"2026-03-27T11:20:59.717637Z","shell.execute_reply.started":"2026-03-27T11:20:58.579010Z","shell.execute_reply":"2026-03-27T11:20:59.716436Z"}},"outputs":[],"execution_count":null}]}