{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":61938,"databundleVersionId":6698770,"sourceType":"competition"},{"sourceId":7442871,"sourceType":"datasetVersion","datasetId":4332174}],"dockerImageVersionId":30635,"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\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","execution":{"iopub.status.busy":"2024-02-04T11:42:29.754557Z","iopub.execute_input":"2024-02-04T11:42:29.754793Z","iopub.status.idle":"2024-02-04T11:42:40.951670Z","shell.execute_reply.started":"2024-02-04T11:42:29.754770Z","shell.execute_reply":"2024-02-04T11:42:40.950751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 os\nimport matplotlib.pyplot as plt\nimport torch\nfrom torchvision import datasets, transforms, models\nfrom torch import nn, optim\nfrom torch.autograd import Variable\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torch.utils.data import Dataset, DataLoader\nfrom PIL import Image\nfrom skimage import io, transform\nimport torch.utils.data as data_utils\n\nclass DogBreedsDataset(Dataset):\n   \n\n    def __init__(self, csv_file, root_dir, transform=None):\n    \n        self.labels_frame = pd.read_csv(csv_file)\n        self.map = dict(zip(self.labels_frame['breed'].unique(),range(0,len(self.labels_frame['breed'].unique()))))\n        self.labels_frame['breed'] = self.labels_frame['breed'].map(self.map)\n        self.root_dir = root_dir\n        self.transform = transform\n        \n    def getmap(self):\n        return self.map\n        \n    def __getclasses__(self):\n        return self.labels_frame['breed'].unique().tolist()\n\n    def __len__(self):\n        return len(self.labels_frame)\n\n    def __getitem__(self, idx):\n        img_name = os.path.join(self.root_dir, self.labels_frame.iloc[idx, 0])\n        img_name = img_name + '.jpg'\n        \n        image = io.imread(img_name)\n        PIL_image = Image.fromarray(image)\n        label = self.labels_frame.iloc[idx, 1:]\n        label = int(label.iloc[0].item())\n        label = np.asarray(label)\n        label = torch.from_numpy(label).long()\n        if self.transform:\n            image = self.transform(PIL_image)\n        #sample = {'image': image, 'label': label}\n        return image,label\n    \ncsv='/kaggle/input/dog-breed-identification-data/labels.csv'\nroot='/kaggle/input/dog-breed-identification-data/train'\ntransformer=transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor()])\nalldata=DogBreedsDataset(csv_file=csv, root_dir=root, transform=transformer)\n#print(\"Nombre d'éléments dans le dataset :\", len(alldata))\n#print(\"Classes uniques :\",len(alldata.__getclasses__()))\n#print(\"Correspondance des classes :\", alldata.getmap())\n\n# Utilisez un DataLoader pour itérer sur le dataset\nbatch_size = 32\ndata_loader = DataLoader(alldata, batch_size=batch_size, shuffle=True)\n\n# Exemple d'itération sur le DataLoader\nfor batch in data_loader:\n    images, labels = batch\n    #Votre code pour traiter le batch ici\n    print(\"limage\",images[:2])\n    print(\"label\",len(labels),labels[:2])","metadata":{"execution":{"iopub.status.busy":"2024-02-04T11:45:43.808778Z","iopub.execute_input":"2024-02-04T11:45:43.809529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch.nn as nn\nimport torchvision.models as models\n\nclass CustomVGG16MultiClass(nn.Module):\n    def __init__(self, num_classes):\n        super(CustomVGG16MultiClass, self).__init__()\n        \n        # Chargement du modèle VGG16 pré-entraîné\n        vgg16 = models.vgg16(pretrained=True)\n        \n        # Utilisation des couches convolutives du modèle pré-entraîné\n        self.features = vgg16.features\n        # calculer le nombre de caracteristique au niveau de model vgg16\n        num_features = self._calculate_num_features(vgg16.features)\n        # Ajout de vos propres couches de classification pour la classification multiple\n        self.classifier = nn.Sequential(\n            nn.Linear(num_features, 4096),\n            nn.ReLU(True),\n            nn.Dropout(),\n            nn.Linear(4096, 4096),\n            nn.ReLU(True),\n            nn.Dropout(),\n            nn.Linear(4096, num_classes),  # Utilisez le nombre de classes spécifié\n           # nn.Softmax(dim=1)  # Utilisation de Softmax pour la classification multiple\n        )\n        \n    def _calculate_num_features(self, features):\n        # Fonction pour calculer le nombre d'entrées pour la couche entièrement connectée\n        x = torch.randn(1, 3, 224, 224)  # Taille d'image typique (3 canaux, 224x224)\n        x = features(x)\n        return x.view(x.size(0), -1).size(1)\n\n    def forward(self, x):\n        # Passage à travers les couches convolutives\n        x = self.features(x)\n        \n        # Aplatir les caractéristiques pour la classification\n        x = x.view(x.size(0), -1)\n        \n        # Passage à travers les couches de classification\n        x = self.classifier(x)\n        \n        return x\n\nnum_classes = 120  # Remplacez par le nombre réel de classes\nmodel = CustomVGG16MultiClass(num_classes)\nalldata = DogBreedsDataset(csv_file=csv, root_dir=root, transform=transformer)\n\nbatch_size = 2\nall_data_loader = DataLoader(alldata, batch_size=batch_size, shuffle=True)\n\nfor x, y in all_data_loader:\n    model(x)\n    break\nprint(\"model is ready\")","metadata":{"execution":{"iopub.status.busy":"2024-01-20T17:54:40.073049Z","iopub.execute_input":"2024-01-20T17:54:40.073551Z","iopub.status.idle":"2024-01-20T17:54:46.903603Z","shell.execute_reply.started":"2024-01-20T17:54:40.073512Z","shell.execute_reply":"2024-01-20T17:54:46.90251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\n\n# Vérifier si CUDA est disponible\nif torch.cuda.is_available():\n    # Afficher le nombre de GPU disponibles\n   \n    print(f\"Nombre de GPU disponibles : \")\nelse:\n    print(\"CUDA n'est pas disponible sur votre système.\")","metadata":{"execution":{"iopub.status.busy":"2024-01-20T17:55:29.121465Z","iopub.execute_input":"2024-01-20T17:55:29.122054Z","iopub.status.idle":"2024-01-20T17:55:29.129981Z","shell.execute_reply.started":"2024-01-20T17:55:29.122005Z","shell.execute_reply":"2024-01-20T17:55:29.128725Z"},"trusted":true},"execution_count":null,"outputs":[]}]}