Views
No views yet
Trainer class from the Transformers library.
It shows that you can finetune the base model in any downstream task and make the model to acquire the ability to complete the task."İşaretle: *object_name*", "Tespit et: *object_name*".Transformers kütüphanesinden Trainer sınıfı kullanılarak ucsahin/TraVisionLM-base modelinin ince ayar yapılmış bir versiyonudur. Bu model, temel modeli herhangi bir alt görevde ince ayar yaparak, modele bu görevi tamamlama yeteneği kazandırabileceğinizi göstermektedir."İşaretle: *nesne_adı*", "Tespit et: *nesne_adı*".Transformers library:1from transformers import AutoModelForCausalLM, AutoProcessor
2import torch
3import requests
4from PIL import Image
5
6model = AutoModelForCausalLM.from_pretrained('ucsahin/TraVisionLM-Object-Detection-ft', trust_remote_code=True, device_map="cuda")
7# you can also load the model in bfloat16 or float16
8# model = AutoModelForCausalLM.from_pretrained('ucsahin/TraVisionLM-base', trust_remote_code=True, torch_dtype=torch.bfloat16, device_map="cuda")
9processor = AutoProcessor.from_pretrained('ucsahin/TraVisionLM-Object-Detection-ft', trust_remote_code=True)
10
11url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg"
12image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
13
14prompt = "İşaretle: araba"
15# prompt = "Tespit et: araba"
16
17inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
18
19outputs = model.generate(**inputs, max_new_tokens=512, do_sample=True, temperature=0.6, top_p=0.9, top_k=50, repetition_penalty=1.2)
20
21output_text = processor.batch_decode(outputs, skip_special_tokens=True)[0]
22
23print("Model response: ", output_text)
24"""
25Model response: İşaretle: araba
26<loc0048><loc0338><loc0912><loc0819> araba;
27""""<loc0000>, <loc0001>, ..., <loc1024>". The bounding box coordinates are in the form of special <loc[value]> tokens, where value is a number that represents a normalized coordinate. Each detection is represented by four location coordinates in the order x_min(left), y_min(top), x_max(right), y_max(bottom), followed by the label that was detected in that box. To convert values to coordinates, you first need to divide the numbers by 1024, then multiply y by the image height and x by its width. This will give you the coordinates of the bounding boxes, relative to the original image size."<loc0000>, <loc0001>, ..., <loc1024>". Sınırlayıcı kutu koordinatları, <loc[value]> şeklindeki özel tokenlar ile belirtilir ve bu tokenlardaki value değeri, normalize edilmiş bir koordinatı temsil eden bir sayıdır. Her bir tespit, sırasıyla x_min(sol), y_min(üst), x_max(sağ), y_max(alt) şeklinde dört konum koordinatı ile bu kutuda tespit edilen etiketle temsil edilir. Değerleri koordinatlara dönüştürmek için önce sayıları 1024’e bölmeniz, ardından y’yi görüntü yüksekliğiyle ve x’i genişliğiyle çarpmanız gerekir. Bu, sınırlayıcı kutuların orijinal görüntü boyutuna göre koordinatlarını verir.1import matplotlib.pyplot as plt
2import matplotlib.patches as patches
3import re
4
5plt.rcParams['font.family'] = 'DejaVu Sans'
6
7def plot_bbox(image, labels, bboxes):
8 # Create a figure and axes
9 fig, ax = plt.subplots()
10
11 # Display the image
12 ax.imshow(image)
13
14 # Plot each bounding box
15 for bbox, label in zip(bboxes, labels):
16 # Unpack the bounding box coordinates
17 x1, y1, x2, y2 = bbox
18 # Create a Rectangle patch
19 rect = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=1, edgecolor='r', facecolor='none')
20 # Add the rectangle to the Axes
21 ax.add_patch(rect)
22 # Annotate the label
23 plt.text(x1, y1, label, color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.5))
24
25 # Remove the axis ticks and labels
26 ax.axis('off')
27
28 # Show the plot
29 plt.show()
30
31def extract_loc_values_and_labels(bbox_str, width, height):
32 bbox_label_pairs = re.findall(r'((?:<loc\d+>){4})\s*([\w\s]+)', bbox_str)
33
34 bboxes = []
35 labels = []
36
37 for bbox, label in bbox_label_pairs:
38 loc_values = re.findall(r'<loc(\d+)>', bbox)
39 loc_values = [int(x) for x in loc_values]
40 loc_values = [value/1024 for value in loc_values]
41 # convert to PASCAL VOC format
42 loc_values = [
43 int(loc_values[0] * width), int(loc_values[1] * height),
44 int(loc_values[2] * width), int(loc_values[3] * height),
45 ]
46 bboxes.append(loc_values)
47 labels.append(label)
48
49 return bboxes, labels1bboxes, labels = extract_loc_values_and_labels(output_text, image.width, image.height)
2print("bboxes: ", bboxes)
3print("labels: ", labels)
4plot_bbox(image, labels, bboxes)
| Training Loss | Epoch | Step | Validation Loss |
|---|---|---|---|
| 2.3213 | 0.2406 | 570 | 2.3409 |
| 2.3129 | 0.4813 | 1140 | 2.3436 |
| 2.3128 | 0.7219 | 1710 | 2.3322 |
| 2.3082 | 0.9626 | 2280 | 2.3239 |
| 2.2853 | 1.2032 | 2850 | 2.3228 |
| 2.2826 | 1.4438 | 3420 | 2.3098 |
| 2.2707 | 1.6845 | 3990 | 2.3067 |
| 2.2706 | 1.9251 | 4560 | 2.3042 |
| 2.2465 | 2.1658 | 5130 | 2.3014 |
| 2.2435 | 2.4064 | 5700 | 2.2978 |
| 2.2433 | 2.6470 | 6270 | 2.2953 |
| 2.2344 | 2.8877 | 6840 | 2.2919 |