[英]Stacking ensemble of classifiers in a chain
我有以下人类活动识别样本数据集:
df = pd.DataFrame(
{
'mean_speed': [40.01, 3.1, 2.88, 20.89, 5.82, 40.01, 33.1, 40.88, 20.89, 5.82, 40.018, 23.1],
'max_speed': [70.11, 6.71, 7.08, 39.63, 6.68, 70.11, 65.71, 71.08, 39.63, 13.68, 70.11, 35.71],
'max_acc': [17.63, 2.93, 3.32, 15.57, 0.94, 17.63, 12.93, 3.32, 15.57, 0.94, 17.63, 12.93],
'mean_acc': [5.15, 1.97, 0.59, 5.11, 0.19, 5.15, 2.97, 0.59, 5.11, 0.19, 5.15, 2.97],
'activity': ['driving', 'walking', 'walking', 'riding', 'walking', 'driving', 'motor-bike',
'motor-bike', 'riding', 'riding', 'motor-bike', 'riding']
}
)
df.head()
mean_speed max_speed max_acc mean_acc activity
0 40.01 70.11 17.63 5.15 driving
1 3.10 6.71 2.93 1.97 walking
2 2.88 7.08 3.32 0.59 walking
3 20.89 39.63 15.57 5.11 riding
4 5.82 6.68 0.94 0.19 walking
所以我想在管道中创建一系列机器学习分类器。 基础分类器首先预测一项activity
是机动的( driving
、 motor-bike
)还是非机动的( riding
、 walking
)。 学习阶段应该像这样进行:
所以我添加了一个列type
,说明活动是机动的还是其他的。
class_mapping = {'driving':'motorised', 'motor-bike':'motorised', 'walking':'non-motorised', 'riding':'non-motorised'}
df['type'] = df['activity'].map(class_mapping)
df.head()
mean_speed max_speed max_acc mean_acc activity type
0 40.01 70.11 17.63 5.15 driving motorised
1 3.10 6.71 2.93 1.97 walking non-motorised
2 2.88 7.08 3.32 0.59 walking non-motorised
3 20.89 39.63 15.57 5.11 riding non-motorised
4 5.82 6.68 0.94 0.19 walking non-motorised
题:
我想训练一个Random Forest
作为基础分类器,以预测一项活动是motorised
的还是non-motorised
,并具有概率输出。 然后是 2 个元分类器:预测活动是walking
还是riding
的Decision Tree
,以及预测活动是driving
还是motor-bike
的SVC
。 元分类器 ( DT, SVC
) 将作为输入,第一个分类器的 4 个特征 + 概率输出。 显然, DT
和SVC
只会采用与他们预测的类相对应的整个数据集的一个子集。
我对学习过程有这个想法,但我不确定如何实施它。
那里的任何人都可以展示如何做到这一点吗?
使用核心 Scikit-Learn 类不可能实现您的要求。 但是,如果您对使用某些第 3 方软件包的想法持开放态度,那么一点也不难。
首先,使用与机动化/非机动化决策概率相对应的特征丰富您的数据集:
from sklego.preprocessing import IdentityTransformer
from sklego.meta import EstimatorTransformer
feature_estimator = FeatureUnion([
("identity", IdentityTransformer()),
("type_estimator", EstimatorTransformer(RandomForestClassifier(), predict_func = "predict_proba"))
])
这会将两列(对应于 RandomForestClassifier.predict_proba(X) 的输出)附加到原始数据矩阵。
其次,建立最终的分类器集成。 使用“机动”类的概率来做出决定(例如,应用 75% 的阈值)。 请注意,此“标志”功能的索引是倒数第二个,即。 X[-2].
from sklearn2pmml.ensemble import EstimatorChain
final_estimator_chain = EstimatorChain([
("motorized", SVC(), "X[-2] >= 0.75"),
("non-motorized", DecisionTreeClassifier(), "X[-2] < 0.75"),
], multioutput = False)
把所有东西放在一起:
pipeline = Pipeline([
("step_one", feature_estimator),
("step_two", final_estimator_chain)
])
pipeline.fit(X, y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.