md-vasim commited on
Commit
7e5b31a
1 Parent(s): 7cfb7cb

app is added

Browse files
.github/workflows/hfspace.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+ on:
3
+ push:
4
+ branches: [main]
5
+
6
+ # to run this workflow manually from the Actions tab
7
+ workflow_dispatch:
8
+
9
+ jobs:
10
+ sync-to-hub:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v3
14
+ with:
15
+ fetch-depth: 0
16
+ lfs: true
17
+ - name: Push to hub
18
+ env:
19
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
20
+ run: git push https://md-vasim:[email protected]/spaces/md-vasim/vit-image-classifier main
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gradio as gr
3
+ import torch
4
+ from transformers import AutoImageProcessor, ViTForImageClassification, AutoModelForImageClassification
5
+ from peft import PeftConfig, PeftModel
6
+ import os
7
+ from PIL import Image
8
+
9
+
10
+ ##### Loading Model #####
11
+ classes = ['chihuahua', 'newfoundland', 'english setter', 'Persian', 'yorkshire terrier', 'Maine Coon', 'boxer', 'leonberger', 'Birman', 'staffordshire bull terrier', 'Egyptian Mau', 'shiba inu', 'wheaten terrier', 'miniature pinscher', 'american pit bull terrier', 'Bombay', 'British Shorthair', 'german shorthaired', 'american bulldog', 'Abyssinian', 'great pyrenees', 'Siamese', 'Sphynx', 'english cocker spaniel', 'japanese chin', 'havanese', 'Russian Blue', 'saint bernard', 'samoyed', 'scottish terrier', 'keeshond', 'Bengal', 'Ragdoll', 'pomeranian', 'beagle', 'basset hound', 'pug']
12
+
13
+ label2id = {c:idx for idx,c in enumerate(classes)}
14
+ id2label = {idx:c for idx,c in enumerate(classes)}
15
+
16
+ model_name = "vit-base-patch16-224"
17
+ model_checkpoint = f"google/{model_name}"
18
+
19
+ repo_name = f"md-vasim/{model_name}-finetuned-lora-oxfordPets"
20
+
21
+ config = PeftConfig.from_pretrained(repo_name)
22
+ model = AutoModelForImageClassification.from_pretrained(
23
+ config.base_model_name_or_path,
24
+ label2id=label2id,
25
+ id2label=id2label,
26
+ ignore_mismatched_sizes=True, # provide this in case you're planning to fine-tune an already fine-tuned checkpoint
27
+ )
28
+ # Load the Lora model
29
+ inference_model = PeftModel.from_pretrained(model, repo_name)
30
+ image_processor = AutoImageProcessor.from_pretrained(model_checkpoint)
31
+
32
+ def inference(image):
33
+ encoding = image_processor(image.convert("RGB"), return_tensors="pt")
34
+ with torch.no_grad():
35
+ outputs = inference_model(**encoding)
36
+ logits = outputs.logits
37
+ predicted_class_idx = logits.argmax(-1).item()
38
+ result = inference_model.config.id2label[predicted_class_idx]
39
+ return result
40
+
41
+
42
+ ##### Interface #####
43
+
44
+ title = "Welcome to Vision Transformers Classification"
45
+
46
+ description = """
47
+ Vision Transformers (ViTs) are used in image classification tasks by breaking down an image into small patches, treating each patch like a token in a sequence. These tokens are then processed by the Transformer model, which uses self-attention to learn and capture the relationships between different parts of the image. This global understanding enables ViTs to classify images with high accuracy, making them effective for identifying objects, scenes, or patterns in various computer vision applications. ViTs are particularly powerful in scenarios requiring detailed and context-aware image analysis.
48
+ """
49
+
50
+ output_box = gr.Textbox(
51
+ label="Output"
52
+ )
53
+
54
+ examples=[
55
+ ["./static/shiba_inu_174.jpg"],
56
+ ["./static/pomeranian_89.jpg"],
57
+ ]
58
+
59
+ demo = gr.Interface(
60
+ inference,
61
+ gr.Image(type="pil"),
62
+ output_box,
63
+ examples=examples,
64
+ title=title,
65
+ description=description,
66
+ )
67
+
68
+ if __name__ == "__main__":
69
+ demo.launch()
notebooks/inference.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/interface.ipynb ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "name": "stderr",
10
+ "output_type": "stream",
11
+ "text": [
12
+ "/home/vasim/.local/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
13
+ " from .autonotebook import tqdm as notebook_tqdm\n"
14
+ ]
15
+ }
16
+ ],
17
+ "source": [
18
+ "import numpy as np\n",
19
+ "import gradio as gr\n",
20
+ "import torch\n",
21
+ "from transformers import AutoImageProcessor, ViTForImageClassification, AutoModelForImageClassification\n",
22
+ "from peft import PeftConfig, PeftModel\n",
23
+ "import os \n",
24
+ "from PIL import Image\n",
25
+ "import requests"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": 4,
31
+ "metadata": {},
32
+ "outputs": [
33
+ {
34
+ "name": "stderr",
35
+ "output_type": "stream",
36
+ "text": [
37
+ "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",
38
+ "- classifier.bias: found shape torch.Size([1000]) in the checkpoint and torch.Size([37]) in the model instantiated\n",
39
+ "- classifier.weight: found shape torch.Size([1000, 768]) in the checkpoint and torch.Size([37, 768]) in the model instantiated\n",
40
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
41
+ "Fast image processor class <class 'transformers.models.vit.image_processing_vit_fast.ViTImageProcessorFast'> is available for this model. Using slow image processor class. To use the fast image processor class set `use_fast=True`.\n"
42
+ ]
43
+ }
44
+ ],
45
+ "source": [
46
+ "classes = ['chihuahua', 'newfoundland', 'english setter', 'Persian', 'yorkshire terrier', 'Maine Coon', 'boxer', 'leonberger', 'Birman', 'staffordshire bull terrier', 'Egyptian Mau', 'shiba inu', 'wheaten terrier', 'miniature pinscher', 'american pit bull terrier', 'Bombay', 'British Shorthair', 'german shorthaired', 'american bulldog', 'Abyssinian', 'great pyrenees', 'Siamese', 'Sphynx', 'english cocker spaniel', 'japanese chin', 'havanese', 'Russian Blue', 'saint bernard', 'samoyed', 'scottish terrier', 'keeshond', 'Bengal', 'Ragdoll', 'pomeranian', 'beagle', 'basset hound', 'pug']\n",
47
+ "\n",
48
+ "label2id = {c:idx for idx,c in enumerate(classes)}\n",
49
+ "id2label = {idx:c for idx,c in enumerate(classes)}\n",
50
+ "\n",
51
+ "model_name = \"vit-base-patch16-224\"\n",
52
+ "model_checkpoint = f\"google/{model_name}\"\n",
53
+ "\n",
54
+ "repo_name = f\"md-vasim/{model_name}-finetuned-lora-oxfordPets\"\n",
55
+ "\n",
56
+ "config = PeftConfig.from_pretrained(repo_name)\n",
57
+ "model = AutoModelForImageClassification.from_pretrained(\n",
58
+ " config.base_model_name_or_path,\n",
59
+ " label2id=label2id,\n",
60
+ " id2label=id2label,\n",
61
+ " ignore_mismatched_sizes=True, # provide this in case you're planning to fine-tune an already fine-tuned checkpoint\n",
62
+ ")\n",
63
+ "# Load the Lora model\n",
64
+ "inference_model = PeftModel.from_pretrained(model, repo_name)\n",
65
+ "image_processor = AutoImageProcessor.from_pretrained(model_checkpoint)\n",
66
+ "\n",
67
+ "def inference(image):\n",
68
+ " encoding = image_processor(image.convert(\"RGB\"), return_tensors=\"pt\")\n",
69
+ " with torch.no_grad():\n",
70
+ " outputs = inference_model(**encoding)\n",
71
+ " logits = outputs.logits\n",
72
+ " predicted_class_idx = logits.argmax(-1).item()\n",
73
+ " result = inference_model.config.id2label[predicted_class_idx]\n",
74
+ " return result "
75
+ ]
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "execution_count": 5,
80
+ "metadata": {},
81
+ "outputs": [
82
+ {
83
+ "name": "stdout",
84
+ "output_type": "stream",
85
+ "text": [
86
+ "Running on local URL: http://127.0.0.1:7861\n",
87
+ "\n",
88
+ "To create a public link, set `share=True` in `launch()`.\n"
89
+ ]
90
+ },
91
+ {
92
+ "data": {
93
+ "text/html": [
94
+ "<div><iframe src=\"http://127.0.0.1:7861/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
95
+ ],
96
+ "text/plain": [
97
+ "<IPython.core.display.HTML object>"
98
+ ]
99
+ },
100
+ "metadata": {},
101
+ "output_type": "display_data"
102
+ }
103
+ ],
104
+ "source": [
105
+ "output_box = gr.Textbox(\n",
106
+ " label=\"Output\"\n",
107
+ " )\n",
108
+ "\n",
109
+ "examples=[\n",
110
+ " [\"../static/shiba_inu_174.jpg\"],\n",
111
+ " [\"../static/pomeranian_89.jpg\"],\n",
112
+ " ]\n",
113
+ "\n",
114
+ "demo = gr.Interface(inference, gr.Image(type=\"pil\"), output_box, examples=examples)\n",
115
+ "if __name__ == \"__main__\":\n",
116
+ " demo.launch()\n"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "execution_count": null,
122
+ "metadata": {},
123
+ "outputs": [],
124
+ "source": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "execution_count": null,
129
+ "metadata": {},
130
+ "outputs": [],
131
+ "source": []
132
+ }
133
+ ],
134
+ "metadata": {
135
+ "kernelspec": {
136
+ "display_name": "Python 3",
137
+ "language": "python",
138
+ "name": "python3"
139
+ },
140
+ "language_info": {
141
+ "codemirror_mode": {
142
+ "name": "ipython",
143
+ "version": 3
144
+ },
145
+ "file_extension": ".py",
146
+ "mimetype": "text/x-python",
147
+ "name": "python",
148
+ "nbconvert_exporter": "python",
149
+ "pygments_lexer": "ipython3",
150
+ "version": "3.10.12"
151
+ }
152
+ },
153
+ "nbformat": 4,
154
+ "nbformat_minor": 2
155
+ }
notebooks/model_card.md ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ language:
5
+ - en
6
+ metrics:
7
+ - accuracy
8
+ pipeline_tag: image-classification
9
+ ---
10
+
11
+ # Model Card for Model ID
12
+
13
+ <!-- Provide a quick summary of what the model is/does. -->
14
+
15
+
16
+
17
+ ## Model Details
18
+
19
+ ### Model Description
20
+
21
+ <!-- Provide a longer summary of what this model is. -->
22
+
23
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
24
+
25
+ - **Developed by:** [More Information Needed]
26
+ - **Funded by [optional]:** [More Information Needed]
27
+ - **Shared by [optional]:** [More Information Needed]
28
+ - **Model type:** [More Information Needed]
29
+ - **Language(s) (NLP):** [More Information Needed]
30
+ - **License:** [More Information Needed]
31
+ - **Finetuned from model [optional]:** [More Information Needed]
32
+
33
+ ### Model Sources [optional]
34
+
35
+ <!-- Provide the basic links for the model. -->
36
+
37
+ - **Repository:** [More Information Needed]
38
+ - **Paper [optional]:** [More Information Needed]
39
+ - **Demo [optional]:** [More Information Needed]
40
+
41
+ ## Uses
42
+
43
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
44
+
45
+ ### Direct Use
46
+
47
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
48
+
49
+ [More Information Needed]
50
+
51
+ ### Downstream Use [optional]
52
+
53
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
54
+
55
+ [More Information Needed]
56
+
57
+ ### Out-of-Scope Use
58
+
59
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
60
+
61
+ [More Information Needed]
62
+
63
+ ## Bias, Risks, and Limitations
64
+
65
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
66
+
67
+ [More Information Needed]
68
+
69
+ ### Recommendations
70
+
71
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
72
+
73
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
74
+
75
+ ## How to Get Started with the Model
76
+
77
+ Use the code below to get started with the model.
78
+
79
+ [More Information Needed]
80
+
81
+ ## Training Details
82
+
83
+ ### Training Data
84
+
85
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
86
+
87
+ [More Information Needed]
88
+
89
+ ### Training Procedure
90
+
91
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
92
+
93
+ #### Preprocessing [optional]
94
+
95
+ [More Information Needed]
96
+
97
+
98
+ #### Training Hyperparameters
99
+
100
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
101
+
102
+ #### Speeds, Sizes, Times [optional]
103
+
104
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
105
+
106
+ [More Information Needed]
107
+
108
+ ## Evaluation
109
+
110
+ <!-- This section describes the evaluation protocols and provides the results. -->
111
+
112
+ ### Testing Data, Factors & Metrics
113
+
114
+ #### Testing Data
115
+
116
+ <!-- This should link to a Dataset Card if possible. -->
117
+
118
+ [More Information Needed]
119
+
120
+ #### Factors
121
+
122
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
123
+
124
+ [More Information Needed]
125
+
126
+ #### Metrics
127
+
128
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
129
+
130
+ [More Information Needed]
131
+
132
+ ### Results
133
+
134
+ [More Information Needed]
135
+
136
+ #### Summary
137
+
138
+
139
+
140
+ ## Model Examination [optional]
141
+
142
+ <!-- Relevant interpretability work for the model goes here -->
143
+
144
+ [More Information Needed]
145
+
146
+ ## Environmental Impact
147
+
148
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
149
+
150
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
151
+
152
+ - **Hardware Type:** [More Information Needed]
153
+ - **Hours used:** [More Information Needed]
154
+ - **Cloud Provider:** [More Information Needed]
155
+ - **Compute Region:** [More Information Needed]
156
+ - **Carbon Emitted:** [More Information Needed]
157
+
158
+ ## Technical Specifications [optional]
159
+
160
+ ### Model Architecture and Objective
161
+
162
+ [More Information Needed]
163
+
164
+ ### Compute Infrastructure
165
+
166
+ [More Information Needed]
167
+
168
+ #### Hardware
169
+
170
+ [More Information Needed]
171
+
172
+ #### Software
173
+
174
+ [More Information Needed]
175
+
176
+ ## Citation [optional]
177
+
178
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
179
+
180
+ **BibTeX:**
181
+
182
+ [More Information Needed]
183
+
184
+ **APA:**
185
+
186
+ [More Information Needed]
187
+
188
+ ## Glossary [optional]
189
+
190
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
191
+
192
+ [More Information Needed]
193
+
194
+ ## More Information [optional]
195
+
196
+ [More Information Needed]
197
+
198
+ ## Model Card Authors [optional]
199
+
200
+ [More Information Needed]
201
+
202
+ ## Model Card Contact
203
+
204
+ [More Information Needed]
notebooks/trials.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
static/Abyssinian_1.jpg ADDED
static/Abyssinian_118.jpg ADDED
static/pomeranian_89.jpg ADDED
static/shiba_inu_136.jpg ADDED
static/shiba_inu_174.jpg ADDED