Spaces:
Sleeping
Sleeping
Upload 5 files
Browse filesFiles changed (5)
- DistilBERT_Model_512.pthAdded+3
- app.pyAdded+119
- class_names.txtAdded+2
- model.pyAdded+73
- requirements.txtAdded+4
123version https://git-lfs.github.com/spec/v1oid sha256:f4af35b75cc722fbf36e99c3839472ae8cb1e3e889466ad6f79d9473b899cf68size 268647156123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119### 1. Imports and class names setup ###
import gradio as gr
import os
import torch
import transformers
from model import create_distilbert_model, tokenize_texts_and_labels
from transformers import DistilBertForSequenceClassification, DistilBertTokenizer
from typing import Tuple, Dict
from timeit import default_timer as timer
# Setup class names
with open("class_names.txt", "r") as f:
class_names = [label.strip() for label in f.readlines()] # ['Negative', 'Positive']
# 加載模型與 tokenizer
DistilBERT_Model, DistilBERT_Tokenizer = create_distilbert_model(num_classes=2, seed=42)
DistilBERT_Model.load_state_dict(
torch.load(
f=r"DistilBERT_Model_512.pth", # 路徑到保存的檔案
map_location=torch.device("cpu") # 加載到 CPU
)
)
# 設定設備
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
DistilBERT_Model.to(device)
# 預測函數
def predict(text: str) -> Tuple[Dict[str, float], float]:
"""
預測輸入文字的情感,返回預測的機率字典和耗時。
Args:
text (str): 要進行情感分析的文本
Returns:
Tuple[Dict[str, float], float]: 包含每個類別的機率字典和預測所需的時間
"""
# 計時開始
start_time = timer()
# 將文本轉為模型輸入格式
test_input = tokenize_texts_and_labels(
DistilBERT_Tokenizer,
[text], # 傳入單條文本,需封裝為列表
labels=None, # 測試時不需要標籤
max_length=512
)
# 移動輸入到設備(CPU/GPU)
inputs = {key: val.to(device) for key, val in test_input.items()}
# 模型推理
DistilBERT_Model.eval() # 設定模型為評估模式
with torch.no_grad(): # 禁用梯度計算以加速推理
outputs = DistilBERT_Model(**inputs)
logits = outputs.logits # 提取 logits
# 計算 softmax 機率
pred_probs = torch.softmax(logits, dim=1)
# 將機率與類別名稱對應
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
# 計算耗時
pred_time = round(timer() - start_time, 5)
return pred_labels_and_probs, pred_time
# Gradio predict function
def gradio_predict(text):
pred_labels_and_probs, pred_time = predict(text)
# Get highest probability label
predicted_label = max(pred_labels_and_probs, key=pred_labels_and_probs.get)
predicted_probability = pred_labels_and_probs[predicted_label]
# 給 Gradio 的輸出
# 第一個輸出:主要的情感標籤
sentiment_label = f"{predicted_label} ({predicted_probability:.2f})"
# 第二個輸出:詳細的預測數據
details = {
"Sentiment": predicted_label,
"Probability": f"{predicted_probability:.2f}",
"Prediction Time (s)": pred_time,
}
return sentiment_label, details # 確保返回兩個值
# Gradio Interface
title = "DistilBERT Sentiment Classifier 😃/😡"
description = (
"A sentiment analysis model powered by DistilBERT. "
"Enter a sentence and the model will classify it as Positive or Negative, "
"along with the prediction probability and time taken."
)
examples = [
["I love this movie!"],
["This product is terrible."],
["Amazing experience, would highly recommend!"],
["I hate waiting in line for hours."],
["The service was good, but the food was average."]
]
# Create Gradio interface
demo = gr.Interface(
fn=gradio_predict,
inputs=gr.Textbox(lines=3, placeholder="Type your sentence here..."),
outputs=[
gr.Label(label="Sentiment Prediction"), # 第一個輸出:情感標籤
gr.JSON(label="Details"), # 第二個輸出:詳細信息
],
examples=examples,
title=title,
description=description
)
# Launch the demo!
demo.launch(debug=False) 12negative
positive12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import torch
from torch import nn
import transformers
from transformers import DistilBertForSequenceClassification, DistilBertTokenizer
def create_distilbert_model(num_classes: int = 2, seed: int = 42):
"""
Creates a DistilBERT model for sentiment analysis with a customized classification head.
Args:
num_classes (int): Number of output classes.
seed (int): Random seed for reproducibility.
Returns:
model (torch.nn.Module): DistilBERT model with a custom classification head.
tokenizer (transformers.PreTrainedTokenizer): Tokenizer for text preprocessing.
"""
# Set random seed for reproducibility
torch.manual_seed(seed)
# Load pre-trained DistilBERT model
model = DistilBertForSequenceClassification.from_pretrained(
"distilbert-base-uncased",
num_labels=num_classes # Output layer matches the number of classes
)
# Freeze base model parameters (optional)
for param in model.distilbert.parameters():
param.requires_grad = False
# Customize the classification head
model.classifier = nn.Sequential(
nn.Dropout(p=0.5), # Add dropout to prevent overfitting
nn.Linear(768, 256), # Add a hidden layer (768 -> 256)
nn.ReLU(), # Non-linear activation function
nn.Dropout(p=0.3), # Add another dropout layer
nn.Linear(256, num_classes) # Output layer (256 -> num_classes)
)
# model.classifier = nn.Sequential(
# nn.Dropout(p=0.6),
# nn.Linear(768, 256),
# nn.ReLU(),
# nn.Dropout(p=0.4),
# nn.Linear(256, 2)
# )
# Load DistilBERT tokenizer
tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
return model, tokenizer
def tokenize_texts_and_labels(tokenizer, texts, labels=None, max_length=128):
"""
將文本數據進行分詞,並處理標籤(如果提供)。
Args:
tokenizer: 分詞器,用於將文本轉換為模型輸入格式。
texts (list[str]): 文本數據列表。
labels (list[int], optional): 標籤列表,可選。
max_length (int): 最大文本長度。
Returns:
dict: 包含分詞結果的字典,包括 input_ids、attention_mask 和 labels(如果提供)。
"""
encodings = tokenizer(
list(texts),
padding="max_length",
truncation=True,
max_length=max_length,
return_tensors="pt"
)
if labels is not None:
encodings["labels"] = torch.tensor(labels) # 將標籤轉為 PyTorch 張量
return encodings1234torch==2.5.1
torchvision==0.20.1
gradio==3.41.2
transformers==4.33.2DistilBERT_Model_512.pthAdded+3
app.pyAdded+119
class_names.txtAdded+2
model.pyAdded+73
requirements.txtAdded+4