Update app.py
Browse files
app.py
CHANGED
@@ -1,34 +1,44 @@
|
|
1 |
import gradio as gr
|
2 |
import threading
|
|
|
3 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
|
4 |
from datasets import load_dataset
|
5 |
|
6 |
-
#
|
|
|
|
|
|
|
7 |
dataset = load_dataset("imdb")
|
8 |
|
|
|
|
|
|
|
9 |
# 모델과 토크나이저 로딩
|
10 |
model_name = "distilbert-base-uncased"
|
11 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
12 |
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
|
|
13 |
|
14 |
# 데이터셋을 모델에 맞게 전처리
|
15 |
def tokenize_function(examples):
|
16 |
-
return tokenizer(examples[
|
17 |
|
18 |
-
tokenized_train_datasets = dataset["train"].map(tokenize_function, batched=True)
|
19 |
-
tokenized_test_datasets = dataset["test"].map(tokenize_function, batched=True)
|
20 |
|
21 |
-
# 훈련 설정 (
|
22 |
training_args = TrainingArguments(
|
23 |
output_dir="./results", # 결과 저장 경로
|
24 |
num_train_epochs=1, # 훈련 에폭 수 1로 설정 (빠르게 테스트)
|
25 |
-
per_device_train_batch_size=
|
26 |
-
per_device_eval_batch_size=
|
27 |
evaluation_strategy="epoch", # 에폭마다 검증
|
|
|
28 |
logging_dir="./logs", # 로그 저장 경로
|
29 |
logging_steps=100, # 100 스텝마다 로그 출력
|
30 |
-
report_to="
|
31 |
load_best_model_at_end=True, # 최상의 모델로 종료
|
|
|
32 |
)
|
33 |
|
34 |
# 훈련 함수
|
@@ -46,25 +56,23 @@ def start_training():
|
|
46 |
train_thread = threading.Thread(target=train_model)
|
47 |
train_thread.start()
|
48 |
|
49 |
-
#
|
50 |
def classify_text(text):
|
51 |
-
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
|
52 |
-
|
|
|
53 |
logits = outputs.logits
|
54 |
predicted_class = logits.argmax(-1).item()
|
55 |
-
return predicted_class
|
56 |
|
57 |
# Gradio 인터페이스 설정
|
58 |
demo = gr.Interface(fn=classify_text, inputs="text", outputs="text")
|
59 |
|
60 |
# 훈련 시작과 Gradio UI 실행
|
61 |
def launch_app():
|
62 |
-
#
|
63 |
-
|
64 |
-
|
65 |
-
# Gradio 인터페이스 실행
|
66 |
-
demo.launch()
|
67 |
|
68 |
-
# 허깅페이스 Spaces에
|
69 |
if __name__ == "__main__":
|
70 |
launch_app()
|
|
|
1 |
import gradio as gr
|
2 |
import threading
|
3 |
+
import torch
|
4 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
|
5 |
from datasets import load_dataset
|
6 |
|
7 |
+
# GPU가 아닌 CPU에서 실행하도록 설정
|
8 |
+
device = torch.device("cpu")
|
9 |
+
|
10 |
+
# IMDb 데이터셋 로딩
|
11 |
dataset = load_dataset("imdb")
|
12 |
|
13 |
+
# 데이터셋의 텍스트 컬럼 자동 감지
|
14 |
+
text_column = dataset["train"].column_names[0] # 기본적으로 "text"일 가능성이 높음
|
15 |
+
|
16 |
# 모델과 토크나이저 로딩
|
17 |
model_name = "distilbert-base-uncased"
|
18 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
19 |
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
20 |
+
model.to(device) # 모델을 CPU로 이동
|
21 |
|
22 |
# 데이터셋을 모델에 맞게 전처리
|
23 |
def tokenize_function(examples):
|
24 |
+
return tokenizer(examples[text_column], padding="max_length", truncation=True)
|
25 |
|
26 |
+
tokenized_train_datasets = dataset["train"].map(tokenize_function, batched=True, batch_size=None, remove_columns=[text_column])
|
27 |
+
tokenized_test_datasets = dataset["test"].map(tokenize_function, batched=True, batch_size=None, remove_columns=[text_column])
|
28 |
|
29 |
+
# 훈련 설정 (GPU 사용 안 함)
|
30 |
training_args = TrainingArguments(
|
31 |
output_dir="./results", # 결과 저장 경로
|
32 |
num_train_epochs=1, # 훈련 에폭 수 1로 설정 (빠르게 테스트)
|
33 |
+
per_device_train_batch_size=4, # 배치 크기 줄이기 (CPU에서는 작은 값 추천)
|
34 |
+
per_device_eval_batch_size=4, # 배치 크기 줄이기
|
35 |
evaluation_strategy="epoch", # 에폭마다 검증
|
36 |
+
save_strategy="epoch",
|
37 |
logging_dir="./logs", # 로그 저장 경로
|
38 |
logging_steps=100, # 100 스텝마다 로그 출력
|
39 |
+
report_to="none", # 허깅페이스 업로드 시 로깅 비활성화
|
40 |
load_best_model_at_end=True, # 최상의 모델로 종료
|
41 |
+
no_cuda=True # ❌ GPU 사용하지 않도록 설정
|
42 |
)
|
43 |
|
44 |
# 훈련 함수
|
|
|
56 |
train_thread = threading.Thread(target=train_model)
|
57 |
train_thread.start()
|
58 |
|
59 |
+
# 텍스트 분류 함수 (CPU에서 실행)
|
60 |
def classify_text(text):
|
61 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True).to(device)
|
62 |
+
with torch.no_grad(): # 불필요한 연산 방지
|
63 |
+
outputs = model(**inputs)
|
64 |
logits = outputs.logits
|
65 |
predicted_class = logits.argmax(-1).item()
|
66 |
+
return str(predicted_class) # Gradio에서 문자열 반환이 더 안정적
|
67 |
|
68 |
# Gradio 인터페이스 설정
|
69 |
demo = gr.Interface(fn=classify_text, inputs="text", outputs="text")
|
70 |
|
71 |
# 훈련 시작과 Gradio UI 실행
|
72 |
def launch_app():
|
73 |
+
start_training() # 훈련 시작
|
74 |
+
demo.launch() # Gradio UI 실행
|
|
|
|
|
|
|
75 |
|
76 |
+
# 허깅페이스 Spaces에 업로드할 때 실행
|
77 |
if __name__ == "__main__":
|
78 |
launch_app()
|