Spaces:
Sleeping
Sleeping
File size: 5,759 Bytes
805c0cd 9d26c64 805c0cd 09f8eff 9d26c64 805c0cd 9d26c64 805c0cd 9d26c64 805c0cd 9d26c64 805c0cd 9d26c64 805c0cd 22b2ce1 |
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import gradio as gr
import pandas as pd
import io
from torch.utils.data import DataLoader, Dataset
from torch.optim import AdamW
from sklearn.model_selection import train_test_split
# ๋ชจ๋ธ๊ณผ ํ ํฌ๋์ด์ ๋ก๋
MODEL_NAME = "beomi/kcbert-base"
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=3) # 3๊ฐ ํด๋์ค๋ก ๋ณ๊ฒฝ
# ๋ฐ์ดํฐ์
ํด๋์ค ์ ์
class CustomDataset(Dataset):
def __init__(self, dataframe, tokenizer, max_len=128):
self.tokenizer = tokenizer
self.data = dataframe
self.max_len = max_len
def __len__(self):
return len(self.data)
def __getitem__(self, index):
item = self.data.iloc[index]
description = str(item['description'])
label = item['label']
encoding = self.tokenizer.encode_plus(
description,
add_special_tokens=True,
max_length=self.max_len,
return_token_type_ids=False,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='pt',
)
return {
'input_ids': encoding['input_ids'].flatten(),
'attention_mask': encoding['attention_mask'].flatten(),
'labels': torch.tensor(label, dtype=torch.long)
}
# ํ๋ จ ๋ฐ์ดํฐ ์ค๋น ๋ฐ ๋ชจ๋ธ ํ๋ จ
def train_model():
csv_data = """description,gender
"๊ทธ๋ ์ถ๊ตฌ๋ฅผ ์ ๋ง ์ข์ํ๊ณ , ๊ทผ์ก์ง์ ๋ชธ๋งค๋ฅผ ๊ฐ์ก๋ค.",๋จ์
"๊ทธ๋
๋ ๊ธด ๋จธ๋ฆฌ๋ฅผ ๊ฐ์ก๊ณ , ๋ถํ์ ์ํผ์ค๋ฅผ ์
์๋ค.",์ฌ์
"์งง์ ๋จธ๋ฆฌ์ ์ ์ฅ์ ์
์ ๊ทธ๋ ํ์์ ์ฐธ์ํ๋ค.",๋จ์
"์๋ฆ๋ค์ด ๋ชฉ์๋ฆฌ๋ก ๋
ธ๋ํ๋ ๊ทธ๋
๋ ๊ฐ์๋ค.",์ฌ์
"๊ทธ์ ์ทจ๋ฏธ๋ ์๋์ฐจ ์ ๋น์ ์ปดํจํฐ ๊ฒ์์ด๋ค.",๋จ์
"๊ทธ๋
๋ ์ฌ์ธํ ์๊ธธ๋ก ์๊ธฐ ์ธํ์ ๋ง๋ค์๋ค.",์ฌ์
"๊ตฐ๋์์ ๋ง ์ ๋ํ ๊ทธ๋ ์ฉ์ฉํด ๋ณด์๋ค.",๋จ์
"๊ทธ๋
๋ ์น๊ตฌ๋ค๊ณผ ์๋ค ๋ ๋ ๊ฒ์ ์ข์ํ๋ค.",์ฌ์
"๊ฐ๋ ฅํ ๋ฆฌ๋์ญ์ผ๋ก ํ์ ์ด๋๋ ๋ชจ์ต์ด ์ธ์์ ์ด์๋ค.",๋จ์
"์์ ์ด ์ง์ ๋ง๋ ์ฟ ํค๋ฅผ ์ฃผ๋ณ์ ๋๋์ด์ฃผ๊ณค ํ๋ค.",์ฌ์
"์ ๋ฏผ์ง",์ฒ์ฌ
"""
data = pd.read_csv(io.StringIO(csv_data))
# 3๊ฐ ํด๋์ค๋ก ๋ผ๋ฒจ ๋ณ๊ฒฝ: ๋จ์=0, ์ฌ์=1, ์ฒ์ฌ=2
data['label'] = data['gender'].apply(lambda x: 0 if x == '๋จ์' else (1 if x == '์ฌ์' else 2))
train_data, _ = train_test_split(data, test_size=0.2, random_state=42)
train_dataset = CustomDataset(train_data, tokenizer)
train_loader = DataLoader(train_dataset, batch_size=2)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
optimizer = AdamW(model.parameters(), lr=5e-5)
print("๋ชจ๋ธ ํ๋ จ ์์...")
model.train()
for epoch in range(3):
for batch in train_loader:
optimizer.zero_grad()
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
loss = outputs.loss
loss.backward()
optimizer.step()
print(f"Epoch {epoch + 1} ์๋ฃ")
print("๋ชจ๋ธ ํ๋ จ ์๋ฃ!")
# ์์ธก ํจ์
def predict_gender(text):
if not text.strip():
return "ํ
์คํธ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์."
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.eval()
encoding = tokenizer.encode_plus(
text,
add_special_tokens=True,
max_length=128,
return_token_type_ids=False,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='pt',
)
input_ids = encoding['input_ids'].to(device)
attention_mask = encoding['attention_mask'].to(device)
with torch.no_grad():
outputs = model(input_ids, attention_mask=attention_mask)
probabilities = torch.nn.functional.softmax(outputs.logits, dim=1)
prediction = torch.argmax(outputs.logits, dim=1).flatten().item()
confidence = probabilities[0][prediction].item()
# 3๊ฐ ํด๋์ค ๋งคํ: 0=๋จ์, 1=์ฌ์, 2=์ฒ์ฌ
gender_map = {0: "๋จ์", 1: "์ฌ์", 2: "์ฒ์ฌ"}
gender = gender_map[prediction]
return f"์์ธก ์ฑ๋ณ: {gender} (์ ๋ขฐ๋: {confidence:.2%})"
# ์ฑ ์์ ์ ๋ชจ๋ธ ํ๋ จ
print("์ฑ ์ด๊ธฐํ ์ค...")
train_model()
# Gradio ์ธํฐํ์ด์ค ์์ฑ
iface = gr.Interface(
fn=predict_gender,
inputs=gr.Textbox(
lines=3,
placeholder="์ฑ๋ณ์ ์์ธกํ ํ
์คํธ๋ฅผ ์
๋ ฅํ์ธ์.\n์: '๊ทธ๋ ์ถ๊ตฌ๋ฅผ ์ข์ํ๊ณ ๊ทผ์ก์ง์ด๋ค.'",
label="ํ
์คํธ ์
๋ ฅ"
),
outputs=gr.Textbox(label="์์ธก ๊ฒฐ๊ณผ"),
title="๐ค AI ์ฑ๋ณ ์์ธก๊ธฐ (3๋ถ๋ฅ)",
description="์
๋ ฅ๋ ํ
์คํธ๋ฅผ ๋ฐํ์ผ๋ก ์ฑ๋ณ์ ์์ธกํฉ๋๋ค. (๋จ์/์ฌ์/์ฒ์ฌ)",
examples=[
["๊ทธ๋ ์ถ๊ตฌ๋ฅผ ์ ๋ง ์ข์ํ๊ณ , ๊ทผ์ก์ง์ ๋ชธ๋งค๋ฅผ ๊ฐ์ก๋ค."],
["๊ทธ๋
๋ ๊ธด ๋จธ๋ฆฌ๋ฅผ ๊ฐ์ก๊ณ , ๋ถํ์ ์ํผ์ค๋ฅผ ์
์๋ค."],
["์งง์ ๋จธ๋ฆฌ์ ์ ์ฅ์ ์
์ ๊ทธ๋ ํ์์ ์ฐธ์ํ๋ค."],
["์๋ฆ๋ค์ด ๋ชฉ์๋ฆฌ๋ก ๋
ธ๋ํ๋ ๊ทธ๋
๋ ๊ฐ์๋ค."],
["๊ทธ๋ค์ ์ฑ
์ฝ๊ธฐ๋ฅผ ์ข์ํ๊ณ ์กฐ์ฉํ ์ฑ๊ฒฉ์ด๋ค."],
["์๋ฆฌ์ ์ฒญ์๋ฅผ ๋ชจ๋ ์ํ๋ฉฐ ์ง์์ผ์ ๋๋งก์ ํ๋ค."]
],
theme=gr.themes.Soft()
)
# ์ฑ ์คํ
if __name__ == "__main__":
iface.launch() |