{"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":"gpu","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":31012,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\nfrom sklearn.model_selection import train_test_split\n\n#import sklearn\n#sklearn.set_config(transform_output=\"pandas\")\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport tensorflow.keras.layers as L\nimport tensorflow.keras.models as M\nimport tensorflow.keras.callbacks as C\nimport tensorflow as tf\nfrom tensorflow.keras import layers as L, models as M, callbacks as C\nfrom tensorflow.keras.applications import InceptionV3\nfrom tensorflow.keras import Model\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-04-18T12:08:40.148639Z","iopub.execute_input":"2025-04-18T12:08:40.149254Z","iopub.status.idle":"2025-04-18T12:08:40.155873Z","shell.execute_reply.started":"2025-04-18T12:08:40.149212Z","shell.execute_reply":"2025-04-18T12:08:40.155033Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ndf_test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-18T12:08:40.156876Z","iopub.execute_input":"2025-04-18T12:08:40.157090Z","iopub.status.idle":"2025-04-18T12:08:43.158126Z","shell.execute_reply.started":"2025-04-18T12:08:40.157075Z","shell.execute_reply":"2025-04-18T12:08:43.157338Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-18T12:08:43.159440Z","iopub.execute_input":"2025-04-18T12:08:43.160009Z","iopub.status.idle":"2025-04-18T12:08:43.183908Z","shell.execute_reply.started":"2025-04-18T12:08:43.159982Z","shell.execute_reply":"2025-04-18T12:08:43.183153Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"LABEL = \"label\"\nFEATURES = [c for c in df_train.columns if c != LABEL]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-18T12:08:43.184810Z","iopub.execute_input":"2025-04-18T12:08:43.185150Z","iopub.status.idle":"2025-04-18T12:08:43.189337Z","shell.execute_reply.started":"2025-04-18T12:08:43.185126Z","shell.execute_reply":"2025-04-18T12:08:43.188752Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y = df_train[LABEL]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-18T12:08:43.190927Z","iopub.execute_input":"2025-04-18T12:08:43.191139Z","iopub.status.idle":"2025-04-18T12:08:43.205926Z","shell.execute_reply.started":"2025-04-18T12:08:43.191124Z","shell.execute_reply":"2025-04-18T12:08:43.205346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = df_train[FEATURES].values.astype(\"float32\") / 255.0\nX = X.reshape(-1, 28, 28, 1)\n\nX_test = df_test.values.astype(\"float32\") / 255.0\nX_test = X_test.reshape(-1, 28, 28, 1)\n\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\nprint(\"Shape entraînement:\", X_train.shape)\nprint(\"Shape validation:\", X_val.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-18T12:08:43.206689Z","iopub.execute_input":"2025-04-18T12:08:43.206942Z","iopub.status.idle":"2025-04-18T12:08:43.770050Z","shell.execute_reply.started":"2025-04-18T12:08:43.206921Z","shell.execute_reply":"2025-04-18T12:08:43.769227Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def create_custom_model(input_shape=(28, 28, 1), num_classes=10):\n    model = M.Sequential([\n        L.Input(shape=input_shape), \n        \n        L.Conv2D(32, kernel_size=3, activation='relu'),\n        L.MaxPooling2D(pool_size=2),\n        \n        L.Conv2D(64, kernel_size=3, activation='relu'),\n        L.MaxPooling2D(pool_size=2),\n        \n        L.Flatten(),\n        L.Dense(128, activation='relu'),\n        L.Dropout(0.5),\n        L.Dense(num_classes, activation='softmax')\n    ])\n    model.compile(\n        optimizer='adam',\n        loss='sparse_categorical_crossentropy',\n        metrics=['accuracy']\n    )\n    return model\n\ndef create_inceptionv3_model(input_shape=(28, 28, 1), num_classes=10):\n    base_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(299, 299, 3))\n    \n    base_model.trainable = False\n    \n    input_layer = L.Input(shape=input_shape)\n    \n    x = L.Conv2D(3, (1, 1), padding='same', activation='relu')(input_layer)\n    x = L.Resizing(299, 299)(x)\n    \n    x = base_model(x)\n    \n    x = L.GlobalAveragePooling2D()(x)\n    x = L.Dense(128, activation='relu')(x)\n    x = L.Dropout(0.5)(x)\n    output_layer = L.Dense(num_classes, activation='softmax')(x)\n    \n\n    model = Model(inputs=input_layer, outputs=output_layer)\n    \n    model.compile(\n        optimizer='adam',\n        loss='sparse_categorical_crossentropy',\n        metrics=['accuracy']\n    )\n    \n    return model\n\n\ndef create_model(mode='custom', input_shape=(28, 28, 1), num_classes=10):\n    if mode == 'custom':\n        return create_custom_model(input_shape, num_classes)\n    elif mode == 'inceptionv3':\n        return create_inceptionv3_model(input_shape, num_classes)\n    else:\n        raise ValueError(\"Mode non supporté. Choisis 'custom' ou 'inceptionv3'.\")\n\n\nmodel_mode = 'inceptionv3'  \nmodel = create_model(mode=model_mode)\n\nmodel.summary()\n\ncallbacks = [\n    C.EarlyStopping(patience=5, restore_best_weights=True)\n]\n\nhistory = model.fit(\n    X_train, y_train,\n    validation_data=(X_val, y_val),\n    epochs=30,\n    batch_size=64,\n    callbacks=callbacks\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-18T12:08:43.770944Z","iopub.execute_input":"2025-04-18T12:08:43.771193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nplt.plot(history.history['accuracy'], label='Train acc')\nplt.plot(history.history['val_accuracy'], label='Val acc')\nplt.title(\"Accuracy over epochs\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.grid(True)\nplt.show()\n\nplt.plot(history.history['loss'], label='Train loss')\nplt.plot(history.history['val_loss'], label='Val loss')\nplt.title(\"Loss over epochs\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.grid(True)\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = model.predict(X_test)\ny_pred_labels = np.argmax(y_pred, axis=1)\n\nsubmission = pd.DataFrame({\n    \"ImageId\": np.arange(1, len(y_pred_labels) + 1),\n    \"Label\": y_pred_labels\n})\nsubmission.to_csv(\"submission.csv\", index=False)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}