Download RecommendationSystem/downstream_train.py from Chamsol/pms_rec_sys: direct link, hf CLI and curl.
- Browser
- Download file 6.5 kB
-
https://huggingface.co/Chamsol/pms_rec_sys/resolve/main/RecommendationSystem/downstream_train.py
- Command line
-
hf download hf://Chamsol/pms_rec_sys/RecommendationSystem/downstream_train.py
-
curl -L -o downstream_train.py https://huggingface.co/Chamsol/pms_rec_sys/resolve/main/RecommendationSystem/downstream_train.py
6.5 kB
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| from torch.utils.data import Dataset, DataLoader | |
| from transformers import ( | |
| AutoTokenizer, | |
| AutoModelForSequenceClassification, | |
| Trainer, | |
| TrainingArguments, | |
| EvalPrediction | |
| ) | |
| from sklearn.metrics import accuracy_score | |
| from transformers import TrainerCallback | |
| # GPU ์ฌ์ฉ ๊ฐ๋ฅ ํ์ธ ๋ฐ device ์ค์ | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # SentimentDataset ํด๋์ค ์ ์ | |
| class SentimentDataset(Dataset): | |
| def __init__(self, encodings, labels): | |
| self.encodings = encodings | |
| self.labels = labels | |
| def __getitem__(self, idx): | |
| item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} | |
| item['labels'] = torch.tensor(self.labels[idx]) | |
| return item | |
| def __len__(self): | |
| return len(self.labels) | |
| # CSV ํ์ผ ๋ก๋ | |
| df = pd.read_csv('path') # hr_data | |
| # ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ | |
| texts = df['person_corpus'].tolist() | |
| labels = df['label'].tolist() # ๋ผ๋ฒจ ๋ฐ์ดํฐ๋ ์ ์๋ก ๋ณํ๋์ด ์์ด์ผ ํฉ๋๋ค. | |
| # ํ ํฌ๋์ด์ ๋ก๋ฉ | |
| tokenizer_roberta = AutoTokenizer.from_pretrained("klue/roberta-large") | |
| tokenizer_electra = AutoTokenizer.from_pretrained("monologg/koelectra-base-v3-discriminator") | |
| # ๋ฐ์ดํฐ์ ํ ํฐํ | |
| encodings_roberta = tokenizer_roberta(texts, truncation=True, padding=True, max_length=128) | |
| encodings_electra = tokenizer_electra(texts, truncation=True, padding=True, max_length=128) | |
| # ๋ฐ์ดํฐ์ ์์ฑ | |
| dataset_roberta = SentimentDataset(encodings_roberta, labels) | |
| dataset_electra = SentimentDataset(encodings_electra, labels) | |
| # ๋ก๋ํ RoBERTa ๋ชจ๋ธ ๊ฒฝ๋ก | |
| roberta_model_path = "path" | |
| # ๋ก๋ํ Electra ๋ชจ๋ธ ๊ฒฝ๋ก | |
| electra_model_path = "path" | |
| # ์ ์ฅ๋ ๋ชจ๋ธ ๋ก๋ | |
| model_roberta = AutoModelForSequenceClassification.from_pretrained(roberta_model_path) | |
| model_electra = AutoModelForSequenceClassification.from_pretrained(electra_model_path) | |
| # CustomTrainer ํด๋์ค ์ ์ | |
| class CustomTrainer(Trainer): | |
| def __init__(self, *args, label_weights=None, **kwargs): | |
| super().__init__(*args, **kwargs) | |
| self.label_weights = label_weights if label_weights is not None else {} | |
| def compute_loss(self, model, inputs, return_outputs=False): | |
| outputs = model(**inputs) | |
| logits = outputs.get('logits') | |
| labels = inputs.get('labels') | |
| if self.label_weights: | |
| weight = torch.tensor([self.label_weights.get(label.item(), 1.0) for label in labels]).to(labels.device) | |
| loss_fct = CrossEntropyLoss(weight=weight) | |
| else: | |
| loss_fct = CrossEntropyLoss() | |
| loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1)) | |
| return (loss, outputs) if return_outputs else loss | |
| # TrainingArguments ์ค์ | |
| training_args = TrainingArguments( | |
| output_dir='./results', | |
| num_train_epochs=100, | |
| per_device_train_batch_size=16, | |
| warmup_steps=500, | |
| weight_decay=0.01, | |
| logging_dir='./logs', | |
| logging_steps=10, | |
| ) | |
| # ๋ผ๋ฒจ๋ณ ๊ฐ์ค์น ์ค์ | |
| label_weights = {0: 8.0, 1: 2.5, 2: 5.0, 3: 1.0} | |
| # CustomTrainer ์ธ์คํด์ค ์์ฑ | |
| trainer_roberta = CustomTrainer( | |
| model=model_roberta, | |
| args=training_args, | |
| train_dataset=dataset_roberta, # dataset_roberta๋ ์ฌ์ฉ์๊ฐ ์ ์ํด์ผ ํจ | |
| label_weights=label_weights, | |
| ) | |
| trainer_electra = CustomTrainer( | |
| model=model_electra, | |
| args=training_args, | |
| train_dataset=dataset_electra, # dataset_electra๋ ์ฌ์ฉ์๊ฐ ์ ์ํด์ผ ํจ | |
| label_weights=label_weights, | |
| ) | |
| # ๋ก์ง์ ํ๋ฅ ๋ก ๋ณํํ๋ ํจ์ | |
| def logits_to_probs(logits): | |
| return torch.softmax(logits, dim=1) | |
| def predict_with_ensemble_modified(texts, roberta_model, koelectra_model, tokenizer_roberta, tokenizer_koelectra, device): | |
| encodings_roberta = tokenizer_roberta(texts, truncation=True, padding=True, max_length=128) | |
| encodings_koelectra = tokenizer_koelectra(texts, truncation=True, padding=True, max_length=128) | |
| roberta_dataset = SentimentDataset(encodings_roberta, [0]*len(texts)) # ๋ผ๋ฒจ์ ์์ธก์ ์ํด ์ฌ์ฉ๋์ง ์์ผ๋ฏ๋ก ์์ ๊ฐ์ผ๋ก ์ค์ | |
| koelectra_dataset = SentimentDataset(encodings_koelectra, [0]*len(texts)) | |
| roberta_dataloader = DataLoader(roberta_dataset, batch_size=32, shuffle=False) | |
| koelectra_dataloader = DataLoader(koelectra_dataset, batch_size=32, shuffle=False) | |
| roberta_model.to(device) | |
| koelectra_model.to(device) | |
| roberta_model.eval() | |
| koelectra_model.eval() | |
| final_labels = [] # ์ต์ข ๋ผ๋ฒจ์ ์ ์ฅํ ๋ฆฌ์คํธ๋ฅผ ๋ฃจํ ์ธ๋ถ์์ ์ด๊ธฐํ | |
| with torch.no_grad(): | |
| for roberta_batch, koelectra_batch in zip(roberta_dataloader, koelectra_dataloader): | |
| roberta_input_ids, roberta_attention_mask = roberta_batch['input_ids'].to(device), roberta_batch['attention_mask'].to(device) | |
| koelectra_input_ids, koelectra_attention_mask = koelectra_batch['input_ids'].to(device), koelectra_batch['attention_mask'].to(device) | |
| roberta_outputs = roberta_model(roberta_input_ids, roberta_attention_mask) | |
| koelectra_outputs = koelectra_model(koelectra_input_ids, koelectra_attention_mask) | |
| roberta_probs = logits_to_probs(roberta_outputs.logits).cpu().numpy() | |
| koelectra_probs = logits_to_probs(koelectra_outputs.logits).cpu().numpy() | |
| ensemble_probs = (roberta_probs + koelectra_probs) / 2 | |
| for probs in ensemble_probs: | |
| pred_label = np.argmax(probs) | |
| if pred_label == 1 and probs[pred_label] > 0.6: # ๊ธ์ ์ด๋ฉด์ ํ๋ฅ ์ด 0.5 ์ด์์ธ ๊ฒฝ์ฐ | |
| pred_label = 3 # ๋งค์ฐ ๊ธ์ ์ผ๋ก ๋ณ๊ฒฝ | |
| elif pred_label == 0 and probs[pred_label] > 0.7: # ๋ถ์ ์ด๋ฉด์ ํ๋ฅ ์ด 0.5 ์ด์์ธ ๊ฒฝ์ฐ | |
| pred_label = 2 # ๋งค์ฐ ๋ถ์ ์ผ๋ก ๋ณ๊ฒฝ | |
| final_labels.append(pred_label) # ์์ ๋ ๋ผ๋ฒจ์ ์ต์ข ๋ผ๋ฒจ ๋ฆฌ์คํธ์ ์ถ๊ฐ | |
| return final_labels # ์์ : ์ต์ข ๋ผ๋ฒจ ๋ฆฌ์คํธ ๋ฐํ | |
| # ํจ์ ํธ์ถ์ device ๋ณ์ ์ฌ์ฉ | |
| final_labels = predict_with_ensemble_modified(texts, model_roberta, model_electra, tokenizer_roberta, tokenizer_electra, device) | |
| # ๊ฒฐ๊ณผ ์ถ๋ ฅ | |
| for text, label in zip(texts, final_labels): | |
| print(f"Text: {text} - Prediction: {label}") | |