Views
No views yet
1import joblib;
2from huggingface_hub import hf_hub_download;
3from peft import PeftModel, PeftConfig;
4from transformers import AutoTokenizer, TextClassificationPipeline, AutoModelForSequenceClassification;
5from huggingface_hub import HfApi, login
6with open('./api_key/HGF_TOKEN.txt', 'r') as hgf:
7 login(token=hgf.read())
8api = HfApi()
9repo_id = "x2bee/plateer_classifier_v0.1"
10data_id = "x2bee/plateer_category_data"
11
12# Load Config, Tokenizer, Label_Encoder
13config = PeftConfig.from_pretrained(repo_id, subfolder="last-checkpoint")
14tokenizer = AutoTokenizer.from_pretrained(repo_id, subfolder="last-checkpoint")
15label_encoder_file = hf_hub_download(repo_id=data_id, repo_type="dataset", filename="label_encoder.joblib")
16label_encoder = joblib.load(label_encoder_file)
17
18# Load base_model
19base_model = AutoModelForSequenceClassification.from_pretrained("Qwen/Qwen2.5-1.5B", num_labels=17)
20base_model.resize_token_embeddings(len(tokenizer))
21
22# Load Model
23model = PeftModel.from_pretrained(base_model, repo_id, subfolder="last-checkpoint")
24
25import torch
26class TextClassificationPipeline(TextClassificationPipeline):
27 def __call__(self, inputs, top_k=5, **kwargs):
28 inputs = self.tokenizer(inputs, return_tensors="pt", truncation=True, padding=True, **kwargs)
29 inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
30
31 with torch.no_grad():
32 outputs = self.model(**inputs)
33
34 probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
35 scores, indices = torch.topk(probs, top_k, dim=-1)
36
37 results = []
38 for batch_idx in range(indices.shape[0]):
39 batch_results = []
40 for score, idx in zip(scores[batch_idx], indices[batch_idx]):
41 temp_list = []
42 label = self.model.config.id2label[idx.item()]
43 label = int(label.split("_")[1])
44 temp_list.append(label)
45 predicted_class = label_encoder.inverse_transform(temp_list)[0]
46
47 batch_results.append({
48 "label": label,
49 "label_decode": predicted_class,
50 "score": score.item(),
51 })
52 results.append(batch_results)
53
54 return results
55
56classifier_model = TextClassificationPipeline(tokenizer=tokenizer, model=model)
57
58def plateer_classifier(text, top_k=3):
59 result = classifier_model(text, top_k=top_k)
60 return result1user_input = "머리띠"
2result = plateer_classifier(user_input)[0]
3print(result)1{'label': 6, 'label_decode': '뷰티/케어', 'score': 0.42996299266815186}
2{'label': 15, 'label_decode': '패션/의류/잡화', 'score': 0.1485249102115631}
3{'label': 8, 'label_decode': '스포츠', 'score': 0.1281907707452774}| Training Loss | Epoch | Step | Validation Loss | Accuracy |
|---|---|---|---|---|
| 0.5023 | 0.0292 | 5000 | 0.5044 | 0.8572 |
| 0.4629 | 0.0585 | 10000 | 0.4571 | 0.8688 |
| 0.4254 | 0.0878 | 15000 | 0.4201 | 0.8770 |
| 0.4025 | 0.1171 | 20000 | 0.4016 | 0.8823 |
| 0.3635 | 0.3220 | 55000 | 0.3623 | 0.8905 |
| 0.3192 | 0.6441 | 110000 | 0.3242 | 0.8997 |