小夥伴們你們好~o( ̄▽ ̄)ブ,我是菜菜,個人開發環境是Jupyter lab,所用的庫和版本你們參考:python
Python 3.7.1(你的版本至少要3.4以上web
Scikit-learn 0.20.0 (你的版本至少要0.19算法
Numpy 1.15.3, Pandas 0.23.4, Matplotlib 3.0.1, SciPy 1.1.0數組
sklearn中包含衆多數據預處理和特徵工程相關的模塊,雖然剛接觸sklearn時,你們都會爲其中包含的各類算法的廣度深度所震驚,但其實sklearn六大板塊中有兩塊都是關於數據預處理和特徵工程的,兩個板塊互相交互,爲建模以前的所有工程打下基礎。微信
在機器學習算法實踐中,咱們每每有着將不一樣規格的數據轉換到同一規格,或不一樣分佈的數據轉換到某個特定分佈的需求,這種需求統稱爲將數據「無量綱化」。譬如梯度和矩陣爲核心的算法中,譬如邏輯迴歸,支持向量機,神經網絡,無量綱化能夠加快求解速度;而在距離類模型,譬如K近鄰,K-Means聚類中,無量綱化能夠幫咱們提高模型精度,避免某一個取值範圍特別大的特徵對距離計算形成影響。(一個特例是決策樹和樹的集成算法們,對決策樹咱們不須要無量綱化,決策樹能夠把任意數據都處理得很好。)網絡
數據的無量綱化能夠是線性的,也能夠是非線性的。線性的無量綱化包括中心化(Zero-centered或者Mean-subtraction)處理和縮放處理(Scale)。中心化的本質是讓全部記錄減去一個固定值,即讓數據樣本數據平移到某個位置。縮放的本質是經過除以一個固定值,將數據固定在某個範圍之中,取對數也算是一種縮放處理。機器學習
當數據(x)按照最小值中心化後,再按極差(最大值 - 最小值)縮放,數據移動了最小值個單位,而且會被收斂到[0,1]之間,而這個過程,就叫作數據歸一化(Normalization,又稱Min-Max Scaling)。注意,Normalization是歸一化,不是正則化,真正的正則化是regularization,不是數據預處理的一種手段。歸一化以後的數據服從正態分佈,公式以下:ide
在sklearn當中,咱們使用preprocessing.MinMaxScaler來實現這個功能。MinMaxScaler有一個重要參數,feature_range,控制咱們但願把數據壓縮到的範圍,默認是[0,1]。學習
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n31" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from sklearn.preprocessing import MinMaxScaler
data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
編碼
import pandas as pd
pd.DataFrame(data)
scaler = MinMaxScaler() #實例化
scaler = scaler.fit(data) #fit,在這裏本質是生成min(x)和max(x)
result = scaler.transform(data) #經過接口導出結果
result
result_ = scaler.fit_transform(data) #訓練和導出結果一步達成
scaler.inverse_transform(result) #將歸一化後的結果逆轉
data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
scaler = MinMaxScaler(feature_range=[5,10]) #依然實例化
result = scaler.fit_transform(data) #fit_transform一步導出結果
result
BONUS: 使用numpy來實現歸一化
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n34" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import numpy as np
X = np.array([[-1, 2], [-0.5, 6], [0, 10], [1, 18]])
X_nor = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_nor
X_returned = X_nor * (X.max(axis=0) - X.min(axis=0)) + X.min(axis=0)
X_returned</pre>
當數據(x)按均值(μ)中心化後,再按標準差(σ)縮放,數據就會服從爲均值爲0,方差爲1的正態分佈(即標準正態分佈),而這個過程,就叫作數據標準化(Standardization,又稱Z-score normalization),公式以下:
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n41" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from sklearn.preprocessing import StandardScaler
data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
scaler = StandardScaler() #實例化
scaler.fit(data) #fit,本質是生成均值和方差
scaler.mean_ #查看均值的屬性mean_
scaler.var_ #查看方差的屬性var_
x_std = scaler.transform(data) #經過接口導出結果
x_std.mean() #導出的結果是一個數組,用mean()查看均值
x_std.std() #用std()查看方差
scaler.fit_transform(data) #使用fit_transform(data)一步達成結果
scaler.inverse_transform(x_std) #使用inverse_transform逆轉標準化</pre>
對於StandardScaler和MinMaxScaler來講,空值NaN會被當作是缺失值,在fit的時候忽略,在transform的時候保持缺失NaN的狀態顯示。而且,儘管去量綱化過程不是具體的算法,但在fit接口中,依然只容許導入至少二維數組,一維數組導入會報錯。一般來講,咱們輸入的X會是咱們的特徵矩陣,現實案例中特徵矩陣不太多是一維因此不會存在這個問題。
看狀況。大多數機器學習算法中,會選擇StandardScaler來進行特徵縮放,由於MinMaxScaler對異常值很是敏感。在PCA,聚類,邏輯迴歸,支持向量機,神經網絡這些算法中,StandardScaler每每是最好的選擇。
MinMaxScaler在不涉及距離度量、梯度、協方差計算以及數據須要被壓縮到特定區間時使用普遍,好比數字圖像處理中量化像素強度時,都會使用MinMaxScaler將數據壓縮於[0,1]區間之中。
建議先試試看StandardScaler,效果很差換MinMaxScaler。
除了StandardScaler和MinMaxScaler以外,sklearn中也提供了各類其餘縮放處理(中心化只須要一個pandas廣播一下減去某個數就行了,所以sklearn不提供任何中心化功能)。好比,在但願壓縮數據,卻不影響數據的稀疏性時(不影響矩陣中取值爲0的個數時),咱們會使用MaxAbsScaler;在異常值多,噪聲很是大時,咱們可能會選用分位數來無量綱化,此時使用RobustScaler。更多詳情請參考如下列表。
機器學習和數據挖掘中所使用的數據,永遠不多是完美的。不少特徵,對於分析和建模來講意義非凡,但對於實際收集數據的人卻不是如此,所以數據挖掘之中,經常會有重要的字段缺失值不少,但又不能捨棄字段的狀況。所以,數據預處理中很是重要的一項就是處理缺失值。
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n55" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import pandas as pd
data = pd.read_csv(r"C:worklearnbettermicro-class\
week 3 PreprocessingNarrativedata.csv",index_col=0)
data.head()</pre>
在這裏,咱們使用從泰坦尼克號提取出來的數據,這個數據有三個特徵,一個數值型,兩個字符型,標籤也是字符型。從這裏開始,咱們就使用這個數據給你們做爲例子,讓你們慢慢熟悉sklearn中數據預處理的各類方式。
class sklearn.impute.SimpleImputer
(missing_values=nan, strategy=’mean’, fill_value=None, verbose=0, copy=True)
在講解隨機森林的案例時,咱們用這個類和隨機森林迴歸填補了缺失值,對比了不一樣的缺失值填補方式對數據的影響。這個類是專門用來填補缺失值的。它包括四個重要參數:
參數 | 含義&輸入 |
---|---|
missing_values | 告訴SimpleImputer,數據中的缺失值長什麼樣,默認空值np.nan |
strategy | 咱們填補缺失值的策略,默認均值。 輸入「mean」使用均值填補(僅對數值型特徵可用) 輸入「median"用中值填補(僅對數值型特徵可用) 輸入"most_frequent」用衆數填補(對數值型和字符型特徵均可用) 輸入「constant"表示請參考參數「fill_value"中的值(對數值型和字符型特徵均可用) |
fill_value | 當參數startegy爲」constant"的時候可用,可輸入字符串或數字表示要填充的值,經常使用0 |
copy | 默認爲True,將建立特徵矩陣的副本,反之則會將缺失值填補到本來的特徵矩陣中去。 |
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n79" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">data.info()
Age = data.loc[:,"Age"].values.reshape(-1,1) #sklearn當中特徵矩陣必須是二維
Age[:20]
from sklearn.impute import SimpleImputer
imp_mean = SimpleImputer() #實例化,默認均值填補
imp_median = SimpleImputer(strategy="median") #用中位數填補
imp_0 = SimpleImputer(strategy="constant",fill_value=0) #用0填補
imp_mean = imp_mean.fit_transform(Age) #fit_transform一步完成調取結果
imp_median = imp_median.fit_transform(Age)
imp_0 = imp_0.fit_transform(Age)
imp_mean[:20]
imp_median[:20]
imp_0[:20]
data.loc[:,"Age"] = imp_median
data.info()
Embarked = data.loc[:,"Embarked"].values.reshape(-1,1)
imp_mode = SimpleImputer(strategy = "most_frequent")
data.loc[:,"Embarked"] = imp_mode.fit_transform(Embarked)
data.info()</pre>
BONUS:用Pandas和Numpy進行填補其實更加簡單
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n82" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import pandas as pd
data = pd.read_csv(r"C:worklearnbettermicro-classweek 3 PreprocessingNarrativedata.csv",index_col=0)
data.head()
data.loc[:,"Age"] = data.loc[:,"Age"].fillna(data.loc[:,"Age"].median())
data.dropna(axis=0,inplace=True)
在機器學習中,大多數算法,譬如邏輯迴歸,支持向量機SVM,k近鄰算法等都只可以處理數值型數據,不能處理文字,在sklearn當中,除了專用來處理文字的算法,其餘算法在fit的時候所有要求輸入數組或矩陣,也不可以導入文字型數據(其實手寫決策樹和普斯貝葉斯能夠處理文字,可是sklearn中規定必須導入數值型)。然而在現實中,許多標籤和特徵在數據收集完畢的時候,都不是以數字來表現的。好比說,學歷的取值能夠是["小學",「初中」,「高中」,"大學"],付費方式可能包含["支付寶",「現金」,「微信」]等等。在這種狀況下,爲了讓數據適應算法和庫,咱們必須將數據進行編碼,便是說,將文字型數據轉換爲數值型。
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n90" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from sklearn.preprocessing import LabelEncoder
y = data.iloc[:,-1] #要輸入的是標籤,不是特徵矩陣,因此容許一維
le = LabelEncoder() #實例化
le = le.fit(y) #導入數據
label = le.transform(y) #transform接口調取結果
le.classes_ #屬性.classes_查看標籤中究竟有多少類別
label #查看獲取的結果label
le.fit_transform(y) #也能夠直接fit_transform一步到位
le.inverse_transform(label) #使用inverse_transform能夠逆轉
data.iloc[:,-1] = label #讓標籤等於咱們運行出來的結果
data.head()
from sklearn.preprocessing import LabelEncoder
data.iloc[:,-1] = LabelEncoder().fit_transform(data.iloc[:,-1])</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" contenteditable="false" cid="n95" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from sklearn.preprocessing import OrdinalEncoder
data_ = data.copy()
data_.head()
OrdinalEncoder().fit(data_.iloc[:,1:-1]).categories_
data_.iloc[:,1:-1] = OrdinalEncoder().fit_transform(data_.iloc[:,1:-1])
data_.head()</pre>
咱們剛纔已經用OrdinalEncoder把分類變量Sex和Embarked都轉換成數字對應的類別了。在艙門Embarked這一列中,咱們使用[0,1,2]表明了三個不一樣的艙門,然而這種轉換是正確的嗎?
咱們來思考三種不一樣性質的分類數據:
1) 艙門(S,C,Q)
三種取值S,C,Q是相互獨立的,彼此之間徹底沒有聯繫,表達的是S≠C≠Q的概念。這是名義變量。
2) 學歷(小學,初中,高中)
三種取值不是徹底獨立的,咱們能夠明顯看出,在性質上能夠有高中>初中>小學這樣的聯繫,學歷有高低,可是學歷取值之間卻不是能夠計算的,咱們不能說小學 + 某個取值 = 初中。這是有序變量。
3) 體重(>45kg,>90kg,>135kg)
各個取值之間有聯繫,且是能夠互相計算的,好比120kg - 45kg = 90kg,分類之間能夠經過數學計算互相轉換。這是有距變量。
然而在對特徵進行編碼的時候,這三種分類數據都會被咱們轉換爲[0,1,2],這三個數字在算法看來,是連續且能夠計算的,這三個數字相互不等,有大小,而且有着能夠相加相乘的聯繫。因此算法會把艙門,學歷這樣的分類特徵,都誤會成是體重這樣的分類特徵。這是說,咱們把分類轉換成數字的時候,忽略了數字中自帶的數學性質,因此給算法傳達了一些不許確的信息,而這會影響咱們的建模。
類別OrdinalEncoder能夠用來處理有序變量,但對於名義變量,咱們只有使用啞變量的方式來處理,纔可以儘可能向算法傳達最準確的信息:
這樣的變化,讓算法可以完全領悟,原來三個取值是沒有可計算性質的,是「有你就沒有我」的不等概念。在咱們的數據中,性別和艙門,都是這樣的名義變量。所以咱們須要使用獨熱編碼,將兩個特徵都轉換爲啞變量。
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n112" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">data.head()
from sklearn.preprocessing import OneHotEncoder
X = data.iloc[:,1:-1]
enc = OneHotEncoder(categories='auto').fit(X)
result = enc.transform(X).toarray()
result
OneHotEncoder(categories='auto').fit_transform(X).toarray()
pd.DataFrame(enc.inverse_transform(result))
enc.get_feature_names()
result
result.shape
newdata = pd.concat([data,pd.DataFrame(result)],axis=1)
newdata.head()
newdata.drop(["Sex","Embarked"],axis=1,inplace=True)
newdata.columns = ["Age","Survived","Female","Male","Embarked_C","Embarked_Q","Embarked_S"]
newdata.head()</pre>
特徵能夠作啞變量,標籤也能夠嗎?能夠,使用類sklearn.preprocessing.LabelBinarizer能夠對作啞變量,許多算法均可以處理多標籤問題(好比說決策樹),可是這樣的作法在現實中不常見,所以咱們在這裏就不贅述了。
根據閾值將數據二值化(將特徵值設置爲0或1),用於處理連續型變量。大於閾值的值映射爲1,而小於或等於閾值的值映射爲0。默認閾值爲0時,特徵中全部的正值都映射到1。二值化是對文本計數數據的常見操做,分析人員能夠決定僅考慮某種現象的存在與否。它還能夠用做考慮布爾隨機變量的估計器的預處理步驟(例如,使用貝葉斯設置中的伯努利分佈建模)。
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" contenteditable="false" cid="n121" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">#將年齡二值化
data_2 = data.copy()
from sklearn.preprocessing import Binarizer
X = data_2.iloc[:,0].values.reshape(-1,1) #類爲特徵專用,因此不能使用一維數組
transformer = Binarizer(threshold=30).fit_transform(X)
transformer</pre>
這是將連續型變量劃分爲分類變量的類,可以將連續型變量排序後按順序分箱後編碼。總共包含三個重要參數:
參數 | 含義&輸入 |
---|---|
n_bins | 每一個特徵中分箱的個數,默認5,一次會被運用到全部導入的特徵 |
encode | 編碼的方式,默認「onehot」 "onehot":作啞變量,以後返回一個稀疏矩陣,每一列是一個特徵中的一個類別,含有該 類別的樣本表示爲1,不含的表示爲0 「ordinal」:每一個特徵的每一個箱都被編碼爲一個整數,返回每一列是一個特徵,每一個特徵下含 有不一樣整數編碼的箱的矩陣 "onehot-dense":作啞變量,以後返回一個密集數組。 |
strategy | 用來定義箱寬的方式,默認"quantile" "uniform":表示等寬分箱,即每一個特徵中的每一個箱的最大值之間的差爲 (特徵.max() - 特徵.min())/(n_bins) "quantile":表示等位分箱,即每一個特徵中的每一個箱內的樣本數量都相同 "kmeans":表示按聚類分箱,每一個箱中的值到最近的一維k均值聚類的簇心得距離都相同 |
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="Python" contenteditable="false" cid="n140" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from sklearn.preprocessing import KBinsDiscretizer
X = data.iloc[:,0].values.reshape(-1,1)
est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform')
est.fit_transform(X)
set(est.fit_transform(X).ravel())
est = KBinsDiscretizer(n_bins=3, encode='onehot', strategy='uniform')
est.fit_transform(X).toarray()</pre>