{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4" }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU", "widgets": { "application/vnd.jupyter.widget-state+json": { "a710457b00a849da9c24e1e1afb9d616": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_7b58972d4c704aa3bcc59a7a3c18682f", "IPY_MODEL_624e284bf09843a7a0b10256fbc416d0", "IPY_MODEL_e5b7191907914d75983b7e4b717b86d3" ], "layout": "IPY_MODEL_6434432da36a4755981ad001472e0cff" } }, "7b58972d4c704aa3bcc59a7a3c18682f": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_40a3244cfaa4404bb7ce4247564df6ed", "placeholder": "​", "style": "IPY_MODEL_234f2286e51c4a53b36584b49cd5a01f", "value": "Upload file Wheeloh-model_1.pth: 100%" } }, "624e284bf09843a7a0b10256fbc416d0": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_66ade188379547aaae0724b4e3d87051", "max": 44782274, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_4f8c9691cd1b4faab91f7fb34348b716", "value": 44782274 } }, "e5b7191907914d75983b7e4b717b86d3": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_7e6ba9a0ee6046b8961da2bf09d287ac", "placeholder": "​", "style": "IPY_MODEL_8ac32f54acd140b483ae523e22a9652b", "value": " 42.7M/42.7M [00:03<00:00, 25.0MB/s]" } }, "6434432da36a4755981ad001472e0cff": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "40a3244cfaa4404bb7ce4247564df6ed": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "234f2286e51c4a53b36584b49cd5a01f": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "66ade188379547aaae0724b4e3d87051": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "4f8c9691cd1b4faab91f7fb34348b716": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "7e6ba9a0ee6046b8961da2bf09d287ac": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "8ac32f54acd140b483ae523e22a9652b": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } } } } }, "cells": [ { "cell_type": "code", "source": [ "!pip install requests transformers" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "qgjLhqhtRoYL", "outputId": "6bb6ee0e-a189-4fe5-c2f9-7e043734db1e" }, "execution_count": 1, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (2.31.0)\n", "Requirement already satisfied: transformers in /usr/local/lib/python3.10/dist-packages (4.41.0)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests) (3.7)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests) (2.0.7)\n", "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests) (2024.2.2)\n", "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from transformers) (3.14.0)\n", "Requirement already satisfied: huggingface-hub<1.0,>=0.23.0 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.23.0)\n", "Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (1.25.2)\n", "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from transformers) (24.0)\n", "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (6.0.1)\n", "Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (2023.12.25)\n", "Requirement already satisfied: tokenizers<0.20,>=0.19 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.19.1)\n", "Requirement already satisfied: safetensors>=0.4.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.4.3)\n", "Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.10/dist-packages (from transformers) (4.66.4)\n", "Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub<1.0,>=0.23.0->transformers) (2023.6.0)\n", "Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub<1.0,>=0.23.0->transformers) (4.11.0)\n" ] } ] }, { "cell_type": "code", "source": [ "import requests\n", "import zipfile\n", "import os\n", "\n", "# URL du fichier zip sur Hugging Face\n", "zip_url = 'https://huggingface.co/datasets/Dabococo/wheeloh_dataset/images'\n", "\n", "# Nom local du fichier zip\n", "zip_file = 'images.zip'\n", "\n", "# Télécharger le fichier zip\n", "response = requests.get(zip_url)\n", "content_type = response.headers.get('Content-Type')\n", "\n", "# Vérifier que le fichier est un fichier zip\n", "if 'zip' not in content_type:\n", " raise ValueError(\"Le fichier téléchargé n'est pas un fichier zip. Content-Type: {}\".format(content_type))\n", "\n", "# Sauvegarder le contenu téléchargé dans un fichier\n", "with open(zip_file, 'wb') as f:\n", " f.write(response.content)\n", "\n", "# Vérifier la taille du fichier\n", "file_size = os.path.getsize(zip_file)\n", "print(\"Taille du fichier téléchargé:\", file_size, \"octets\")\n", "\n", "# Afficher le début du contenu du fichier pour vérifier\n", "with open(zip_file, 'rb') as f:\n", " print(f.read(100)) # Lire les 100 premiers octets\n", "\n", "# Créer un répertoire pour extraire les fichiers\n", "extract_dir = 'extracted_files'\n", "os.makedirs(extract_dir, exist_ok=True)\n", "\n", "# Extraire le contenu du fichier zip\n", "try:\n", " with zipfile.ZipFile(zip_file, 'r') as zip_ref:\n", " zip_ref.extractall(extract_dir)\n", " # Afficher les fichiers extraits\n", " extracted_files = os.listdir(extract_dir)\n", " print(\"Fichiers extraits :\", extracted_files)\n", "except zipfile.BadZipFile:\n", " print(\"Erreur : le fichier téléchargé n'est pas un fichier zip valide.\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 241 }, "id": "WX_U7Z6GRpTR", "outputId": "5efdb53c-196c-4692-91ff-e9c131fce1f4" }, "execution_count": 22, "outputs": [ { "output_type": "error", "ename": "ValueError", "evalue": "Le fichier téléchargé n'est pas un fichier zip. Content-Type: text/html; charset=utf-8", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[0;31m# Vérifier que le fichier est un fichier zip\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;34m'zip'\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcontent_type\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 17\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Le fichier téléchargé n'est pas un fichier zip. Content-Type: {}\"\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mformat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcontent_type\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 18\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 19\u001b[0m \u001b[0;31m# Sauvegarder le contenu téléchargé dans un fichier\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mValueError\u001b[0m: Le fichier téléchargé n'est pas un fichier zip. Content-Type: text/html; charset=utf-8" ] } ] }, { "cell_type": "code", "source": [ "from torchvision.datasets import ImageFolder\n", "import os\n", "from torchvision.datasets.folder import has_file_allowed_extension, IMG_EXTENSIONS, default_loader\n", "\n", "class CustomImageFolder(ImageFolder):\n", " def __init__(self, root, transform=None, loader=default_loader, is_valid_file=None):\n", " super().__init__(root, transform=transform, loader=loader, is_valid_file=is_valid_file)\n", "\n", " def find_classes(self, directory):\n", " # Ignorer les répertoires cachés\n", " classes = [d.name for d in os.scandir(directory) if d.is_dir() and not d.name.startswith('.')]\n", " classes.sort()\n", " class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}\n", " return classes, class_to_idx\n", "\n", " def make_dataset(self, directory, class_to_idx, extensions=None, is_valid_file=None, allow_empty=False):\n", " instances = []\n", " directory = os.path.expanduser(directory)\n", " both_none = extensions is None and is_valid_file is None\n", " if both_none:\n", " raise ValueError(\"Both extensions and is_valid_file cannot be None\")\n", " if extensions is not None:\n", " def is_valid_file(x):\n", " return has_file_allowed_extension(x, extensions)\n", "\n", " for target_class in sorted(class_to_idx.keys()):\n", " class_index = class_to_idx[target_class]\n", " target_dir = os.path.join(directory, target_class)\n", " if not os.path.isdir(target_dir):\n", " continue\n", " for root, _, fnames in sorted(os.walk(target_dir)):\n", " for fname in sorted(fnames):\n", " path = os.path.join(root, fname)\n", " if is_valid_file(path) and not fname.startswith('.'):\n", " item = path, class_index\n", " instances.append(item)\n", "\n", " if not allow_empty and len(instances) == 0:\n", " raise RuntimeError(f\"Found 0 files in subfolders of: {directory}. Supported extensions are: {','.join(extensions)}\")\n", "\n", " return instances" ], "metadata": { "id": "5y-PWXOnoH-k" }, "execution_count": 7, "outputs": [] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "CuyZBWiyP88V", "outputId": "fdef3381-9464-4433-c96d-2343bc22a1f6" }, "outputs": [ { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:08<00:00, 1.86it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [1/10], Loss: 0.2799\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:08<00:00, 1.96it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [2/10], Loss: 0.0916\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:07<00:00, 2.08it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [3/10], Loss: 0.0356\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:08<00:00, 1.86it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [4/10], Loss: 0.0253\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:07<00:00, 2.25it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [5/10], Loss: 0.0101\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:09<00:00, 1.73it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [6/10], Loss: 0.0089\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:08<00:00, 1.81it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [7/10], Loss: 0.0096\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:07<00:00, 2.23it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [8/10], Loss: 0.0101\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:08<00:00, 1.85it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [9/10], Loss: 0.0631\n" ] }, { "output_type": "stream", "name": "stderr", "text": [ "100%|██████████| 16/16 [00:07<00:00, 2.20it/s]\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "Epoch [10/10], Loss: 0.0186\n", "Finished Training\n" ] } ], "source": [ "import torch\n", "import torch.nn as nn\n", "import torch.optim as optim\n", "from torch.utils.data import DataLoader\n", "from torchvision import transforms, models\n", "from tqdm import tqdm\n", "\n", "# Configuration\n", "batch_size = 32\n", "num_epochs = 10\n", "learning_rate = 0.001\n", "num_classes = 2\n", "\n", "# Préparer les transformations\n", "transform = transforms.Compose([\n", " transforms.Resize((224, 224)),\n", " transforms.ToTensor(),\n", " transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n", "])\n", "\n", "# Charger les données d'entraînement avec CustomImageFolder\n", "train_dataset = CustomImageFolder(root='/content/dataset/train', transform=transform)\n", "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True)\n", "\n", "# Définir le modèle\n", "model = models.resnet18(pretrained=True)\n", "model.fc = nn.Linear(model.fc.in_features, num_classes)\n", "model = model.to('cuda')\n", "\n", "# Définir la perte et l'optimiseur\n", "criterion = nn.CrossEntropyLoss()\n", "optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n", "\n", "# Utiliser le scaler pour l'AMP\n", "scaler = torch.cuda.amp.GradScaler()\n", "\n", "# Entraînement\n", "for epoch in range(num_epochs):\n", " model.train()\n", " running_loss = 0.0\n", " for inputs, labels in tqdm(train_loader):\n", " inputs, labels = inputs.to('cuda'), labels.to('cuda')\n", "\n", " # Zero the parameter gradients\n", " optimizer.zero_grad()\n", "\n", " # Forward pass with autocast\n", " with torch.cuda.amp.autocast():\n", " outputs = model(inputs)\n", " loss = criterion(outputs, labels)\n", "\n", " # Backward pass with scaler\n", " scaler.scale(loss).backward()\n", " scaler.step(optimizer)\n", " scaler.update()\n", "\n", " running_loss += loss.item() * inputs.size(0)\n", "\n", " epoch_loss = running_loss / len(train_loader.dataset)\n", " print(f'Epoch [{epoch + 1}/{num_epochs}], Loss: {epoch_loss:.4f}')\n", "\n", "print('Finished Training')\n", "\n", "# Sauvegarder le modèle\n", "torch.save(model.state_dict(), 'model.pth')" ] }, { "cell_type": "code", "source": [ "#Ici pour charger le modèle" ], "metadata": { "id": "aJBYukdNfx8P" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "import torch\n", "import torch.nn as nn\n", "from torchvision import models, transforms\n", "from PIL import Image\n", "\n", "# Définir le modèle\n", "num_classes = 2 # Canard et Perroquet\n", "model = models.resnet18(pretrained=False)\n", "model.fc = nn.Linear(model.fc.in_features, num_classes)\n", "model = model.to('cuda')\n", "\n", "# Charger les poids du modèle enregistré\n", "model.load_state_dict(torch.load('model.pth'))\n", "model.eval() # Mettre le modèle en mode évaluation\n", "\n", "# Définir les transformations\n", "transform = transforms.Compose([\n", " transforms.Resize((224, 224)),\n", " transforms.ToTensor(),\n", " transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n", "])\n", "\n", "# Charger et transformer une nouvelle image\n", "def load_image(image_path):\n", " image = Image.open(image_path).convert('RGB')\n", " image = transform(image)\n", " image = image.unsqueeze(0) # Ajouter une dimension pour le batch\n", " return image\n", "\n", "# Exemple de chargement d'une image\n", "image_path = '/content/lg.jpeg'\n", "image = load_image(image_path).to('cuda')\n", "\n", "# Passer l'image dans le modèle pour obtenir des prédictions\n", "with torch.no_grad(): # Désactiver la grad pour l'inférence\n", " outputs = model(image)\n", " _, predicted = torch.max(outputs, 1)\n", "\n", " classes = ['Alpine', 'Bugatti']\n", " predicted_class = classes[predicted.item()]\n", " print(f'Predicted class: {predicted_class}')" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "oj0pgYdyQFXz", "outputId": "13c95418-6dcd-440c-cb78-2edbfdb8b386" }, "execution_count": 22, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Predicted class: Bugatti\n" ] } ] }, { "cell_type": "code", "source": [ "!pip install transformers huggingface_hub" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "cksp1PveZU22", "outputId": "eb8bdf38-4cc2-42ce-a047-d02b22c004bb" }, "execution_count": 23, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Requirement already satisfied: transformers in /usr/local/lib/python3.10/dist-packages (4.41.0)\n", "Requirement already satisfied: huggingface_hub in /usr/local/lib/python3.10/dist-packages (0.23.0)\n", "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from transformers) (3.14.0)\n", "Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (1.25.2)\n", "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from transformers) (24.0)\n", "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (6.0.1)\n", "Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (2023.12.25)\n", "Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from transformers) (2.31.0)\n", "Requirement already satisfied: tokenizers<0.20,>=0.19 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.19.1)\n", "Requirement already satisfied: safetensors>=0.4.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.4.3)\n", "Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.10/dist-packages (from transformers) (4.66.4)\n", "Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.10/dist-packages (from huggingface_hub) (2023.6.0)\n", "Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface_hub) (4.11.0)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->transformers) (3.3.2)\n", "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->transformers) (3.7)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->transformers) (2.0.7)\n", "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->transformers) (2024.2.2)\n" ] } ] }, { "cell_type": "code", "source": [ "!huggingface-cli login" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "c-3Qxby1ZWFV", "outputId": "66148da3-bf28-4fa4-baf6-0034b8b5b35e" }, "execution_count": 11, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "\n", " _| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|\n", " _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|\n", " _|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|\n", " _| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|\n", " _| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|\n", "\n", " To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .\n", "Enter your token (input will not be visible): \n", "Add token as git credential? (Y/n) Y\n", "Token is valid (permission: read).\n", "\u001b[1m\u001b[31mCannot authenticate through git-credential as no helper is defined on your machine.\n", "You might have to re-authenticate when pushing to the Hugging Face Hub.\n", "Run the following command in your terminal in case you want to set the 'store' credential helper as default.\n", "\n", "git config --global credential.helper store\n", "\n", "Read https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more details.\u001b[0m\n", "Token has not been saved to git credential helper.\n", "Your token has been saved to /root/.cache/huggingface/token\n", "Login successful\n" ] } ] }, { "cell_type": "code", "source": [ "from huggingface_hub import HfApi, HfFolder, Repository\n", "\n", "# Variables\n", "model_path = \"Wheeloh-model_1.pth\"\n", "repo_name = \"Wheeloh-model_1\" # Remplacez par le nom de votre dépôt\n", "commit_message = \"Initial commit\"\n", "\n", "# Se connecter à l'API\n", "api = HfApi()\n", "\n", "# Obtenir le token d'authentification\n", "token = HfFolder.get_token()\n", "\n", "# Cloner le dépôt Hugging Face\n", "repo_url = api.create_repo(repo_name, token=token, exist_ok=True)\n", "repo = Repository(local_dir=repo_name, clone_from=repo_url)\n", "\n", "# Copier le fichier du modèle dans le dépôt local\n", "import shutil\n", "shutil.copy(model_path, repo_name)\n", "\n", "# Pousser le modèle sur le hub\n", "repo.push_to_hub(commit_message=commit_message)\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 421, "referenced_widgets": [ "a710457b00a849da9c24e1e1afb9d616", "7b58972d4c704aa3bcc59a7a3c18682f", "624e284bf09843a7a0b10256fbc416d0", "e5b7191907914d75983b7e4b717b86d3", "6434432da36a4755981ad001472e0cff", "40a3244cfaa4404bb7ce4247564df6ed", "234f2286e51c4a53b36584b49cd5a01f", "66ade188379547aaae0724b4e3d87051", "4f8c9691cd1b4faab91f7fb34348b716", "7e6ba9a0ee6046b8961da2bf09d287ac", "8ac32f54acd140b483ae523e22a9652b" ] }, "id": "LDyh9-MfZiMX", "outputId": "e0e9ab72-d5df-4f21-eb3a-5226263071de" }, "execution_count": 25, "outputs": [ { "output_type": "stream", "name": "stderr", "text": [ "/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_token.py:89: UserWarning: \n", "The secret `HF_TOKEN` does not exist in your Colab secrets.\n", "To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.\n", "You will be able to reuse this secret in all of your notebooks.\n", "Please note that authentication is recommended but still optional to access public models or datasets.\n", " warnings.warn(\n", "/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_deprecation.py:131: FutureWarning: 'Repository' (from 'huggingface_hub.repository') is deprecated and will be removed from version '1.0'. Please prefer the http-based alternatives instead. Given its large adoption in legacy code, the complete removal is only planned on next major release.\n", "For more details, please read https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http.\n", " warnings.warn(warning_message, FutureWarning)\n", "Cloning https://huggingface.co/Dabococo/Wheeloh-model_1 into local empty directory.\n", "WARNING:huggingface_hub.repository:Cloning https://huggingface.co/Dabococo/Wheeloh-model_1 into local empty directory.\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "Upload file Wheeloh-model_1.pth: 0%| | 1.00/42.7M [00:00 main\n", "\n", "WARNING:huggingface_hub.repository:To https://huggingface.co/Dabococo/Wheeloh-model_1\n", " 09e573f..8606a55 main -> main\n", "\n" ] }, { "output_type": "execute_result", "data": { "text/plain": [ "'https://huggingface.co/Dabococo/Wheeloh-model_1/commit/8606a554a318e75a54b8b841b31825c29f577de8'" ], "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" } }, "metadata": {}, "execution_count": 25 } ] } ] }