Download RecommendationSystem/pre_train.py from Chamsol/pms_rec_sys: direct link, hf CLI and curl.
- Browser
- Download file 5.75 kB
-
https://huggingface.co/Chamsol/pms_rec_sys/resolve/main/RecommendationSystem/pre_train.py
- Command line
-
hf download hf://Chamsol/pms_rec_sys/RecommendationSystem/pre_train.py
-
curl -L -o pre_train.py https://huggingface.co/Chamsol/pms_rec_sys/resolve/main/RecommendationSystem/pre_train.py
5.75 kB
| #pre_train.py | |
| #ec2-train | |
| from transformers import AutoModelForSequenceClassification | |
| import torch | |
| from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments | |
| from torch.utils.data import Dataset, DataLoader | |
| import numpy as np | |
| import pandas as pd | |
| from transformers import 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 νμΌ λ‘λ | |
| import pandas as pd | |
| df = pd.read_csv('/home/ec2-user/train_org.csv') # 'your_dataset.csv'λ₯Ό μ€μ νμΌ κ²½λ‘λ‘ λ³κ²½νμΈμ. | |
| # λ°μ΄ν° μ μ²λ¦¬ | |
| texts = df['document'].tolist() # 리뷰 ν μ€νΈ | |
| labels = df['label'].tolist() # λΌλ²¨ λ°μ΄ν°λ μ μλ‘ λ³νλμ΄ μμ΄μΌ ν©λλ€.. | |
| labels = [int(label) for label in labels] # λΌλ²¨μ μ μνμΌλ‘ λ³ν | |
| texts = [str(text) for text in texts if text is not None] | |
| # ν ν¬λμ΄μ λ‘λ© | |
| 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 = "/home/ec2-user/roberta_model" | |
| # λ‘λν Electra λͺ¨λΈ κ²½λ‘ | |
| electra_model_path = "/home/ec2-user/electra_model" | |
| # μ μ₯λ λͺ¨λΈ λ‘λ | |
| model_roberta = AutoModelForSequenceClassification.from_pretrained(roberta_model_path) | |
| model_electra = AutoModelForSequenceClassification.from_pretrained(electra_model_path) | |
| # μ¬μ©μ μ§μ μ½λ°± ν΄λμ€ μ μ | |
| class PrintProgressCallback(TrainerCallback): | |
| def on_epoch_end(self, args, state, control, **kwargs): | |
| print(f"Epoch {state.epoch} μ’ λ£. μ§ν μν: {state.global_step}/{state.max_steps} ({(state.global_step/state.max_steps)*100:.2f}%)") | |
| if 'eval_metrics' in kwargs: | |
| print(f"Epoch {state.epoch} Accuracy: {kwargs['eval_metrics']['eval_accuracy']:.4f}") | |
| # μμμ μ μν compute_metrics ν¨μ μ¬μ© | |
| def compute_metrics(p: EvalPrediction): | |
| preds = np.argmax(p.predictions, axis=1) | |
| return {"accuracy": accuracy_score(p.label_ids, preds)} | |
| class CustomTrainer(Trainer): | |
| def __init__(self, label_weights, *args, **kwargs): | |
| super().__init__(*args, **kwargs) | |
| self.label_weights = label_weights | |
| def compute_loss(self, model, inputs, return_outputs=False): | |
| labels = inputs.get("labels") | |
| # λͺ¨λΈμ μΆλ ₯μμ λ‘μ€ κ³μ° | |
| outputs = model(**inputs) | |
| logits = outputs.get('logits') | |
| # κ°μ€μΉ μ μ©νμ¬ λ‘μ€ κ³μ° | |
| loss_fct = torch.nn.CrossEntropyLoss(weight=self.label_weights) | |
| loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1)) | |
| return (loss, outputs) if return_outputs else loss | |
| # def on_step_end(self, args, state, control, **kwargs): | |
| # super().on_step_end(args, state, control, **kwargs) | |
| # # λ§€ 1000 μ€ν λ§λ€ λͺ¨λΈ μ μ₯ | |
| # if state.global_step % 10 == 0: | |
| # output_dir1 = f"{args.output_dir1}/checkpoint-{state.global_step}" | |
| # self.save_model(output_dir1) | |
| # print(f"λͺ¨λΈμ {output_dir1}μ μ μ₯νμ΅λλ€.") | |
| # if state.global_step % 10 == 0: | |
| # output_dir2 = f"{args.output_dir2}/checkpoint-{state.global_step}" | |
| # self.save_model(output_dir2) | |
| # print(f"λͺ¨λΈμ {output_dir2}μ μ μ₯νμ΅λλ€.") | |
| # TrainingArguments μ€μ | |
| training_args = TrainingArguments( | |
| output_dir= './result', | |
| num_train_epochs=1, | |
| per_device_train_batch_size=32, | |
| warmup_steps=160000000, | |
| weight_decay=0.01, | |
| logging_dir='./logs', | |
| logging_steps=800, | |
| ) | |
| # λΌλ²¨ κ°μ€μΉ μ€μ | |
| # μμ: κ° λΌλ²¨μ λν κ°μ€μΉκ° λμΌνλ€κ³ κ°μ | |
| label_weights = torch.tensor([1.0, 1.0, 1.0, 1.0]).to(device) | |
| # CustomTrainer μΈμ€ν΄μ€ μμ± μ μ¬μ©μ μ§μ μ½λ°± μΆκ° | |
| trainer_roberta = CustomTrainer( | |
| model=model_roberta, | |
| args=training_args, | |
| train_dataset=dataset_roberta, | |
| label_weights=label_weights, | |
| compute_metrics=compute_metrics, | |
| callbacks=[PrintProgressCallback()], # μ½λ°± μΆκ° | |
| ) | |
| trainer_electra = CustomTrainer( | |
| model=model_electra, | |
| args=training_args, | |
| train_dataset=dataset_electra, | |
| label_weights=label_weights, | |
| compute_metrics=compute_metrics, | |
| callbacks=[PrintProgressCallback()], # μ½λ°± μΆκ° | |
| ) | |
| # νλ ¨ μμ | |
| trainer_roberta.train() | |
| trainer_electra.train() | |
| # νλ ¨λ RoBERTa λͺ¨λΈ μ μ₯ | |
| model_save_path = "/home/ec2-user/to/save/roberta_model" | |
| trainer_roberta.save_model(model_save_path) | |
| # νλ ¨λ Electra λͺ¨λΈ μ μ₯ | |
| model_save_path = "/home/ec2-user/to/save/electra_model" | |
| trainer_electra.save_model(model_save_path) |