biengsen4real commited on
Commit
347252f
·
verified ·
1 Parent(s): 20d10c7

Upload predict .ipynb

Browse files
Files changed (1) hide show
  1. predict .ipynb +146 -0
predict .ipynb ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": []
7
+ },
8
+ "kernelspec": {
9
+ "name": "python3",
10
+ "display_name": "Python 3"
11
+ },
12
+ "language_info": {
13
+ "name": "python"
14
+ }
15
+ },
16
+ "cells": [
17
+ {
18
+ "cell_type": "code",
19
+ "source": [
20
+ "import os\n",
21
+ "import torch\n",
22
+ "import pandas as pd\n",
23
+ "from torchvision import transforms\n",
24
+ "from transformers import ViTForImageClassification, ViTFeatureExtractor\n",
25
+ "from PIL import Image\n",
26
+ "\n",
27
+ "def load_model(model_path):\n",
28
+ " \"\"\"Load the pre-trained model.\"\"\"\n",
29
+ " model = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224', num_labels=13, ignore_mismatched_sizes=True)\n",
30
+ " model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')), strict=False)\n",
31
+ " model.eval()\n",
32
+ " return model\n",
33
+ "\n",
34
+ "def preprocess_image(image_path):\n",
35
+ " \"\"\"Preprocess the image for prediction.\"\"\"\n",
36
+ " feature_extractor = ViTFeatureExtractor.from_pretrained('google/vit-base-patch16-224')\n",
37
+ " image = Image.open(image_path).convert(\"RGB\")\n",
38
+ " image = feature_extractor(images=image, return_tensors=\"pt\")[\"pixel_values\"]\n",
39
+ " return image\n",
40
+ "\n",
41
+ "def predict(model, image_path):\n",
42
+ " \"\"\"Predict the class probabilities for an image.\"\"\"\n",
43
+ " image = preprocess_image(image_path)\n",
44
+ " with torch.no_grad():\n",
45
+ " outputs = model(image).logits\n",
46
+ " probabilities = torch.softmax(outputs, dim=1)\n",
47
+ " return probabilities\n",
48
+ "\n",
49
+ "def main(input_path, model_path, output_file):\n",
50
+ " \"\"\"Main function to predict and save results to Excel.\"\"\"\n",
51
+ " model = load_model(model_path)\n",
52
+ " results = []\n",
53
+ "\n",
54
+ " if os.path.isdir(input_path):\n",
55
+ " for img_name in os.listdir(input_path):\n",
56
+ " img_path = os.path.join(input_path, img_name)\n",
57
+ " if img_path.endswith(('.png', '.jpg', '.jpeg')): # Check for image file types\n",
58
+ " probs = predict(model, img_path).cpu().numpy()[0]\n",
59
+ " result = {\"Image Name\": img_name}\n",
60
+ " for i, prob in enumerate(probs):\n",
61
+ " result[f\"Class {i} Probability\"] = prob # Store probabilities\n",
62
+ " results.append(result)\n",
63
+ " else:\n",
64
+ " # If a single image file is provided\n",
65
+ " probs = predict(model, input_path).cpu().numpy()[0]\n",
66
+ " result = {\"Image Name\": os.path.basename(input_path)}\n",
67
+ " for i, prob in enumerate(probs):\n",
68
+ " result[f\"Class {i} Probability\"] = prob # Store probabilities\n",
69
+ " results.append(result)\n",
70
+ "\n",
71
+ " # Create DataFrame and save to Excel\n",
72
+ " df = pd.DataFrame(results)\n",
73
+ " df.to_excel(output_file, index=False)\n",
74
+ " print(f\"Results saved to {output_file}\")\n"
75
+ ],
76
+ "metadata": {
77
+ "id": "340nVjm4AcDO",
78
+ "colab": {
79
+ "base_uri": "https://localhost:8080/"
80
+ },
81
+ "outputId": "0bf9c9c0-a9cb-4fb9-ed4c-23c362546b9f"
82
+ },
83
+ "execution_count": 29,
84
+ "outputs": [
85
+ {
86
+ "output_type": "stream",
87
+ "name": "stderr",
88
+ "text": [
89
+ "Some weights of ViTForImageClassification were not initialized from the model checkpoint at google/vit-base-patch16-224 and are newly initialized because the shapes did not match:\n",
90
+ "- classifier.bias: found shape torch.Size([1000]) in the checkpoint and torch.Size([13]) in the model instantiated\n",
91
+ "- classifier.weight: found shape torch.Size([1000, 768]) in the checkpoint and torch.Size([13, 768]) in the model instantiated\n",
92
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
93
+ "<ipython-input-29-03634c1e367c>:11: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
94
+ " model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')), strict=False)\n"
95
+ ]
96
+ },
97
+ {
98
+ "output_type": "stream",
99
+ "name": "stdout",
100
+ "text": [
101
+ "Results saved to predictions.xlsx\n"
102
+ ]
103
+ }
104
+ ]
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "source": [
109
+ "# Example call\n",
110
+ "input_path = '/content/ddd.jpg' # Replace with your image folder or single image path\n",
111
+ "model_path = '/content/model.pth' # Replace with your model path\n",
112
+ "output_file = 'predictions.xlsx' # Name of the output Excel file\n",
113
+ "main(input_path, model_path, output_file)"
114
+ ],
115
+ "metadata": {
116
+ "id": "CY-fkhjdAeMM",
117
+ "colab": {
118
+ "base_uri": "https://localhost:8080/"
119
+ },
120
+ "outputId": "04e4352d-b889-437c-ae41-a4fa2b72ac56"
121
+ },
122
+ "execution_count": 30,
123
+ "outputs": [
124
+ {
125
+ "output_type": "stream",
126
+ "name": "stderr",
127
+ "text": [
128
+ "Some weights of ViTForImageClassification were not initialized from the model checkpoint at google/vit-base-patch16-224 and are newly initialized because the shapes did not match:\n",
129
+ "- classifier.bias: found shape torch.Size([1000]) in the checkpoint and torch.Size([13]) in the model instantiated\n",
130
+ "- classifier.weight: found shape torch.Size([1000, 768]) in the checkpoint and torch.Size([13, 768]) in the model instantiated\n",
131
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
132
+ "<ipython-input-29-03634c1e367c>:11: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
133
+ " model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')), strict=False)\n"
134
+ ]
135
+ },
136
+ {
137
+ "output_type": "stream",
138
+ "name": "stdout",
139
+ "text": [
140
+ "Results saved to predictions.xlsx\n"
141
+ ]
142
+ }
143
+ ]
144
+ }
145
+ ]
146
+ }