将 Sklearn GridSearchCV 与管道一起使用时如何传递权重

How to pass weights when using Sklearn GridSearchCV with Pipeline

我正在研究文本分类模型,我正在使用 Pipeline coupled with GridSearch Cross Validation。下面的代码片段:

count_vec=CountVectorizer(ngram_range=(1,2),stop_words=Stopwords_X,min_df=0.01)
TFIDF_Transformer=TfidfTransformer(sublinear_tf=True,norm='l2')

my_pipeline=Pipeline([('Count_Vectorizer',count_vec),
                    ('TF_IDF',TFIDF_Transformer),
                    ('MultiNomial_NB',MultinomialNB())])

param_grid={'Count_Vectorizer__ngram_range':[(1,1),(1,2),(2,2)],
               'Count_Vectorizer__stop_words':[Stopwords_X,stopwords],
               'Count_Vectorizer__min_df':[0.001,0.005,0.01],
               'TF_IDF__sublinear_tf':[True,False],
               'TF_IDF__norm':['l2'],
               'TF_IDF__smooth_idf':[True,False],
               'MultiNomial_NB__alpha':[0.2,0.4,0.5,0.6],
               'MultiNomial_NB__fit_prior':[True,False]}

# Grid Search CV with pipeline
model=GridSearchCV(estimator=my_pipeline,param_grid=param_grid,
                   scoring=scoring,cv=4,verbose=1,refit=False)

但是,由于数据高度不平衡,我想将权重传递给管道中的MultinomialNB分类器。我知道我可以将权重传递给管道内的元素(如下所示):

model.fit(Data_Labeled['Clean-Merged-Final'], 
          Data_Labeled['Labels'],MultiNomial_NB__sample_weight=weights)

我的问题是如何在没有形状错误的情况下进行编译? 因为在 CV 分区时权重仅传递给管道中的最终元素(MultiNomial_NB 分类器) X/Y 饲料进入管道。

GridSearchCV 根据交叉验证迭代器处理 sample_weights 的适当分解。

GridSearchCV 调用 _fit_and_score() method internally on the data and passes the indices for the training data. Up until now, the fit_params are for the whole data. Now this function in turn calls the function _index_param_value,它处理 sample_weight(或其他 fit_params)的拆分 在这一行中:

     ...
     return safe_indexing(v, indices)
     ...

这已在此处的问题中进行了讨论: