首頁>技術>

導讀: 預處理是資料探勘過程和機器學習的重要步驟。它被用來表示 "廢料進,廢品出"。在機器學習和資料探勘中,資料採集方法往往控制鬆散,導致值超出範圍、不可能的資料組合、缺失值等問題。在使用之前需要進行資料預處理。要想應用恰當的分析方法得到理想結果,就必須透過一些方法提高資料質量,而這就是預處理的工作。

預處理之所以重要,是因為它會對後續的資料分析質量、模型預測精度產生極大影響。資料預處理一般包括資料清洗和資料變換,資料清洗包括缺失值、異常值處理,資料變換一般包括資料歸一化、標準化、特徵編碼等等。

資料預處理沒有標準的流程,通常針對不同的任務和資料集屬性的不同而不同。下面就一起看下常用六大步完成資料預處理。其中資料獲取可以參考金融資料準備。

一、資料預處理六大步

Step 1:匯入相關模組

import numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport warningswarnings.filterwarnings("ignore")import yfinance as yfyf.pdr_override()

Step 2:獲取資料

symbol = 'TCEHY'start = '2011-01-01'end = '2021-03-31'dataset = yf.download(symbol,start,end)# 檢視資料dataset.head()
X = dataset[['Open', 'High', 'Low', 'Volume']].valuesy = dataset['Adj Close'].values特徵構造dataset['Increase_Decrease'] = np.where(dataset['Volume'].shift(-1) > dataset['Volume'],1,0)dataset['Buy_Sell_on_Open'] = np.where(dataset['Open'].shift(-1) > dataset['Open'],1,0)dataset['Buy_Sell'] = np.where(dataset['Adj Close'].shift(-1) > dataset['Adj Close'],1,0)dataset['Returns'] = dataset['Adj Close'].pct_change()dataset = dataset.dropna()dataset.head()

Step 3:處理缺失值

from sklearn.preprocessing import Imputerimputer = Imputer(missing_values = "NaN", strategy = "mean", axis = 0)imputer = imputer.fit(X[ : , 1:3])X[ : , 1:3] = imputer.transform(X[ : , 1:3])

Step 4:分類資料編碼

from sklearn.preprocessing import LabelEncoder, OneHotEncoderlabelencoder_X = LabelEncoder()X[ : , 0] = labelencoder_X.fit_transform(X[ : , 0])
建立虛擬變數
onehotencoder = OneHotEncoder(categorical_features = [0])X = onehotencoder.fit_transform(X).toarray()labelencoder_Y = LabelEncoder()Y =  labelencoder_Y.fit_transform(Y)

Step 5:劃分訓練集和測試集

from sklearn.cross_validation import train_test_splitX_train, X_test, Y_train, Y_test = train_test_split(         X ,          Y ,          test_size = 0.2,          random_state = 0)

Step 6:特徵標準化

from sklearn.preprocessing import StandardScalersc_X = StandardScaler()X_train = sc_X.fit_transform(X_train)X_test = sc_X.fit_transform(X_test)

二、資料變換十大秘訣

資料變換[1]是將資料集的每個元素乘以常數 ;也就是說,將每個數 變換為 ,其中 , 和 都是實數。資料變換將可能改變資料的分佈以及資料點的位置。

1、MinMaxScaler

>>> from sklearn.preprocessing import MinMaxScaler>>> scaler=MinMaxScaler(feature_range=(0,1))>>> rescaledX=scaler.fit_transform(X)>>> np.set_printoptions(precision=3) # 設定輸出的精度>>> rescaledX[0:5,:]array([[0.009, 0.008, 0.009, 0.01 ],       [0.01 , 0.009, 0.01 , 0.003],       [0.01 , 0.009, 0.01 , 0.001],       [0.01 , 0.009, 0.01 , 0.009],       [0.01 , 0.009, 0.01 , 0.017]])

2、Standardizing Data

資料標準化[2](有時稱為 z-score 或 standar score)是已重新縮放為平均值為零且標準偏差為1的變數。對於標準化變數,每種情況下的值在標準化變數上的值都表明它與原始變數的均值(或原始變數的標準偏差)的差值。

>>> from sklearn.preprocessing import StandardScaler>>> scaler=StandardScaler().fit(X)>>> rescaledX=scaler.transform(X)>>> rescaledX[0:5,:]array([[-1.107, -1.105, -1.109, -0.652],       [-1.102, -1.102, -1.103, -0.745],       [-1.103, -1.1  , -1.103, -0.764],       [-1.099, -1.099, -1.102, -0.663],       [-1.103, -1.101, -1.105, -0.564]])

3、Normalizing Data

歸一化資料是將資料縮放到0到1範圍內。

>>> from sklearn.preprocessing import Normalizer>>> scaler=Normalizer().fit(X)>>> normalizedX=scaler.transform(X)>>> normalizedX[0:5,:]array([[1.439e-05, 1.454e-05, 1.433e-05, 1.000e+00],       [4.104e-05, 4.107e-05, 4.089e-05, 1.000e+00],       [6.540e-05, 6.643e-05, 6.540e-05, 1.000e+00],       [1.627e-05, 1.627e-05, 1.612e-05, 1.000e+00],       [9.142e-06, 9.222e-06, 9.082e-06, 1.000e+00]])

4、Binarizing Data

二值化[3]是將任何實體的資料特徵轉換為二值化的向量以使分類器演算法更高效的過程。在一個簡單的示例中,將影象的灰度從0-255光譜轉換為0-1光譜就是二值化。

>>> from sklearn.preprocessing import Binarizer>>> binarizer=Binarizer(threshold=0.0).fit(X)>>> binaryX=binarizer.transform(X)>>> binaryX[0:5,:]array([[1., 1., 1., 1.],       [1., 1., 1., 1.],       [1., 1., 1., 1.],       [1., 1., 1., 1.],       [1., 1., 1., 1.]])

5、Mean Removal

去均值法是將均值從每一列或特徵中移除,使其以零為中心的過程。

>>> from sklearn.preprocessing import scale>>> data_standardized=scale(dataset)>>> data_standardized.mean(axis=0)array([ 0.000e+00,  0.000e+00, -8.823e-17, -1.765e-16, -8.823e-17,        8.823e-17,  6.617e-17,  1.792e-17, -2.654e-17, -7.065e-18])>>> data_standardized.std(axis=0)array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

6、One Hot Encoding

獨熱編碼[4]是將分類變數轉換為可以提供給ML演算法以更好地進行預測的形式的過程。

>>> from sklearn.preprocessing import OneHotEncoder>>> encoder=OneHotEncoder()>>> encoder.fit(X)OneHotEncoder(categorical_features=None, categories=None,       dtype=<class 'numpy.float64'>, handle_unknown='error',       n_values=None, sparse=True)

7、Label Encoding

標籤編碼適用於具有分類變數並將資料轉換為數字的資料。

fit
>>> from sklearn.preprocessing import LabelEncoder>>> label_encoder=LabelEncoder()>>> input_classes=['Apple','Intel','Microsoft','Google','Tesla']>>> label_encoder.fit(input_classes)>>> LabelEncoder()>>> for i,companies in enumerate(label_encoder.classes_):...     print(companies,'-->',i)Apple --> 0Google --> 1Intel --> 2Microsoft --> 3Tesla --> 4
transform
labels=['Apple','Intel','Microsoft']label_encoder.transform(labels)array([0, 2, 3], dtype=int64)label_encoder.inverse_transform(label_encoder.transform(labels))array(['Apple', 'Intel', 'Microsoft'], dtype='<U9')

8、DictVectorizor

詞向量用於帶有標籤和數字的資料。此外,詞向量可用於提取資料。

>>> from sklearn.feature_extraction import DictVectorizer>>> companies = [{'Apple':180.25,'Intel':45.30,                  'Microsoft':30.26,'Google':203.75,                  'Tesla':302.18}] >>> vec = DictVectorizer()>>> vec.fit_transform(companies).toarray()array([[180.25, 203.75,  45.3 ,  30.26, 302.18]])
獲取特徵名稱
>>> vec.get_feature_names()['Apple', 'Google', 'Intel', 'Microsoft', 'Tesla']

9、Polynomial Features

多項式特徵用於生成多項式特徵和互動特徵。它還生成了一個新的特徵矩陣資料,該資料是由所有次數小於或等於指定次數的特徵的多項式組合組成的。

>>> from sklearn.preprocessing import PolynomialFeatures>>> poly = PolynomialFeatures(2) # 二次互動項>>> poly.fit_transform(X)array([[1.000e+00, 4.490e+00, 4.538e+00, ..., 2.000e+01, 1.395e+06,        9.734e+10],       ...,       [1.000e+00, 7.857e+01, 7.941e+01, ..., 6.089e+03, 1.339e+08,        2.944e+12]])
截距項
>>> poly = PolynomialFeatures(interaction_only=True) # 不保留截距項>>> poly.fit_transform(X)array([[1.000e+00, 4.490e+00, 4.538e+00, ..., 2.029e+01, 1.416e+06,        1.395e+06],       ...,       [1.000e+00, 7.857e+01, 7.941e+01, ..., 6.196e+03, 1.363e+08,        1.339e+08]])

10、Imputer

填補(如用均值填補缺失值),它用列或特性資料中的平均值替換缺失的值

[7.857e+01 7.941e+01 7.803e+01 1.716e+06]]

>>> from sklearn.preprocessing import Imputer>>> imputer = SimpleImputer()>>> print(imputer.fit_transform(X, y))[[4.490e+00 4.538e+00 4.472e+00 3.120e+05] ...

8
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 真實模式下CPU如何獲取資料及指令