背景:
在拿到的數據里,經常有分類型變量的存在,如下:
球鞋品牌:Nike、adidas、 Vans、PUMA、CONVERSE
性別:男、女
顏色:紅、黃、藍、綠
However,sklearn大佬不能直接分析這類變量呀。在回歸,分類,聚類等機器學習算法中,特征之間距離的計算或相似度的計算是算法關鍵部分,而常用的距離或相似度的計算都是在歐式空間的相似度計算,計算余弦相似性,基於的就是歐式空間。於是,我們要對這些分類變量進行啞變量處理,又或者叫虛擬變量。
缺點:
當類別的數量很多時,特征空間會變得非常大。在這種情況下,一般可以用PCA來減少維度。而且one hot encoding+PCA這種組合在實際中也非常有用。有些基於樹的算法在處理變量時,並不是基於向量空間度量,數值只是個類別符號,即沒有偏序關系,所以不用進行獨熱編碼。Tree Model不太需要one-hot編碼: 對於決策樹來說,one-hot的本質是增加樹的深度。
In summary,
要是one hot encoding的類別數目不太多,可優先考慮。
一.pd.get_dummies()簡單&粗暴
pandas.get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None)
官網文檔:
http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html
輸入:array-like, Series, or DataFrame
輸出:DataFrame
主要參數說明:
data : array-like, Series, or DataFrame
prefix : 給輸出的列添加前綴,如prefix="A",輸出的列會顯示類似
prefix_sep : 設置前綴跟分類的分隔符sepration,默認是下划線"_"
一般,我們輸入data就夠了。如果要專門關注Nan這類東東,可設置dummy_na=True,專門生成一列數據。
見下面的栗子:(簡直不要太容易)
import numpy as np
import pandas as pd
data = pd.DataFrame({"學號":[1001,1002,1003,1004],
"性別":["男","女","女","男"],
"學歷":["本科","碩士","專科","本科"]})
data
學歷 | 學號 | 性別 | |
---|---|---|---|
0 | 本科 | 1001 | 男 |
1 | 碩士 | 1002 | 女 |
2 | 專科 | 1003 | 女 |
3 | 本科 | 1004 | 男 |
pd.get_dummies(data)
學號 | 學歷_專科 | 學歷_本科 | 學歷_碩士 | 性別_女 | 性別_男 | |
---|---|---|---|---|---|---|
0 | 1001 | 0 | 1 | 0 | 0 | 1 |
1 | 1002 | 0 | 0 | 1 | 1 | 0 |
2 | 1003 | 1 | 0 | 0 | 1 | 0 |
3 | 1004 | 0 | 1 | 0 | 0 | 1 |
pd.get_dummies(data,prefix="A")
學號 | A_專科 | A_本科 | A_碩士 | A_女 | A_男 | |
---|---|---|---|---|---|---|
0 | 1001 | 0 | 1 | 0 | 0 | 1 |
1 | 1002 | 0 | 0 | 1 | 1 | 0 |
2 | 1003 | 1 | 0 | 0 | 1 | 0 |
3 | 1004 | 0 | 1 | 0 | 0 | 1 |
pd.get_dummies(data,prefix=["A","B"],prefix_sep="+")
學號 | A+專科 | A+本科 | A+碩士 | B+女 | B+男 | |
---|---|---|---|---|---|---|
0 | 1001 | 0 | 1 | 0 | 0 | 1 |
1 | 1002 | 0 | 0 | 1 | 1 | 0 |
2 | 1003 | 1 | 0 | 0 | 1 | 0 |
3 | 1004 | 0 | 1 | 0 | 0 | 1 |
二.sklearn的崽一:LabelEncoder 將不連續的數字or文本進行編號
sklearn.preprocessing.LabelEncoder()
官方文檔:
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit([1,5,67,100])
le.transform([1,1,100,67,5])
#輸出: array([0,0,3,2,1])
array([0, 0, 3, 2, 1], dtype=int64)
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit([1, 3, 3, 7])
LabelEncoder()
le.transform([1, 1, 3, 7])
#array([0, 0, 1, 2]...)
le.classes_ #查看分類
#array([1, 2, 6])
le.inverse_transform([0, 0, 1, 2]) #transform的逆向
#array([1, 1, 2, 6])
array([1, 1, 3, 7])
三.sklearn的崽二:OneHotEncoder 對表示分類的數字進行編碼,輸出跟dummies一樣
sklearn.preprocessing.OneHotEncoder(n_values=None, categorical_features=None, categories=None, sparse=True, dtype=<class ‘numpy.float64’>, handle_unknown=’error’)
官方文檔:
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html
注意:
輸入的應該是表示類別的數字,如果輸入文本,會報錯的。
from sklearn.preprocessing import OneHotEncoder
OHE = OneHotEncoder()
OHE.fit(data)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-ba3b2772e40d> in <module>()
1 from sklearn.preprocessing import OneHotEncoder
2 OHE = OneHotEncoder()
----> 3 OHE.fit(data)
F:\Anaconda\lib\site-packages\sklearn\preprocessing\data.py in fit(self, X, y)
1954 self
1955 """
-> 1956 self.fit_transform(X)
1957 return self
1958
F:\Anaconda\lib\site-packages\sklearn\preprocessing\data.py in fit_transform(self, X, y)
2017 """
2018 return _transform_selected(X, self._fit_transform,
-> 2019 self.categorical_features, copy=True)
2020
2021 def _transform(self, X):
F:\Anaconda\lib\site-packages\sklearn\preprocessing\data.py in _transform_selected(X, transform, selected, copy)
1807 X : array or sparse matrix, shape=(n_samples, n_features_new)
1808 """
-> 1809 X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)
1810
1811 if isinstance(selected, six.string_types) and selected == "all":
F:\Anaconda\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
400 force_all_finite)
401 else:
--> 402 array = np.array(array, dtype=dtype, order=order, copy=copy)
403
404 if ensure_2d:
ValueError: could not convert string to float: '男'
看到,OneHotEncoder處理不了字符串。要先用
data3 = le.fit_transform(data["性別"])
OHE.fit(data3.reshape(-1,1))
OHE.transform(data3.reshape(-1,1)).toarray()
array([[ 0., 1.],
[ 1., 0.],
[ 1., 0.],
[ 0., 1.]])
對因變量y不能用OneHotEncoder,要用LabelBinarizer。