如何将两个不同训练的 ML 模型组合为一个?

问题描述 投票:0回答:2

我已经根据两个不同的数据集训练了两个机器学习模型。然后我将它们保存为 model1.pkl 和 model2.pkl 。有两个用户输入(不是模型的输入数据),例如 x=0 和 x=1,如果 x=0 我必须使用 model1.pkl 进行预测,否则我必须使用 model2.pkl 进行预测。我可以使用 if 条件来完成它们,但我的问题是我必须知道是否有可能将其保存为 model.pkl ,包括此条件语句。如果我将它们组合起来并另存为模型,则可以轻松加载到其他 IDE 中。

pandas machine-learning model conditional-statements pickle
2个回答
0
投票

您可以创建一个类,它具有像模型类一样的最小接口,如下所示:

# create the test setup
import lightgbm as lgb
import pickle as pkl
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import LabelEncoder
#from sklearn
df['x1']= LabelEncoder().fit_transform(df['x1'])

data= {
 'x': [1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0],
 'q': [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0],
 'b': [1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0],
 'target': [0.0, 2.0, 1.5, 0.0, 5.1, 4.0, 0.0, 1.0, 2.0, 0.0, 2.1, 1.5]
}
df= pd.DataFrame(data) 
X, y=df.iloc[:, :-1], df.iloc[:, -1]
X= X.astype('float32')

# create two models                 
model1= LinearRegression()
model2 = lgb.LGBMRegressor(n_estimators=5, num_leaves=10, min_child_samples=1) 
ser_model1= X['x']==0.0
model1.fit(X[ser_model1], y[ser_model1])
model2.fit(X[~ser_model1], y[~ser_model1])

# define a class that mocks the model interface
class CombinedModel:
    def __init__(self, model1, model2):
        self.model1= model1
        self.model2= model2
        
    def predict(self, X, **kwargs):
        ser_model1= X['x']==0.0
        return pd.concat([
                pd.Series(self.model1.predict(X[ser_model1]), index=X.index[ser_model1]),
                pd.Series(self.model2.predict(X[~ser_model1]), index=X.index[~ser_model1])
            ]
        ).sort_index()

# create a model with the two trained sum models
# and pickle it
model= CombinedModel(model1, model2)
model.predict(X)
with open('model.pkl', 'wb') as fp:
    pkl.dump(model, fp)
model= model1= model2= None

# test load it
with open('model.pkl', 'rb') as fp:
    model= pkl.load(fp)
model.predict(X)

如果你愿意,当然你也可以在上面的类中实现一个 fit 方法,它只是调用两个模型。如果您实现了必要的方法,您甚至可以在 sklearn 管道中使用此类。


0
投票

您可以使用集成投票分类器,它将考虑两个模型的输出并给出适当的输出。 链接 - https://machinelearningmastery.com/voting-ensembles-with-python/

© www.soinside.com 2019 - 2024. All rights reserved.