---
tags: Admin, TA
---
# GAI 2024 Project1 Grading Policy (助教)
原作業規範:https://hackmd.io/IRtu9eKpRM2mvfj0abu3vg
## Numpy
### 練習 1:softmax (10)
在學生程式中加入 `np.random.seed(903)`
```
np.random.seed(903)
# 設定總共類別
c = 10
# 模擬輸出 logits
x = np.random.rand(c)
# 計算指數
x_exp = np.exp(x)
# 取得 softmax 分母
x_exp_sum = np.sum(x_exp)
# 定義機率值維度,儲存 softmax 結果
p = np.zeros_like(x)
# 對每個維度計算 softmax
for i in range(c):
p[i] = x_exp[i] / x_exp_sum
# 輸出 logits
print(x)
# 輸出經過 softmax 後的機率值
print(p)
```
**正確 output 為**
```
[0.66795894 0.79949537 0.04248317 0.38224843 0.86843254 0.29593196
0.04275267 0.21304653 0.72480104 0.13292176]
[0.12266666 0.13991108 0.0656275 0.09218156 0.14989637 0.0845585
0.06564519 0.07783243 0.12984127 0.07183943]
```
### 練習 2:Linear Layer + ReLU Activation (10)
**同樣在學生 code 前加入`np.random.seed(903)`**
```
np.random.seed(903)
# 設定輸入維度
d_in = 10
# 設定輸出維度
d_out = 30
# 模擬神經網路輸入
x = np.ones((d_in, 1))
# 模擬神經網路權重
W = np.random.rand(d_out, d_in) * 10 - 5
# 模擬神經網路偏差值
b = np.random.rand(d_out, 1) * 10 - 5
# TODO
h = W.dot(x) + b
# 計算 ReLU 得到神經網路輸出
y = h * (h > 0)
# 輸出神經網路輸入
print(x)
# 輸出神經網路輸出
print(y)
```
**正確 output 為**
```
[[1.]
[1.]
[1.]
[1.]
[1.]
[1.]
[1.]
[1.]
[1.]
[1.]]
[[-0. ]
[ 0.94999447]
[ 3.88704845]
[21.03030551]
[-0. ]
[12.85518268]
[ 5.17560451]
[-0. ]
[ 5.67361334]
[12.88152638]
[-0. ]
[-0. ]
[-0. ]
[-0. ]
[-0. ]
[10.2724664 ]
[ 1.02685378]
[-0. ]
[ 0.24543543]
[-0. ]
[-0. ]
[15.53112718]
[-0. ]
[ 6.77223105]
[-0. ]
[-0. ]
[-0. ]
[10.00265258]
[-0. ]
[ 9.19881995]]
```
## pandas
### 練習 1:數值轉換 (10)
資料即已放到雲端[台南站氣象觀測站(467410)資料集](https://drive.google.com/file/d/1Fp6Wp7Ut7SuXnRolt0S5uYqHFKohnP-v/view?usp=sharing),因為沒有要求要放資料所以有可能需要載來用,主要檢查紫外線強度每個等級的出現次數:
$$
低:0~2、中:3~5、高:6~7、甚高:8~10、極高:11+
$$
```
df = pd.read_csv('./467410-2022-08.csv', skiprows=1)
df['強度等級'] = ''
df.loc[(df['UVI Max'] <= 2) & (df['UVI Max'] >= 0), '強度等級'] = '低'
df.loc[(df['UVI Max'] <= 5) & (df['UVI Max'] >= 3), '強度等級'] = '中'
df.loc[(df['UVI Max'] <= 7) & (df['UVI Max'] >= 6), '強度等級'] = '高'
df.loc[(df['UVI Max'] <= 10) & (df['UVI Max'] >= 8), '強度等級'] = '甚高'
df.loc[(df['UVI Max'] >= 11), '強度等級'] = '極高'
#column_to_write = df['強度等級']
df.to_csv('467410.csv', index=False, encoding='utf-16')
# print(df)
counts = df['強度等級'].value_counts()
print(counts)
```
**主要檢查的次數結果**
```
強度等級
極高 24
甚高 4
高 2
中 1
```
### 練習 2:條件篩選 (10)
根據給定的降水量(mm)和降水時數(hour),計算出降水強度(mm/hr),並找出降水強度大於平均強度的日期及其相關資訊 (將整個 row print 出)。
```
import pandas as pd
import numpy as np
def print_rows_greater_than(df, column_name, threshold):
selected_rows = df[df[column_name] > threshold]
print(selected_rows['ObsTime'].values)
# for index, row in selected_rows.iterrows():
# print(row)
def convert_precp(value):
if value == 'T':
return 0.0
else:
return float(value)
df = pd.read_csv('./467410-2022-08.csv', skiprows=1, converters={'Precp': convert_precp, 'PrecpHour': float})
df['降水強度'] = df['Precp']/df['PrecpHour']
average_value = df['降水強度'].mean()
column_name = '降水強度'
print_rows_greater_than(df, column_name, average_value)
#print(df['降水強度'])
```
**主要檢查符合條件的天數是否吻合**
```
[ 2 7 9 10 15 16 17 18]
```
## matplotlib
此部份主要檢查圖是否符合即可
### 練習 1:折線圖 (10)
請依照日期畫出氣溫以及雨量的變化,並以折線圖的方式呈現。
```
import pandas as pd
import matplotlib.pyplot as plt
def convert_precp(value):
if value == 'T':
return 0.0
else:
return float(value)
# 讀取 CSV 檔案
df = pd.read_csv('./467410-2022-08.csv', skiprows=1, converters={'Precp': convert_precp, 'PrecpHour': float})
# 繪製折線圖
plt.figure(figsize=(10, 6)) # 設置圖表大小
plt.plot(df['ObsTime'], df['Temperature'], label='Temperature(C)', marker='o') # 繪製氣溫折線圖
plt.plot(df['ObsTime'], df['Precp'], label='Precp(mm)', marker='o') # 繪製雨量折線圖
# 添加標籤和標題
plt.xlabel('ObsTime')
plt.ylabel('Value')
plt.title('Temperature and Rainfall Variation')
plt.legend() # 顯示圖例
plt.grid(True) # 顯示網格
plt.xticks(rotation=45) # 旋轉 x 軸標籤,以避免重疊
# 顯示圖表
plt.tight_layout() # 調整布局,避免標籤被截斷
plt.show()
```
**主要檢查圖是不是長這樣就好**,有可能會有人兩張圖分開畫,那樣也算對


### 練習 2:雷達圖 (10)
分析風速和風向之間的關係,對於每個風向角度區間(0-90度、90-180度、180-270度、270-360度),計算相應的平均風速,並繪製成雷達圖以可視化四種風向的風速分佈情況。
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 讀取 CSV 檔案
df = pd.read_csv('./467410-2022-08.csv', skiprows=1)
# 將風向轉換為數值,例如 0 度表示北風,90 度表示東風,以此類推
# 假設風向存儲在 'WindDirection' 欄位中,風速存儲在 'WindSpeed' 欄位中
# 這裡的角度從 0 到 360 度
# 如果您的角度從 -180 到 180 度,請將角度調整為 0 到 360 度
# 將風向轉換為弧度
df['WindDirection_rad'] = np.deg2rad(df['WD'])
# 將風向角度劃分為四個區間:0-90度、90-180度、180-270度、270-360度
bins = [0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi]
labels = ['0-90 degrees', '90-180 degrees', '180-270 degrees', '270-360 degrees']
df['WindDirection_interval'] = pd.cut(df['WindDirection_rad'], bins=bins, labels=labels)
# 分別計算每個區間內的平均風速
avg_wind_speed = df.groupby('WindDirection_interval')['WS'].mean()
print(avg_wind_speed)
# (2.0 2.6 2.4222222222222225 2.4714285714285715)
# 繪製雷達圖
angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False).tolist()
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
ax.fill(angles, avg_wind_speed, color='blue', alpha=0.25)
ax.plot(angles, avg_wind_speed, color='blue', linewidth=2, linestyle='solid')
ax.set_yticklabels([]) # 隱藏半徑標籤
ax.set_theta_zero_location('N') # 將北方設置為起始位置
ax.set_theta_direction(-1) # 順時針方向
plt.title('Average Wind Speed by Wind Direction', size=20, color='blue')
plt.show()
```
**主要檢查是否與下列數值相同(圖相似即可)**
Actual avg wind_speed (>min & <=max) = [2.0 2.6 2.4222222222222225 2.4714285714285715]
Actual avg wind_speed (>=min & <max) = [2.0, 2.175, 2.66, 2.483333333333333]

## scikit-learn
1. <font color="blue">關使用 sklearn.model_selection.train_test_split 將 train.csv 分割,參數請設置成:train_size=0.8, random_state=1012,以分割後的 test_data 做最終預測結果的分析基準</font>
2. 分割後 test acc 預測原始分數為:<font color="red">0.7262</font>,請改進到超越此分數
未符合 1. 則直接在 rules 中扣除 20
### 練習 1:改善決策樹分類模型 [10pts]
檢查改進後 test acc 是否超過 0.762,未滿足則看完成度扣分
### 練習 2:使用不同的模型 [10pts]
檢查是否使用兩種以上模型,任一 test acc 是否超過 0.762,未滿足則看完成度扣分
## Report
- The way to improve [10pts]
說明對哪個部分進行改進,解釋方法與前後結果差異
- Different model comparison [10pts]
測試不同模型的訓練結果,至少兩種以上。