-
Notifications
You must be signed in to change notification settings - Fork 38
Description
-- coding: utf-8 --
作業主題:用 Softmax 模擬「飲料猶豫症」
飲料候選:
1. 珍煮丹|西瓜烏龍 (1分糖)
2. 屋弄|清茶 (無糖)
3. 八曜和茶|和茶307茶乳 (1分糖)
import numpy as np
import matplotlib.pyplot as plt
Step 1. 設定候選飲料與分數(logits)
drinks = ["珍煮丹|西瓜烏龍(1分糖)",
"屋弄|清茶(無糖)",
"八曜和茶|和茶307茶乳(1分糖)"]
logits = 偏好分數(可自己設定,數值差異才重要)
logits = np.array([1.2, 0.8, 1.0])
Step 2. 定義 Softmax 函數
def softmax(x, temperature=1.0):
"""計算 softmax 機率分布"""
x = x / temperature
exp_x = np.exp(x - np.max(x)) # 減掉 max 確保數值穩定
return exp_x / exp_x.sum()
Step 3. 計算某一個溫度下的機率
temperature = 1.0
probs = softmax(logits, temperature=temperature)
print("=== Softmax 計算結果(理論機率) ===")
for drink, p in zip(drinks, probs):
print(f"{drink}: {p*100:.2f}%")
Step 4. 模擬隨機點單(抽樣 N 次)
N = 1000
choices = np.random.choice(drinks, size=N, p=probs)
統計結果
unique, counts = np.unique(choices, return_counts=True)
sim_results = dict(zip(unique, counts))
print(f"\n=== 模擬 {N} 次點單結果 ===")
for drink in drinks:
c = sim_results.get(drink, 0)
print(f"{drink}: {c} 次({c/N*100:.2f}%)")
Step 5. 視覺化(模擬 vs 理論對照)
plt.figure(figsize=(8,5))
plt.bar(drinks, probs100, alpha=0.6, label="理論機率(%)")
plt.bar(drinks, [sim_results.get(d,0)/N100 for d in drinks],
alpha=0.6, label="模擬結果(%)")
plt.ylabel("百分比 %")
plt.title(f"Softmax 模擬 vs. 理論 (N={N}, τ={temperature})")
plt.legend()
plt.show()