1. 程式人生 > 其它 >機器學習sklearn(六): 資料處理(三)數值型資料處理(一)歸一化( MinMaxScaler/MaxAbsScaler)

機器學習sklearn(六): 資料處理(三)數值型資料處理(一)歸一化( MinMaxScaler/MaxAbsScaler)

來源:https://www.cntofu.com/book/170/docs/59.md

1 將特徵縮放至特定範圍內

一種標準化是將特徵縮放到給定的最小值和最大值之間,通常在零和一之間,或者也可以將每個特徵的最大絕對值轉換至單位大小。可以分別使用MinMaxScalerMaxAbsScaler實現。

使用這種縮放的目的包括實現特徵極小方差的魯棒性以及在稀疏矩陣中保留零元素。

以下是一個將簡單的資料矩陣縮放到[0, 1]的例子:

>>> X_train = np.array([[ 1., -1.,  2.],
...                     [ 2.,  0.,  0.],
...                     [ 0.,  
1., -1.]]) ... >>> min_max_scaler = preprocessing.MinMaxScaler() >>> X_train_minmax = min_max_scaler.fit_transform(X_train) >>> X_train_minmax array([[0.5 , 0. , 1. ], [1. , 0.5 , 0.33333333], [0. , 1. , 0. ]])

同樣的轉換例項可以被用與在訓練過程中不可見的測試資料:實現和訓練資料一致的縮放和移位操作:

>>> X_test = np.array([[ -3., -1.,  4.]])
>>> X_test_minmax = min_max_scaler.transform(X_test)
>>> X_test_minmax
array([[-1.5       ,  0\.        ,  1.66666667]])

可以檢查縮放器(scaler)屬性,來觀察在訓練集中學習到的轉換操作的基本性質:

>>> min_max_scaler.scale_                             
array([ 
0.5 , 0.5 , 0.33...]) >>> min_max_scaler.min_ array([ 0\. , 0.5 , 0.33...])

如果給MinMaxScaler提供一個明確的feature_range=(min, max),完整的公式是:

X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))

X_scaled = X_std * (max - min) + min

MaxAbsScaler的工作原理非常相似,但是它只通過除以每個特徵的最大值將訓練資料特徵縮放至[-1, 1]範圍內,這就意味著,訓練資料應該是已經零中心化或者是稀疏資料。 例子::用先前例子的資料實現最大絕對值縮放操作。

以下是使用上例中資料運用這個縮放器的例子:

>>> X_train = np.array([[ 1., -1.,  2.],
...                     [ 2.,  0.,  0.],
...                     [ 0.,  1., -1.]])
...
>>> max_abs_scaler = preprocessing.MaxAbsScaler()
>>> X_train_maxabs = max_abs_scaler.fit_transform(X_train)
>>> X_train_maxabs
array([[ 0.5, -1. ,  1. ],
       [ 1. ,  0. ,  0. ],
       [ 0. ,  1. , -0.5]])
>>> X_test = np.array([[ -3., -1.,  4.]])
>>> X_test_maxabs = max_abs_scaler.transform(X_test)
>>> X_test_maxabs
array([[-1.5, -1. ,  2. ]])
>>> max_abs_scaler.scale_
array([2.,  1.,  2.])

2縮放稀疏(矩陣)資料

中心化稀疏(矩陣)資料會破壞資料的稀疏結構,因此很少有一個比較明智的實現方式。但是縮放稀疏輸入是有意義的,尤其是當幾個特徵在不同的量級範圍時。

MaxAbsScaler以及maxabs_scale是專為縮放資料而設計的,並且是縮放資料的推薦方法。但是,scaleStandardScaler也能夠接受scipy.sparse作為輸入,只要引數with_mean=False被準確傳入它的構造器。否則會出現ValueError的錯誤,因為預設的中心化會破壞稀疏性,並且經常會因為分配過多的記憶體而使執行崩潰。RobustScaler不能適應稀疏輸入,但你可以在稀疏輸入使用transform方法。

注意,縮放器同時接受壓縮的稀疏行和稀疏列(參見scipy.sparse.csr_matrix以及scipy.sparse.csc_matrix)。任何其他稀疏輸入將會轉化為壓縮稀疏行表示。為了避免不必要的記憶體複製,建議在上游(早期)選擇CSR或CSC表示。

最後,最後,如果已經中心化的資料並不是很大,使用toarray方法將輸入的稀疏矩陣顯式轉換為陣列是另一種選擇。

3. 縮放有離群值的資料

如果你的資料包含許多異常值,使用均值和方差縮放可能並不是一個很好的選擇。這種情況下,你可以使用robust_scale以及RobustScaler作為替代品。它們對你的資料的中心和範圍使用更有魯棒性的估計。

參考:

更多關於中心化和縮放資料的重要性討論在此FAQ中提及:Should I normalize/standardize/rescale the data?

Scaling vs Whitening 有時候獨立地中心化和縮放資料是不夠的,因為下游的機器學習模型能夠對特徵之間的線性依賴做出一些假設(這對模型的學習過程來說是不利的)。

要解決這個問題,你可以使用sklearn.decomposition.PCAsklearn.decomposition.RandomizedPCA並指定引數whiten=True來更多移除特徵間的線性關聯。

在迴歸中縮放目標變數

scale以及StandardScaler可以直接處理一維陣列。在迴歸中,縮放目標/相應變數時非常有用。

4. 核矩陣的中心化

如果你有一個核矩陣,它計算由函式定義的特徵空間的點積,那麼一個KernelCenterer類能夠轉化這個核矩陣,通過移除特徵空間的平均值,使它包含由函式定義的內部產物。

相關api:

classsklearn.preprocessing.MinMaxScaler(feature_range=0, 1,*,copy=True,clip=False)

Transform features by scaling each feature to a given range.

This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one.

The transformation is given by:

X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min

where min, max = feature_range.

This transformation is often used as an alternative to zero mean, unit variance scaling.

Read more in theUser Guide.

Parameters
feature_rangetuple (min, max), default=(0, 1)

Desired range of transformed data.

copybool, default=True

Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array).

clipbool, default=False

Set to True to clip transformed values of held-out data to providedfeaturerange.

New in version 0.24.

Attributes
min_ndarray of shape (n_features,)

Per feature adjustment for minimum. Equivalent tomin-X.min(axis=0)*self.scale_

scale_ndarray of shape (n_features,)

Per feature relative scaling of the data. Equivalent to(max-min)/(X.max(axis=0)-X.min(axis=0))

New in version 0.17:scale_attribute.

data_min_ndarray of shape (n_features,)

Per feature minimum seen in the data

New in version 0.17:data_min_

data_max_ndarray of shape (n_features,)

Per feature maximum seen in the data

New in version 0.17:data_max_

data_range_ndarray of shape (n_features,)

Per feature range(data_max_-data_min_)seen in the data

New in version 0.17:data_range_

n_samples_seen_int

The number of samples processed by the estimator. It will be reset on new calls to fit, but increments acrosspartial_fitcalls.

>>> from sklearn.preprocessing import MinMaxScaler
>>> data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]
>>> scaler = MinMaxScaler()
>>> print(scaler.fit(data))
MinMaxScaler()
>>> print(scaler.data_max_)
[ 1. 18.]
>>> print(scaler.transform(data))
[[0.   0.  ]
 [0.25 0.25]
 [0.5  0.5 ]
 [1.   1.  ]]
>>> print(scaler.transform([[2, 2]]))
[[1.5 0. ]]

classsklearn.preprocessing.MaxAbsScaler(*,copy=True)

Scale each feature by its maximum absolute value.

This estimator scales and translates each feature individually such that the maximal absolute value of each feature in the training set will be 1.0. It does not shift/center the data, and thus does not destroy any sparsity.

This scaler can also be applied to sparse CSR or CSC matrices.

New in version 0.17.

Parameters
copybool, default=True

Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array).

Attributes
scale_ndarray of shape (n_features,)

Per feature relative scaling of the data.

New in version 0.17:scale_attribute.

max_abs_ndarray of shape (n_features,)

Per feature maximum absolute value.

n_samples_seen_int

The number of samples processed by the estimator. Will be reset on new calls to fit, but increments acrosspartial_fitcalls.

Examples

>>> from sklearn.preprocessing import MaxAbsScaler
>>> X = [[ 1., -1.,  2.],
...      [ 2.,  0.,  0.],
...      [ 0.,  1., -1.]]
>>> transformer = MaxAbsScaler().fit(X)
>>> transformer
MaxAbsScaler()
>>> transformer.transform(X)
array([[ 0.5, -1. ,  1. ],
       [ 1. ,  0. ,  0. ],
       [ 0. ,  1. , -0.5]])