如何将PCA和keras分类器都放入sklearn管道中,并进行网格搜索CV?

问题描述

我正在尝试事先使用PCA在keras NN上进行网格搜索CV操作。为此,我构建了一个管道,该管道包括PCA步骤,然后使用sklearn包装器进行keras估计器。但是,我要搜索的一件事是PCA的n_components,这意味着神经网络的输入大小需要可变,并且取决于在上一条画线步骤中选择的特征的数量

下面是我的代码,用于创建一个已放入keras包装器中的NN

def create_model(learning_rate=0.01,activation='relu',Input_Vector_Size=34,neuron_number=10,dropout_prob=0.1):
    # Create an Adam optimizer with the given learning rate
    opt=Adam(lr=learning_rate)
    
    
    # Create your binary classification model  
    model=Sequential()
    model.add(Dense(neuron_number,input_shape=(Input_Vector_Size,),activation=activation))
    model.add(Dropout(dropout_prob))
    model.add(Dense(1,activation='sigmoid')) #output layer
    
    
    # Compile model with your optimizer,loss,and metrics
    model.compile(optimizer=opt,loss='binary_crossentropy',metrics=['accuracy'])
    
    return model

我使用以下方法将其放入管道

#%% Create a Pipeline with the Keras_Classifier and PCA
pca=PCA(n_components=0.9)
NN=KerasClassifier(build_fn=create_model,verbose=0)
# Define the parameters to try out
pipeline=Pipeline([('pca',pca),('NN',NN)])
params = {'pca__n_components':[0.8,0.85,0.9,0.95],'NN__activation': ['relu','tanh'],'NN__neuron_number': [10,15,20],'NN__dropout_prob':[0.05,0.1,0.2,0.3],'NN__learning_rate': [0.1,0.01,0.001]}

但是,我对于设置Input_Vector_Size的参数有些犹豫,因为这取决于PCA选择了多少个功能

那么,是否有可能使管道参数(此处为Input_Vector_Size)取决于管道上一步中的参数(此处为PCA选择的特征数)?

(注意:我意识到解决此问题的一种方法是在我的NN中仅使用一个自动编码器并改变压缩率,但是我希望专门进行PCA)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)