# 機器學習
### Types of machine learning
#### learn under human supervision ?
:::spoiler Supervised learning 監督式學習
- 利用訓練**資料集**(已標記)建立一個模型,依照此模型推測新單體的答案
- 可以使用監督式學習技術來解決已知結果以及已標記資料的問題。
:::
:::spoiler Unsupervised learning 非監督式學習
- 自動對**沒有事先標記過**的資料集進行分類(classify)或分群(cluster)
- 對於未標記資料且目標是發現模式、將類似執行個體分組或偵測異常的場景,可以使用非監督式學習。
:::
:::spoiler Semi-supervised learning 半監督式學習
- 提供只有部分事先標記(labeled)的資料
- 利用沒有標記的資料改善類別(classes)間的界線(boundaries)
:::
:::spoiler Reinforcement learning 強化式學習
- 資料無法事先標記
- 只能在機器做出反應時給予處罰或獎勵來教機器,從嘗試錯誤中學習
:::
#### perform incremental learning from incoming data steams ? 能否從傳入的資料流進行增量學習
:::spoiler Batch learning 批次學習(離線學習)
- 所有訓練資料在模型訓練期間必須是可用的(available)
- 訓練完成後,模型才可以被使用
:::
:::spoiler Online learning 線上學習
- 即incremental learning (增量學習)
- 當一筆資料輸入,重新訓練並立即更新模型的權重(weights)
:::
### Neuron and Perceptron 神經元跟感知器
* perceptron learning algorithm
1. **initial values**: weights, bias, threshould
2. **calculate the output value**
3. **adjust weight**
4. **repeat 2. and 3.**

### Multi-Layer Perceptron (MLP) 多層感知網路
:::success
**前饋式網路(feedforward neural network)**
- 網路每層都可以包含許多各自獨立的神經元,同一層的神經元不互相連結
- 每層的神經元都會連接到下一層神經元(fully connected)
- [前饋神經網路與遞迴神經網路](https://baubimedi.medium.com/%E9%80%9F%E8%A8%98ai%E8%AA%B2%E7%A8%8B-%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92%E5%85%A5%E9%96%80-%E4%BA%8C-954b0e473d7f)
:::
:::info
**激活函數 Activation function**
- 一般是==非線性函數==(nonlinear function)
- 主要讓神經網路可以加入非線性的因素,讓神經網路可以解決更複雜的問題
:::
#### 常用的激活函數
:::spoiler Sigmoid

- 函數輸出介於0到1之間,適合用於輸出**機率**(probabilities)的模型
- 在使用反向傳播調整權重時,會有梯度消失的問題
- 特別不適用於有多層的網路模型(多層時梯度消失問題會更嚴重)
:::
:::spoiler tanh

- 值介於(-1,1)
- 主要用於分類工作
- 也有梯度消失的問題
:::
:::spoiler Rectified Linear Unit (ReLU)

- 當x小於0時,值設為0。當x大於0時,值設為x。
- 捕捉生物特性,刺激超過某個強度才會引發神經衝突。在實際應用上有效率
- 當x大於0時不會有梯度消失問題,但當x小於0時,權重無法再調整(Dead ReLU problem)
:::
:::spoiler Softmax

- 歸一化指數函數:每個元素取指數次方,加總放在分母,分子為每個元素指數次方,則每個元素對應的值都小於1,但所有元素對應的值加總會等於1
- 適合用於==多分類的機率模型==
:::
:::info
Loss Function 損失函數
- 用於計算**預測值**跟**實際值**之間的偏差
- 偏差越小表示模型越精準
:::
#### 常用的損失函數
* 預測結果是數值型的(從數值大小決定要用哪個)
:::spoiler Mean_squared_error

:::
:::spoiler Mean_absolute_error

:::
:::spoiler Mean_absolute_percentage_error

:::
:::spoiler Mean_squared_logarithmic_error

:::

- n代表有多少個分類
:::spoiler Binary_crossentropy
- 主要用於二分類
- 基本上會搭配 sigmoid activation function
- output 要經過 one-hot encoding
:::
:::spoiler Categorical_crossentropy
- 用於多分類
- 基本上會搭配 softmax activation function
- output 要經過 one-hot encoding
:::
:::success
- One-Hot Encoding:用N個bit表示狀態
example:
Binary Encoding:
000,001,010,011,100,101
One-Hot Encoding:
000001,000010,000100,001000,010000,100000
:::
### Strategies for adjusting MLP weights 多層感知網路調整權重的策略
* 神經網路的效率代表他的預測值準不準,由Loss function(L(w))計算
* 神經網路的目的主要就是調整這些權重值,使得他的預測所產生的誤差最小
#### 改進多層感知網路效率的方法
:::spoiler Backpropagation 反向傳播法
- 將神經網路中所有權重對損失函數進行梯度運算(Gradient)
- 做Gradient主要用來更新權重,使得損失函數值最小化

- learning rate 也可以做調整
- 影響梯度的因素:Activation Functions
- Problem 1:
- 一次用全部訓練集的資訊去計算損失函數的梯度才更新一次權重,收斂速度會很慢
- 解決方式:用**Stochastic Gradient Descent**來加速
- Problem 2:
- 梯度下降法無法保證能找到global optimal solution
- 為了避免困在local minimum,可以利用**Momentum**
:::
:::spoiler Stochastic Gradient Descent (SGD)隨機梯度下降法
- 用隨機逼近(stochastic approach)的梯度下降優化方法
- 一次只會跑一個樣本,就會算一次梯度並更新權重。樣本採隨機抽取
- 一次一次更新,時間還是太慢了
:::
:::spoiler Mini-Batch Gradient Descent 小批次梯度下降法
- 把訓練資料拆解成很多的小份資料,每次就有多筆資料進行訓練
- 好處:
- Compared with SGD:一個epoch的執行時間比較快
- Compared with GD:收斂(convergence)速度比較快
- batch size:不能太大,實務上大約設2的某個次方(32~2048)
:::
:::spoiler Momentum 動量法
- 梯度下降的一個變形
- 如果目前gradient的方向跟歷史更新權重(historical weight update)的方向一致,此gradient在這個方向就會被加強,反之則會減弱

:::
:::info
**Optimizer 優化器**
使用數值方法在continuous batch training中更新權重(weight)和偏差值(bias),使得損失函數的誤差值(error value)能夠最小
:::
#### 常用優化器:
:::spoiler SGD - Stochastic Gradient Descent
:::
:::spoiler AdaGrad - Adaptive Gradient Method
- 學習率(learning rate)不設置固定的值,因為迭代到最後時,值已經非常接近最佳解,調整只算微調
- 在迭代過程中,每次參數優化(parameter optimization)會使用不同學習率
:::
:::spoiler RMSprop - Root Mean Square Propagation
- 自適應(adaptive)學習率的一種方法
- 主要解決AdaGrad學習率急遽下降的問題
- 將gradient除以以往梯度的均方根來做比較,決定後面梯度的改變
- 目前公認最好的優化器之一
:::
:::spoiler Adam - Adaptive Moment Estimation
- 類似RMS Propagation加上Momentum
- 目前公認最好且最常用的優化器之一
:::
### Tensorflow
- 主要透過Computational Graphs來進行運算
- 所有運算都是基於張量(Tensor)來進行的,Tensor是單一資料型態的多維陣列
:::info
先import tensorflow
```python
import tensorflow as tf
tf.constant([1]) #產生一個tensor,裡面儲存常數1
tf.variable([1]) #變數
```
.ndim:查看維度
:::
#### Flow
- Tensorflow裡面的flow是一種資料流(運算)
- 透過得到資料流的圖(Data Flow Graphs)來進行運算,也就是Computation Graphs
- 計算圖的點代表數學運算,邊代表點跟點之間的關聯性
#### Session
- Session是圖和執行者之間的媒介,透過它可以啟動圖
- 主要負責執行圖的架構
- 在計算時分配資源(CPU, GPU)
- 像檔案總管一樣決定要開啟或是釋放資源(variables, queues, threads,...)
#### Eager Execution
- Dynamic Graph, Execution Mode
- 不需要再定義計算圖
- 不需要初始化的參數
- 不需要用Session.run()來執行,可直接啟動
- Tensor跟Numpy可以混用
#### Keras
- 快速建構Tensorflow的模型
- tf.keras就可以直接啟用
#### [Code](https://colab.research.google.com/drive/1zYG7I4Pcw_ijqxTc5Jsm62HKww0jN_9w?usp=sharing)
:::warning
colab印出圖要使用:
```python=
import IPython.display as display
display.Image(filename='Sequential_Model2.png')
#image = Image.open('Sequential_Model2.png')
#image.show() #會失敗!!
```
:::
### Classic Sample Dataset
* **MNIST Dataset**
- 手寫數字(0~9)數據庫
> Special Database 1:高中生手寫字
> Special Database 3:員工手寫字
- 下載:
1.yann.lecun
2.Kaggle
3.keras
```python=
import keras
from keras.datasets import mnist
```
* **CIFAR-10 Dataset**
- 60,000張32*32的RGB彩色小照片(10類)
- CIFAR-100有100類(20*5)
- 下載:
1.keras
```python=
from keras.datasets import cifar10
```
### Build MLP Model
#### Model Training
:::spoiler Basic Step
**1. Load Libraries (函式庫)**
```python=
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import RMSprop
```
**2. Prameter Configuration 參數設定**
```python=
batch_size = 128 #加速訓練過程(設太小會比較慢,但太快可能沒訓練好)
num_classes = 10 #有10類
epochs = 20 #訓練20趟(trained for 20 iterations)
```
**3. Data Loading and Preprocessing 資料讀取前處裡**
1. 從mnist裡面load資料
2. reshape成為一維資料
3. Normalize : 因像素值介於0到255,除以255使值介於0到1之間,加速
4. 利用to_categorical將一般數字轉換成one-hot encoding
**4. Build Model Architecture 建立模型架構**
- 用Sequential model建構框架
- 依序加入input layer, hidden layer(one fully connected layer), output layer
**5. Model Training 模型訓練**
- model.compile : 設定loss function和optimizer
- model.fit : 進行訓練
**6. Model Evaluation 模型評估**
- model.evaluate : 測試模型效率,會回傳Loss value跟accuracy(準確度)
**7. Model Saving 儲存**
- model.save_weights
:::
#### Sample prediction
:::spoiler Basic steps
**1. Load Libraries**
- 前面模型會用到的函式庫還是要事先import進來
**2. Build Model Architecture**
- 跟前面定義的一樣
**3. Load Model**
- model.load_weight
**4. Read sample**
- 讀取樣本
- tensorflow裡面都是用numpy array,所以要轉成numpy array來儲存
**5. Data Preprocessing**
- reshape, normalize(避免格式不同,造成預測結果不準)
**6. Sample prediction**
- model.predict 輸出各類別的機率
:::
### Model Evaluation Metrics 模型評估標準
:::info
**Confusion matrix 混淆矩陣**

- [機器學習-常見的評估指標](https://dysonma.github.io/2020/12/05/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E5%B8%B8%E8%A6%8B%E7%9A%84%E8%A9%95%E4%BC%B0%E6%8C%87%E6%A8%99/)
:::
:::spoiler Accuracy
- Accuracy = (TP + TF) / Total
- 可能造成一些誤導(unbalance data)。
- ex.罕見疾病全都說沒病,錯的就很少(可能只有1/1000000),造成Accuracy很高,但沒有預測正確
:::
:::spoiler Precision
- Precision = TP / (TP + FP)
:::
:::spoiler Recall
- 又Sensitivity(靈敏度)
- Recall = TP / (TP + FN)
:::
:::spoiler Specificity
- Specificity:特異度
- Specificity = TN / (FP + TN)
:::
:::spoiler F-measure
- F1 score
- F1 score = 2 / (1 / precision + 1 / recall)
- F-measure
- Fα = (1 + α^2) * precision * recall / (α^2 * (precision + recall))
:::
:::info
TPR & FPR
TPR = TP / (TP + FN)
FPR = FP / (FP + TN)
:::
:::spoiler ROC
- Receiver Operating Characteristic curve 受試者操作特徵曲線
- 表達不同模型真陽率對假陽率的函數關係
- 點座標(TPR,FPR)
:::
:::spoiler AUC
- Area Under the Curve = Area of ROC
- 面積越大代表分類越好
:::
### Image Convolution 影像捲積
:::info
* 也被稱作image filtering 影像濾波器
* 主要目的:強化影像中某些重要特徵,消除不想要的特徵
:::
:::spoiler Common convolution effects 常用卷積效果:
- Sharpen
- Blur
- Edge Detection
- Edge Enhancement
- Noice Removal
:::
#### Convolution Operation
:::info
**Convolution 卷積:**
A "filter" (or "kernal") refers to a fixed-size window, such as 3 * 3.
當這個filter在圖片中由左上到右下移動,針對每個pixel的鄰近區域做運算(entrywise product)。

:::
#### 常見Filters
:::spoiler **Smoothing Filter 平滑濾波器**
- 模糊化,去除雜訊
- Loss pass filter
- 消除影像高頻部分,使影像變均勻一點
- 消除高頻雜訊,使影像變比較平緩,一般可去除對比強烈的雜點
- 將所有neighboring pixels的灰階值加總起來,再以平均值取代該像素的灰階值
:::
:::spoiler **Sharpening Filter 邊緣銳化**
- 強化物件邊緣位置
- High pass filter
- 保持高頻部分,減少或消除低頻部分
- 原始影像減去loss-pass filter的影像
:::
:::spoiler **Sobel Filter**
- 邊緣偵測
- 有分垂直及水平


:::
:::spoiler **Laplacian Filter**
- 邊緣偵測
- 計算central pixel和neighboring pixels的差異,計算差異值的和,取代central pixel的值

:::
### Convolution Neural Network 卷積神經網路
:::info
減少影像複雜度:
- 只取重要特徵來做訓練
- 特徵由neighboring pixels組成
- 用convolution operation來萃取特徵
:::
- 由輸入層,一些隱藏層,及輸出層所組成
- 隱藏層與MLP差異:不是都是全連接層,裡面包含卷積層(convolution),池化層(pooling),激活層(activation),平坦層(flattening),及一些全連接層
#### Hyperparameters(超參數) for Convolutional Layers
:::spoiler Zero-padding
- 在做convolution時的問題:邊緣Pixel的neighboring pixels會超出圖片
- 解決方式:add extra zeros at the border of the image

:::
:::spoiler Stride
- 在做convolution時,filter對應的window一次要滑動多少格?
- reduce the output of convolution layer

:::
:::spoiler Depth
- 在做convolution時,要套幾個filter?
- 如果是RGB彩色的,不同的channel會套上不同的filter,最後再組合起來
:::
:::spoiler Pooling
- 影像太大,留下特徵值就好
- 好處:影像會變小,權重變少,訓練模型時Load會輕一點

:::
**Hyperparameter settings**
- 通常影響大小要能被2整除
- 常見影像:32, 64, 96, 224, 384, 512
- convolution layer filter跟stride的選擇
- filter size大部分是3 * 3(太大不一定能有好的作用)
- stride的選擇跟filter有關,通常不會超過filter的一半
- Very deep CNN model (16+ layers) 通常用3 * 3 filter 跟 stride 1
- Zero-padding 跟 Pooling layer 是選擇性的
- Pooling layer避免overfitting,降低weights的數量,減少影像包含的資訊,一般而言不會大於3 * 3
### Build CNN model
#### Model Training
:::spoiler Basic Step
**1. Load Libraries (函式庫)**
```python=
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.layers import Conv2D, MaxPooling2D
```
**2. Prameter Configuration 參數設定**
```python=
batch_size = 128 #加速訓練過程(設太小會比較慢,但太快可能沒訓練好)
num_classes = 10 #有10類
epochs = 20 #訓練20趟(trained for 20 iterations)
```
**3. Data Loading and Preprocessing 資料讀取前處裡**
1. 從mnist裡面load資料
2. reshape成為一維資料
3. Normalize : 因像素值介於0到255,除以255使值介於0到1之間,加速
4. 利用to_categorical將一般數字轉換成one-hot encoding
**4. Build Model Architecture 建立模型架構**
- 用Sequential model建構框架
- 依序加入convolutional layer, pooling layer, Flatten, fully connected layer, output layer
**5. Model Training 模型訓練**
- model.compile : 設定loss function和optimizer
- model.fit : 進行訓練
- verbose=1 : 顯示進度條(0不顯示)
- validation_split=0.2 : 訓練過程中拿20%當作validation
**6. Model Evaluation 模型評估**
- model.evaluate : 測試模型效率,會回傳Loss value跟accuracy(準確度)
**7. Model Saving 儲存**
- model.save_weights
:::
#### Sample prediction
:::spoiler Basic steps
**1. Load Libraries**
- 前面模型會用到的函式庫還是要事先import進來
**2. Build Model Architecture**
- 跟前面定義的一樣
**3. Load Model**
- model.load_weight
**4. Load sample**
- 讀取樣本
- 必須遵照訓練資料的格式,convert('L')把圖片轉成灰階,存在numpy.array
**5. Data Preprocessing**
- reshape, normalize(避免格式不同,造成預測結果不準)
**6. Sample prediction**
- model.predict 輸出各類別的機率
:::
### Classic CNN Models
:::spoiler LeNet(1998)
- 用於手寫數字和字母辨識
- 主要利用卷積層,池化層等操作提取特徵,再利用全連接層進行分類的訓練辨識
- the basisi of the latest deep neural network architecture
- Model Architecture

:::
:::spoiler AlexNet(2012)
- 使用非線性的activation function:ReLU(在AlexNet以前大部分使用tanh)
- 使用Data Augmentation和Dropout,防止overfitting
- 使用mini-batch SGD,加速
- Model Architecture:包含8個學習層,5個卷積層,3個全連接層

:::
:::spoiler VGGNet(2014)
- 包含5層卷積層,3層全連接層,softmax輸出層,層之間以MaxPooling分離。
- 使用的activation function:ReLU
- 卷積層使用multiple smaller convolution kernels(3 * 3)
- 減少參數
- 可以進行更多非線性映射,增加網路的fitting/expression adility
- 使用small pooling kernel(AlexNet用3 * 3,VGGNet用2 * 2)
- 通道數很多(第一層有64個,每層逐漸增加,直到最大512)
- 可以讓更多特徵被提取出來
:::
:::spoiler ResNet(2015)
- residual learning解決deep internet裡面梯度消失及精確度下降問題,讓神經網路能get deeper

:::
### Image Data Augmentation 影像資料擴增
**Data augmentation**
- rotation 旋轉
- shift 位移,左右移動
- zoom 放大縮小
- brightness 亮度
:::spoiler CNN model building process
**1. Data preprocessing**
- Data augmentation
- import package
```python=
from numpy import expand_dims
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import ImageDataGenerator
```
**2. Determine the model architecture and parameters**
**3. Compile and train the model**
**4. Model Evaluation**
**5. Hyperparameters tuning**
**6. Repeat steps 2~5 until the model efficiency can no longer be improved**
**7. Predictions**
:::
:::info
Compute class_weight 平衡資料不平衡的狀況
```python=
from sklearn.utils import class_weight
class_weight = class_weight.compute_class_weight('balanced',np.unique(y),y)
```
:::
- 資料量少:
1. Data Augmentation將資料增加
- image processing(rotation, shift, zoom,...):用原圖生成出來的,效果有限
- Generative Adversarial Networks(GAN):生成假照片。以假亂真
2. Segmentation : 從每個pixel判斷到底是不是
3. 用traditional machine learning algorithms(Random Forest, SVM,...)
- 資料量不平衡:
1. 用class weights:定權重
2. 將資料量變大或減小,讓不同類別的資料數量能夠平衡
### OpenCV (Open Source Computer Vision Library)
- Python program import package
```python=
import cv2
```
#### 常用指令:
:::spoiler Read image
```python=
cv2.imread([filename],[flag])
```
Prameter:
- filename:圖片檔案路徑 file path (資料型態:string)
- flag:讀取資料模式 reaging mode (資料型態:int)
- Return : image data (資料型態:numpy.array)
- Description:flag option
- cv2.IMREAD_GRAYSCALE:圖片轉成灰階
- cv2.IMREAD_COLOR:圖片是彩色的(Defult)
- cv2.IMREAD_UNCHANGED:不變
:::
:::spoiler Saving image
```python=
imwrite([filename],[image])
```
- Parameter:
- filename:儲存後檔名及路徑 saving filename path (資料型態:string)
- image:image data (資料型態:numpy.array)
- Return : 資料是否儲存成功(資料型態:boolen)
:::
:::spoiler Slicing image 切割影像
- Slice operate:use colons(:) for start, end, and step

```python=
import cv2
img=cv2.imread('lena.jpg')
crop=img[50:500,50:420,:] #xy座標,x座標從50到500之前,y同理
cv2.imwrite('lena.imwrite.jpg',crop)
```
:::
:::spoiler color converting 顏色轉換
```python=
cvtColor([image],[code])
```
- Parameter:
- image:image data(資料型態:numpy.array)
- code:converting format(資料型態:int)
- Return:轉換後image data(資料型態:numpy.array)
- Description:commomly used code options
- cv2.COLOR_BGR2GRAY
- cv2.COLOR_RGB2BGR
:::
:::spoiler Slicing channels
- Slice operate:use colons(:) for start, end, and step
```python=
import cv2
img=cv2.imread('lena.jpg')
img=img[:,:,0] #拿掉藍色通道
cv2.imwrite('lena_b.jpg',img)
img=img[:,:,2] #拿掉紅色通道(綠色通道為1)
cv2.imwrite('lena_r.jpg',img)
```
:::
:::spoiler Zoom out
```python=
cv2.resize([src],[size],[interpolation])
```
- Parameter:
- src:圖片資料(資料型態:numpy.array)
- size:新的圖片大小(資料型態:tuple)
- interpolation:放大方式(補畫質)(資料型態:int)
- Return:調整後image data (資料型態:numpy.array)
- Description:commomly used interpolation code options
- cv2.INTER_NEAREST
- cv2.INTER_LINEAR
- cv2.INTER_AREA
- cv2.INTER_CUBIC
- cv2.INTER_LANCZOS4
:::
### Classic Datasets for Data Analysis
:::spoiler Iris Dataset
- Iris Setosa, Iris Versicolor, Iris Virginica
- 四種特徵:花萼長度及寬度,花瓣長度及寬度
- 每種有50張
- [下載](https://www.kaggle.com/datasets/uciml/iris)
:::
:::spoiler Boston Housing
- 14種城鎮資料,總共506筆記錄
- [下載](https://www.kaggle.com/datasets/kyasar/boston-housing)
:::
:::spoiler Breast Cancer Wisconsin Dataset
- 包含569個samples,每筆資料有10種屬性,每個feature有三種data values:平均值,標準差,最差值,所以總共有30個features
- 資料及分為兩種類別:benign(良性的),malignant(惡性的)
- 資料不平均:benign有357筆, malignant有212筆
- [下載1](https://archive.ics.uci.edu/dataset/17/breast+cancer+wisconsin+diagnostic)
- [下載2](https://www.kaggle.com/datasets/uciml/breast-cancer-wisconsin-data)
```python=
from sklearn.datasets import load_breast_cancer
bunch = load_breast_cancer()
```
:::
### Data Preprocessing
:::spoiler Feature selection
- 評估feature的重要性
- 刪除較不重要的feature
- Pandas DataFrame's drop
```python=
import pandas as pd
df = pd.read_csv('data.csv')
df.drop(['id','name']) #將id及name的column刪除
```
:::
:::spoiler Dealing with missing data
- delete the feature
- 太多features遺失
- 用Pandas DataFrame刪除
- fill the gaps補資料
- 如果是ㄧ些類別就先通通補0,若為數值的資料型態先求其平均
- 用pandas Series median(), mean(), fillna()
```python=
mean = data['price'].mean() #裡面有值的取出來算平均值
data['price'] = data['price'].fillna(mean) #原本沒有值的全部填上平均值(mean)
```
:::
:::spoiler Convert data for non-numeric type
- 轉換成數值
- 地址:可以轉換成經緯度
- 文字:給編號,數字有大小關係,文字最好是有可比較性
- `data['level'] = data['level'].map({'normal':0,'mild':1, 'moderate':2, 'serve':3})`
- 類別型態的資料,沒有可比較性,轉換成one-hot encoding
:::
:::spoiler delete duplicate data
- 若不是augmentation的資料,重複的資料就要刪掉
- 用pandas DataFrame.drop_duplicates 來刪除資料
```python=
data = data.drop_duplicates(keep='first') #留下第一筆
```
:::
:::spoiler pick out the outliers 挑出離群點
- 用data visualization tools,視覺化較容易看出
:::
:::spoiler Dealing with imbalanced classes
- 導致overfitting
- 資料少的做duplicate或augmentation,資料多的做through out(挑出比較重要的)
- 用class_weight調整權重克服imbalance的狀況
```python=
from sklearn.utils import class_weight
import numpy as np
y = [1,1,1,1,0,0,1]
cw = class_weight.compute_class_weight('balanced'.np.unique(y),y)
print(cw)
```
```python=
[1.75 0.7] #0的權重被調整為1.75,1被調整為0.7
```
:::
:::spoiler Standardization 標準化
- z-score

- x:要被標準化的原始分數
- μ:population mean
- σ:population standard deviation()標準差
```python=
import pandas as pd
import numpy.random as rand
df = pd.DataFrame(rand.randiant(100,200,size=(5,3)),clumns = ['A','B','C'])
print(df)
df_zscore = (df-df.mean())/df.std()
print(df_zscore)
```
:::
:::spoiler Normalization
- 加速,把值壓縮到0~1之間,可以在模型訓練時更快調整權重
- size relationship : min-max normalization,把所有值都處理最大值
- 類別資料:one-hot encoding
:::
:::spoiler Training strategy
- Regression:直接預測值
- Classification:分類(多分類使用one-hot encoding,二分類不用特別轉換)
:::
### Feature selection 特徵選擇
:::spoiler RFE
- Recursive Feature Elimination
- 用base model。根據feature的數量,迭代feature的選擇。每輪訓練完後移除不重要的feature,繼續執行下一輪訓練,直到達到目標feature數量
- Implement
```python=
from sklearn.feature_selection import RFE
```
:::
:::spoiler Feature Selection-Filter
- 根據feature發散程度(變異數)以及feature跟target之間的相關性,對各個feature進行評分
- filter method
- 移除變異數較低的feature
- use sklearn variance Threshold package
- 單變量特徵選擇
- 個別計算每個feature的統計指標,根據這個指標判斷feature的重要性,去除不重要的feature
> 評分指標:
>- 分類問題(classification problem):
>f_classif(ANOVA F-value), mutual_info_classif and chi2(chi-square test)
>- regression problem:
>f_regression and mutual_info_regression
> sklearn method:
> - SelectKBest:用評分指標算出每個feature的得分,根據分數留下**前k名的feature**
> - SelectPercentile:用評分指標算出每個feature的得分,根據分數留**前下k%的feature**
:::