数据预处理没有标准的流程,通常针对不同的任务和数据集属性的不同而不同。下面就一起看下常用六大步完成数据预处理。
Step 1:导入相关模块
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
import yfinance as yf
yf.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']].values
y = 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 Imputer
imputer = 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, OneHotEncoder
labelencoder_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_split
X_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 StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.fit_transform(X_test)
数据变换十大秘诀
数据变换[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]])
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]])
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]])
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.]])
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.])
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)
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 --> 0
Google --> 1
Intel --> 2
Microsoft --> 3
Tesla --> 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')
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']
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]])
Imputer
填补(如用均值填补缺失值),它用列或特性数据中的平均值替换缺失的值
>>> 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]
...
[7.857e+01 7.941e+01 7.803e+01 1.716e+06]]