Update tuner.py
Browse files
tuner.py
CHANGED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
from transformers import ViTForImageClassification, TrainingArguments, Trainer
|
5 |
+
from datasets import load_dataset
|
6 |
+
|
7 |
+
def finetune_model(epochs, save_at_num_epoch, learning_rate):
|
8 |
+
# Load the dataset
|
9 |
+
dataset = load_dataset("imagenet")
|
10 |
+
|
11 |
+
# Initialize the model
|
12 |
+
model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224")
|
13 |
+
|
14 |
+
# Define the training arguments
|
15 |
+
training_args = TrainingArguments(
|
16 |
+
output_dir="vit-finetuned",
|
17 |
+
num_train_epochs=epochs,
|
18 |
+
save_strategy="steps",
|
19 |
+
save_steps=save_at_num_epoch,
|
20 |
+
learning_rate=learning_rate,
|
21 |
+
)
|
22 |
+
|
23 |
+
# Create the trainer and fine-tune the model
|
24 |
+
trainer = Trainer(model=model, args=training_args, train_dataset=dataset["train"])
|
25 |
+
train_metrics = trainer.train()
|
26 |
+
|
27 |
+
# Save the fine-tuned model
|
28 |
+
model.save_pretrained("vit-finetuned")
|
29 |
+
|
30 |
+
# Plot the loss graph
|
31 |
+
plt.figure(figsize=(8, 6))
|
32 |
+
plt.plot(train_metrics.history["loss"])
|
33 |
+
plt.title("Model Loss")
|
34 |
+
plt.xlabel("Epoch")
|
35 |
+
plt.ylabel("Loss")
|
36 |
+
plt.savefig("loss_graph.png")
|
37 |
+
|
38 |
+
return "Fine-tuning complete!"
|
39 |
+
|
40 |
+
# Create the Gradio interface
|
41 |
+
with gr.Blocks() as demo:
|
42 |
+
gr.Markdown("# Fine-Tune a Model")
|
43 |
+
|
44 |
+
with gr.Column():
|
45 |
+
epochs = gr.Slider(label="Epochs", minimum=1, maximum=10, value=3)
|
46 |
+
save_at_num_epoch = gr.Slider(label="Save Model Every X Epochs", minimum=1, maximum=epochs, value=1)
|
47 |
+
learning_rate = gr.Slider(label="Learning Rate", minimum=1e-5, maximum=1e-3, value=2e-5)
|
48 |
+
run_button = gr.Button("Fine-Tune Model")
|
49 |
+
|
50 |
+
status = gr.Textbox(label="Fine-Tuning Status")
|
51 |
+
loss_graph = gr.Image(label="Loss Graph")
|
52 |
+
|
53 |
+
run_button.click(finetune_model, inputs=[epochs, save_at_num_epoch, learning_rate], outputs=[status, loss_graph])
|
54 |
+
|
55 |
+
if __name__ == "__main__":
|
56 |
+
demo.launch()
|