machine learning
|python
ctrl + i 可尋找方法或類別的相關資訊
養成習慣:
取得dataset後第一步:觀察並分析欄位、特徵
以下皆使用此表格作為範例
Country –> 只會有France、Spain、Germany,不會出現其他國家。屬於分類型欄位
Age、Salary –> 屬於連續型數值
Purchased –> 是否購買,用布林值表示
此表格可預測顧客是否購買產品
as 後面為別名
- numpy –> 提供矩陣數學運算方法
- matplotlib.pyplot –> 提供畫圖方法
長條圖、直線圖等
- pandas –> 提供讀取資料集的方法
通常為csv檔
選取資料集檔案路徑
透過pandas中的read_csv方法來讀取
python裡,字串用單引號或雙引號都可
:表示所有rows or columns
:-1 表示所有rows or columns但不包含最後一個row or column
缺點:
投入的成本會損失Image Not Showing Possible ReasonsLearn More →
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
10筆資料內,有2筆資料缺失,若刪除,相當於20%的資料被刪掉Image Not Showing Possible ReasonsLearn More →
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
- 使用scikit-learn (sklearn)
提供資料分析與資料處理的方法- 使用sklearn中的impute
提供估算的方法- 使用sklearn中的impute的SimpleImputer類別
提供missing data處理的方法
- 平均值(mean)或中位數(median) –> 連續型數值
- 最常出現的(most_frequent) –> 分類型欄位
- 常數(constant) –> fill_value要寫值多少
- 透過imputer.fit()進行資料擬合,並設定要進行缺失資料擬合的範圍
x[:, 1:3] –> x[all rows, 1 & 2 columns]
1:3表示索引值1到3,但不包含3(第2及第3行)
- 透過imputer.transform()進行資料轉換,並設定要進行缺失資料轉換的範圍
x[:, 1:3] –> x[all rows, 1 & 2 columns]
1:3表示索引值1到3,但不包含3(第2及第3行)- 將轉換的結果設定回原本的資料集合中
- 使用sklearn中的preprocessing
提供預處理的方法- 使用sklearn中的preprocessing的LabelEncoder類別
提供標籤編碼處理的方法
- 宣告LabelEncoder物件
針對Country進行標籤編碼(Country為input –> )
- 使用LabelEncoder中的fit_transform()進行資料擬合與轉換,並設定範圍
x[:, 0] –> x[all rows, 0 column]- 將轉換的結果設定回原本的資料集合中
- 應變量能夠自動被識別為類別,所以不需要做虛擬編碼,直接使用LabelEncoder即可
- 使用LabelEncoder中的fit_transform()進行資料擬合與轉換
標籤編碼後有順序之分,此例的Country被分成三類,延展成三行
- 使用sklearn中的preprocessing的OneHotEncoder類別
提供虛擬編碼處理的方法
- 使用sklearn中的compose
提供編寫的方法
- 參數設定為須處理虛擬編碼的欄位
[0] –> 索引值為0的行 –> Country- remainder:其他未指定的欄位要如何處理
remainder = "passthrough" –> 剩餘欄位不會被轉換
- 使用ColumnTransformer中的fit_transform()進行資料擬合與轉換,並且轉換為array()
- 使用sklearn中的model_selection的train_test_split類別
提供分割訓練集合與測試集合的方法
- 若給一個array[x],train_test_split會回傳兩組array,分別是測試集合與訓練集合
- test_size = 0.2 –> 測試集合為20%
- random_state = 0 –> 取值不變時,每次得到的結果一樣;取值改變時,每次得到的結果不同;不設定參數時,會隨機選擇樣本,得到的结果也就不同
以此例來說,Age和Salary的範圍不同(Age落在0-100左右,Salary以萬起跳),若方程式為,Age會小到可以被忽略
缺點:丟棄特徵 –> 損失成本
不論範圍如何,為求模型更客觀,都會做特徵縮放
:標準差
:平均值
數值落在0~1之間
- 使用sklearn中的preprocessing的StandardScaler類別
提供標準化的方法
- 宣告StandardScaler()物件
針對自變量進行- 使用StandardScaler()中的fit_transform()對x_train進行資料擬合與轉換
- 因為sc_x已經被擬合過,故第3行的sc_x不需要再用fit_transform(),可直接使用transform()
- 應變量是用來分辨的(是否購買),故維持分類編碼(0、1)
機器學習-作業1
機器學習-作業3