【发布时间】:2025-12-29 09:40:06
【问题描述】:
我有一个包含 6 个类的数据集,它们可以映射到 4 个 one-hot-encoded 列,以便每个类对应于 one-hot-encodings 的不同组合:
| Class | one-hot1 | one-hot2 | one-hot3 | one-hot4 | |
|---|---|---|---|---|---|
| 0 | class1 | 1 | 0 | 1 | 0 |
| 1 | class2 | 1 | 0 | 0 | 0 |
| 2 | class3 | 1 | 1 | 0 | 0 |
| 3 | class4 | 0 | 0 | 1 | 0 |
| 4 | class5 | 0 | 1 | 0 | 0 |
| 5 | class6 | 1 | 1 | 0 | 1 |
我能够在每个 one-hot-encoded 列上拟合 4 个不同的二元分类器,它们都表现得相当好(大约 90% 的准确度,几乎没有偏差)。如何将这 4 个分类器组合成一个分类器,而不用每个分类器拟合不相关的数据?
二元分类器之一的示例:
# Optimized ngrams + features
transformer_one_hot_1 = FeatureUnion([
('feature1_tfidf',
Pipeline([('extract_field',
FunctionTransformer(return_feature1, validate=False)),
('tfidf',
TfidfVectorizer(ngram_range=(2, 6), analyzer='char_wb', sublinear_tf=True, lowercase=False))])),
('feature2_tfidf',
Pipeline([('extract_field',
FunctionTransformer(return_feature2, validate=False)),
('tfidf',
TfidfVectorizer(ngram_range=(1, 7), analyzer='char_wb', sublinear_tf=True, lowercase=False))])),
('feature3_tfidf',
Pipeline([('extract_field',
FunctionTransformer(return_feature3, validate=False)),
('tfidf',
TfidfVectorizer(ngram_range=(1, 6), analyzer='char_wb', sublinear_tf=True, lowercase=False))])),
('feature4_tfidf',
Pipeline([('extract_field',
FunctionTransformer(return_feature4, validate=False)),
('tfidf',
TfidfVectorizer(ngram_range=(1, 8), analyzer='char_wb', sublinear_tf=True, lowercase=False))]))])
# Pipeline
pipeline_one_hot_1 = Pipeline(
[
("tfidfs", transformer_one_hot_1),
("classifier", LinearSVC(class_weight='balanced')),
]
)
# Fit the pipeline to the one-hot-encoded column of interest
pipeline_one_hot_1.fit(X_train, y_train['one-hot1'])
每个分类器(pipeline_one_hot_1、pipeline_one_hot_2、pipeline_one_hot_3 等)单独执行都相当不错。
现在我结合单独训练的二进制分类器的输出来生成预测的 one-hot-encoded 列:
one-hot-col-1 = pipeline_one_hot_1.predict(X_test)
one-hot-col-2 = pipeline_one_hot_2.predict(X_test)
one-hot-col-3 = pipeline_one_hot_3.predict(X_test)
one-hot-col-4 = pipeline_one_hot_4.predict(X_test)
然后我检查这些输出以查看它们是否对应于每个类的 one-hot-encodings。
但是,我最终想要的是一个接受数据帧/字典并返回单热编码向量的分类器:
prediction = combined_classifiers.predict(X_test)
其中prediction 是一个形状为(nsamples, n-onehotencodedcolumns) 的数组。
具体来说,我如何确保每个分类器都只针对相关数据进行训练? IE。我不想在one-hot2 列上训练pipeline_one_hot_1。有没有办法确保 StackingClassifier() 中的分类器在拟合时只看到某些数据,以便微调的模型不会拟合到错误的 one-hot-encoded 列?
【问题讨论】:
-
很少有人费心阅读和理解这么多信息。我强烈建议您只保留您的问题所需的信息
-
是的,这也是我的感觉。我会修改它以使其更简洁。
标签: python scikit-learn svm text-classification multilabel-classification