Johnson8187 commited on
Commit
0f958db
1 Parent(s): 174d920

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +34 -14
README.md CHANGED
@@ -40,12 +40,10 @@ pip install transformers torch
40
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
41
  import torch
42
 
43
- # 加載模型和分詞器
44
- model_name = "your_username/your_model_name"
45
- tokenizer = AutoTokenizer.from_pretrained(model_name)
46
- model = AutoModelForSequenceClassification.from_pretrained(model_name)
47
 
48
- # 標籤映射
49
  label_mapping = {
50
  0: "平淡語氣",
51
  1: "關切語調",
@@ -57,19 +55,41 @@ label_mapping = {
57
  7: "厭惡語調"
58
  }
59
 
60
- # 分析情感
61
- def predict_emotion(text):
62
- inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
 
 
 
 
 
 
63
  with torch.no_grad():
64
  outputs = model(**inputs)
 
 
65
  predicted_class = torch.argmax(outputs.logits).item()
66
- return label_mapping[predicted_class]
 
 
67
 
68
- # 測試
69
- text = "雖然我努力了很久,但似乎總是做不到,我感到自己一無是處。"
70
- emotion = predict_emotion(text)
71
- print(f"文本: {text}")
72
- print(f"預測情緒: {emotion}")
 
 
 
 
 
 
 
 
 
 
 
 
73
  ```
74
 
75
  ---
 
40
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
41
  import torch
42
 
43
+ # 添加設備設定
44
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
 
45
 
46
+ # 標籤映射字典
47
  label_mapping = {
48
  0: "平淡語氣",
49
  1: "關切語調",
 
55
  7: "厭惡語調"
56
  }
57
 
58
+ def predict_emotion(text, model_path="./fine_tuned_model"):
59
+ # 載入模型和分詞器
60
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
61
+ model = AutoModelForSequenceClassification.from_pretrained(model_path).to(device) # 移動模型到設備
62
+
63
+ # 將文本轉換為模型輸入格式
64
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True).to(device) # 移動輸入到設備
65
+
66
+ # 進行預測
67
  with torch.no_grad():
68
  outputs = model(**inputs)
69
+
70
+ # 取得預測結果
71
  predicted_class = torch.argmax(outputs.logits).item()
72
+ predicted_emotion = label_mapping[predicted_class]
73
+
74
+ return predicted_emotion
75
 
76
+ if __name__ == "__main__":
77
+ # 使用範例
78
+ test_texts = [
79
+ "雖然我努力了很久,但似乎總是做不到,我感到自己一無是處。",
80
+ "你說的那些話真的讓我很困惑,完全不知道該怎麼反應。",
81
+ "這世界真的是無情,為什麼每次都要給我這樣的考驗?",
82
+ "有時候,我只希望能有一點安靜,不要再聽到這些無聊的話題。",
83
+ "每次想起那段過去,我的心還是會痛,真的無法釋懷。",
84
+ "我從來沒有想過會有這麼大的改變,現在我覺得自己完全失控了。",
85
+ "我完全沒想到你會這麼做,這讓我驚訝到無法言喻。",
86
+ "我知道我應該更堅強,但有些時候,這種情緒真的讓我快要崩潰了。"
87
+ ]
88
+
89
+ for text in test_texts:
90
+ emotion = predict_emotion(text)
91
+ print(f"文本: {text}")
92
+ print(f"預測情緒: {emotion}\n")
93
  ```
94
 
95
  ---