博客:https://www.cnblogs.com/enhaofrank/,公众号:生信AI区块链科技前沿,github:https://github.com/enhaofrank

功不唐捐 玉汝于成

数据处理以及建模完整流程

在数据挖掘工作中,数据预处理对于结果的影响是非常重要的,所以在这方面需要多花时间探索。

这里,我介绍一些数据预处理的流程以及方法:

首先,拿到数据之后,我们先把数据读进来:

 

### code ###

import numpy as np

import pandas as pd

import pandas_profiling

#read data 

data = pd.read_csv("yourdata")

#看数据情况

data.info

#看是否有空值

data.isnull().sum()

#看数据前面几行信息

data.head()

#看数据几行几列

data.shape

#看数据的每一列的情况(count,mean.std等)

data.describe()

data.drop_duplicates()

#这样一通看了之后,其实对数据了解还有限,没办法了解数据的整体分布,数据长什么样

#所以对感兴趣的内容需要画图进一步去看

data.profile_report()

##################

 

使用Pandas  Profiling可以在进行数据分析之前对数据进行快速预览,一行代码就生成丰富的交互式数据EDA报告。

除了之前我们需要的一些描述性统计数据,该报告还包含以下信息:

    • 类型推断:检测数据帧中列的数据类型。

    • 要点:类型,唯一值,缺失值

    • 分位数统计信息,例如最小值,Q1,中位数,Q3,最大值,范围,四分位数范围

    • 描述性统计数据,例如均值,众数,标准偏差,总和,中位数绝对偏差,变异系数,峰度,偏度

    • 最常使用的值

    • 直方图

    • 相关性矩阵

    • 缺失值矩阵,计数,热图和缺失值树状图

    • 文本分析:了解文本数据的类别(大写,空格),脚本(拉丁,西里尔字母)和块(ASCII)

 

补全空值:

data['age'].filllna(data['age'].median(),inplace=True)

 

这样一通下来,基本对数据应该是有个一定的了解了,接下来做的就是对数据进行预处理,

接下来我们使用sklearn中的preproccessing库来进行数据预处理:

from sklearn import preprocessing
import numpy as np

from sklearn.preprocessing import StandardScaler

#standard scaler

st_scaled = preprocessing.StandardScaler().fit_transform(X_train)
st_scaled

from sklearn.preprocessing import MinMaxScaler

min-max标准化方法是将数据缩放至给定的最小值与最大值之间,通常是0与1之间,可用MinMaxScaler实现。

#MinMaxScaler
minmax_scaled = preprocessing.MinMaxScaler().fit_transform(X_train)
minmax_scaled

或者将最大的绝对值缩放至单位大小,可用MaxAbsScaler实现。
与上述标准化方法相似,但是它通过除以最大值将训练集缩放至[-1,1]。这意味着数据已经以0为中心或者是含有非常非常多0的稀疏数据

#MaxAbsScaler
maxabs = preprocessing.MaxAbsScaler().fit_transform(X_train)
maxabs

#如果你的数据当中有很多异常值,用以上这些方面进行标准化或许发现不太好。但是可以用
#robust_scale或者robustScaler
sklearn.preprocessing.robust_scale(X, axis=0, with_centering=True, with_scaling=True, quantile_range=(25.0, 75.0), copy=True)

#归一化

from sklearn.preprocessing import Normalizer

preprocessing.Normalizer().fit_transform(X)

#preprocessing.OrdinalEncoder()
#preprocessing.OneHotEncoder()
#https://www.jianshu.com/p/4e19eb163e78
#https://blog.csdn.net/wuzhongqiang/article/details/104169480

 

 

from sklearn.preprocessing import Binarizer

#特征二值化
X = [[1,-1,2],[2,0,0],[0,1,-2]]
binarizer = preprocessing.Binarizer().fit_transform(X)
binarizer

#二值化,阈值设置为1.1,返回值为二值化后的数据

preprocessing.Binarizer(threshold=1.1).fit_transform(X)

 

from sklearn.preprocessing import OneHotEncoder
#独热编码,对IRIS数据集的目标值,返回值为独热编码后的数据
OneHotEncoder().fit_transform(iris.target.reshape((-1,1)))

 

get_dummies方法:

pd.get_dummies(data['sex'])

 

缺失值填充

from sklearn.preprocessing import Imputer

#用均值插补缺失值 imp = Imputer(missing_values='NaN', strategy='mean', axis=0)

#imputation of missing values
import numpy as np
from sklearn.impute import SimpleImputer
imp = SimpleImputer(missing_values=np.nan,strategy='mean')
imp.fit([[1,2],[np.nan,3],[7,6]])
X=[[np.nan,2],[np.nan,3],[7,6]]
print(imp.transform(X))

 

import numpy as np
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
imp = IterativeImputer(max_iter=10,random_state=0)
imp.fit([[1,2],[3,6],[4,8],[np.nan,3],[7,np.nan]])
X_test = [[np.nan,2],[6,np.nan],[np.nan,6]]
print(np.round(imp.transform(X_test)))

 

#Nearest neighbors imputation
import numpy as np
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.impute import KNNImputer
nan = np.nan
X = [[1,2,nan],[3,4,3],[nan,6,5],[8,8,7]]
imputer = KNNImputer(n_neighbors=2,weights='uniform')
imputer.fit_transform(X)

1、缺失值

2、处理文本和类别数据

3、特征缩放

 

特征选择:

from sklearn.feature_selection import VarianceThreshold
#方差选择法,返回值为特征选择后的数据
#参数threshold为方差的阈值
VarianceThreshold(threshold=2).fit_transform(iris.data)

 

from sklearn.feature_selection import SelectKBest
from scipy.stats import pearsonr

#选择K个最好的特征,返回选择特征后的数据
#第一个参数为计算评估特征是否好的函数,该函数输入特征矩阵和目标向量,输出二元组(评分,P值)的数组,数组第i项为第i个特征的评分和P值。在此定义为计算相关系数
#参数k为选择的特征个数
SelectKBest(lambda X, Y: tuple(map(tuple,array(list(map(lambda x:pearsonr(x, Y), X.T))).T)), k=2).fit_transform(iris.data, iris.target)
#SelectKBest(lambda X, Y: list(array([pearsonr(x, Y) for x in X.T]).T), k=2).fit_transform(iris.data, iris.target)

 

from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
#选择K个最好的特征,返回选择特征后的数据
SelectKBest(chi2, k=2).fit_transform(iris.data, iris.target)

from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression

#递归特征消除法,返回特征选择后的数据
#参数estimator为基模型
#参数n_features_to_select为选择的特征个数
RFE(estimator=LogisticRegression(), n_features_to_select=2).fit_transform(iris.data, iris.target)

from sklearn.decomposition import PCA
#主成分分析法,返回降维后的数据
#参数n_components为主成分数目
pca= PCA(n_components=2)
newData = pca.fit_transform(iris.data)
d_new=pca.inverse_transform(newData)
newData

 

from sklearn.lda import LDA
LDA(n_components=2).fit_transform(iris.data, iris.target)

 

模型选择和训练:

利用网格搜索对模型进行微调:

from sklearn.model_selection import GridSearchCV
param_grid = [
{'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},
{'bootstrap': [False], 'n_estimators': [3, 10], 'max_features': [2, 3, 4]},
]
forest_reg = RandomForestRegressor()
grid_search = GridSearchCV(forest_reg, param_grid, cv=5,
scoring='neg_mean_squared_error')
grid_search.fit(X_train,y_train)


grid_search.best_params_
grid_search.best_score_
grid_search.best_estimator_
用最好的模型去评估测试集数据
from sklearn.metrics import mean_squared_error
final_model = grid_search.best_estimator_
final_predictions = final_model.predict(X_test)
#k-折交叉验证 

cross_val_score(svc,X_digits,y_digits,cv=k_fold) 

#Automatic parameter searches
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import train_test_split
from scipy.stats import randint

#load the data and split into train and test sets
X,y = fetch_california_housing(return_X_y=True)
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=0)

#define the parameter space that will be searched over
param_distributions = {'n_estimators':randint(1,5),
'max_depth':randint(5,10)}

#now create a searchCV object and fit it to the data
search = RandomizedSearchCV(estimator=RandomForestRegressor(random_state=0),
n_iter=5,
param_distributions=param_distributions,
random_state=0)

search.fit(X_train,y_train)
search.best_params_

# the search object now acts like a normal random forest estimator
# with max_depth = 9 and n_estimators = 4
search.score(X_test,y_test)

 

参考资料:

1、https://www.jianshu.com/p/78c7be12d2a2?utm_source=oschina-app

2、这4款数据自动化探索 Python 神器,解决99%的数据分析问题! (qq.com)

posted on 2020-05-16 11:09  enhaofrank  阅读(1112)  评论(0编辑  收藏  举报

导航