python – 分类:使用sklearn进行PCA和逻辑回归

第0步:问题描述

我有一个分类问题,即我想基于数字特征的集合,使用逻辑回归和运行主成分分析(PCA)来预测二进制目标.

我有2个数据集:df_train和df_valid(分别是训练集和验证集)作为pandas数据框,包含特征和目标.作为第一步,我使用了get_dummies pandas函数将所有分类变量转换为boolean.例如,我会:

n_train = 10
np.random.seed(0)
df_train = pd.DataFrame({"f1":np.random.random(n_train),\
                         "f2": np.random.random(n_train),\
                         "f3":np.random.randint(0,2,n_train).astype(bool),\
                         "target":np.random.randint(0,n_train).astype(bool)})

In [36]: df_train
Out[36]: 
         f1        f2     f3 target
0  0.548814  0.791725  False  False
1  0.715189  0.528895   True   True
2  0.602763  0.568045  False   True
3  0.544883  0.925597   True   True
4  0.423655  0.071036   True   True
5  0.645894  0.087129   True  False
6  0.437587  0.020218   True   True
7  0.891773  0.832620   True  False
8  0.963663  0.778157  False  False
9  0.383442  0.870012   True   True

n_valid = 3
np.random.seed(1)
df_valid = pd.DataFrame({"f1":np.random.random(n_valid),\
                         "f2": np.random.random(n_valid),n_valid).astype(bool),n_valid).astype(bool)})

In [44]: df_valid
Out[44]: 
         f1        f2     f3 target
0  0.417022  0.302333  False  False
1  0.720324  0.146756   True  False
2  0.000114  0.092339   True   True

我现在想应用PCA来减少问题的维数,然后使用sklearn中的LogisticRegression训练并获得我的验证集的预测,但我不确定我遵循的程序是否正确.这是我做的:

第1步:PCA

我的想法是,我需要以与PCA相同的方式转换我的训练和验证设置.换句话说,我不能单独执行PCA.否则,它们将被投射到不同的特征向量上.

from sklearn.decomposition import PCA

pca = PCA(n_components=2) #assume to keep 2 components,but doesn't matter
newdf_train = pca.fit_transform(df_train.drop("target",axis=1))
newdf_valid = pca.transform(df_valid.drop("target",axis=1)) #not sure here if this is right

第二步:Logistic回归

这没有必要,但我更喜欢将事物保存为数据帧:

features_train = pd.DataFrame(newdf_train)
features_valid = pd.DataFrame(newdf_valid)  

现在我进行逻辑回归

from sklearn.linear_model import LogisticRegression
cls = LogisticRegression() 
cls.fit(features_train,df_train["target"])
predictions = cls.predict(features_valid)

我认为第2步是正确的,但我对第1步有更多疑问:这是我应该链接PCA,然后是分类器的方式吗?

最佳答案
为此目的,sklearn中有一个pipeline.

from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

pca = PCA(n_components=2)
cls = LogisticRegression() 

pipe = Pipeline([('pca',pca),('logistic',clf)])
pipe.fit(features_train,df_train["target"])
predictions = pipe.predict(features_valid)

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...