File size: 2,638 Bytes
58f09d1 bbf9c8b a4fc148 58f09d1 a4fc148 58f09d1 a4fc148 bbf9c8b a4fc148 bbf9c8b a4fc148 bbf9c8b a4fc148 bbf9c8b a4fc148 bbf9c8b a4fc148 bbf9c8b a4fc148 bbf9c8b a4fc148 bbf9c8b a4fc148 bbf9c8b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import gradio as gr
import threading
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
# ๋ฐ์ดํฐ์
๋ก๋ฉ
dataset = load_dataset("imdb")
# ๋ชจ๋ธ๊ณผ ํ ํฌ๋์ด์ ๋ก๋ฉ
model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
# ๋ฐ์ดํฐ์
์ ๋ชจ๋ธ์ ๋ง๊ฒ ์ ์ฒ๋ฆฌ
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
tokenized_train_datasets = dataset["train"].map(tokenize_function, batched=True)
tokenized_test_datasets = dataset["test"].map(tokenize_function, batched=True)
# ํ๋ จ ์ค์ (๋น ๋ฅด๊ฒ ํ๋ จํ๊ธฐ ์ํด ์ํญ ์๋ฅผ ์ค์)
training_args = TrainingArguments(
output_dir="./results", # ๊ฒฐ๊ณผ ์ ์ฅ ๊ฒฝ๋ก
num_train_epochs=1, # ํ๋ จ ์ํญ ์ 1๋ก ์ค์ (๋น ๋ฅด๊ฒ ํ
์คํธ)
per_device_train_batch_size=16, # ๋ฐฐ์น ํฌ๊ธฐ ์ฆ๊ฐ
per_device_eval_batch_size=16, # ๋ฐฐ์น ํฌ๊ธฐ ์ฆ๊ฐ
evaluation_strategy="epoch", # ์ํญ๋ง๋ค ๊ฒ์ฆ
logging_dir="./logs", # ๋ก๊ทธ ์ ์ฅ ๊ฒฝ๋ก
logging_steps=100, # 100 ์คํ
๋ง๋ค ๋ก๊ทธ ์ถ๋ ฅ
report_to="tensorboard", # ํ
์๋ณด๋๋ก ๋ก๊ทธ ๋ณด๊ณ
load_best_model_at_end=True, # ์ต์์ ๋ชจ๋ธ๋ก ์ข
๋ฃ
)
# ํ๋ จ ํจ์
def train_model():
trainer = Trainer(
model=model, # ํ๋ จํ ๋ชจ๋ธ
args=training_args, # ํ๋ จ ์ธ์
train_dataset=tokenized_train_datasets, # ํ๋ จ ๋ฐ์ดํฐ์
eval_dataset=tokenized_test_datasets, # ํ๊ฐ ๋ฐ์ดํฐ์
)
trainer.train()
# ํ๋ จ์ ๋ณ๋์ ์ค๋ ๋์์ ์คํ
def start_training():
train_thread = threading.Thread(target=train_model)
train_thread.start()
# ๊ทธ๋ผ๋์ธํธ ๊ธฐ๋ฐ ํ๋ จ๋ ๋ชจ๋ธ์ UI์ ์ฐ๊ฒฐ
def classify_text(text):
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
outputs = model(**inputs)
logits = outputs.logits
predicted_class = logits.argmax(-1).item()
return predicted_class
# Gradio ์ธํฐํ์ด์ค ์ค์
demo = gr.Interface(fn=classify_text, inputs="text", outputs="text")
# ํ๋ จ ์์๊ณผ Gradio UI ์คํ
def launch_app():
# ํ๋ จ์ ์์
start_training()
# Gradio ์ธํฐํ์ด์ค ์คํ
demo.launch()
# ํ๊น
ํ์ด์ค Spaces์ ์
๋ก๋ ํ ๋๋ ์ด ๋ถ๋ถ์ ์คํํ๋๋ก ์ค์
if __name__ == "__main__":
launch_app()
|