2017-08-01 51 views
0

首先,我创建两个ML算法并将它们保存到两个单独的文件中。请注意,这两种模型都基于相同的数据框。 feature_1feature_2是从相同数据集中提取的不同特征组。保存并加载pyspark中的两个ML模型

import sys 
from pyspark.ml.classification import RandomForestClassificationModel 

trainer_1 = RandomForestClassifier(featuresCol="features_1") 
trainer_2 = RandomForestClassifier(featuresCol="features_2") 
model_1 = trainer_1.fit(df_training_data) 
model_2 = trainer_2.fit(df_training_data) 

model_1.save(sys.argv[1]) 
model_2.save(sys.argv[2]) 

然后,当我后来想使用的机型,我必须从各自的路径加载他们两个,f.ex.提供的路径通过sys.argv。

import sys 
from pyspark.ml.classification import RandomForestClassificationModel 

model_1 = RandomForestClassificationModel.load(sys.argv[1]) 
model_2 = RandomForestClassificationModel.load(sys.argv[2]) 

我想要的是一个优雅的方式,可以将这两个模型作为一个整体保存在同一个路径中。我主要这样做,以便用户在每次保存和加载时都不必跟踪两个单独的路径名。这两个模型是紧密相连的,并且通常会一起创建和使用,因此它们只是一种模型。

这是管道的目的是什么?

回答

0

我想通过将它们放在一个文件夹中的方式来做到这一点。然后用户只需提供并知道该文件夹的路径。

import sys 
import os 
from pyspark.ml.classification import RandomForestClassificationModel 

trainer_1 = RandomForestClassifier(featuresCol="features_1") 
trainer_2 = RandomForestClassifier(featuresCol="features_2") 
model_1 = trainer_1.fit(df_training_data) 
model_2 = trainer_2.fit(df_training_data) 

path = 'model_rfc' 
os.mkdir(path) 
model_1.save(os.path.join(sys.argv[1], 'model_1')) 
model_2.save(os.path.join(sys.argv[1], 'model_2')) 

名称model_1model_2是硬编码的,而不是需要由用户是已知的。

import sys 
import os 
from pyspark.ml.classification import RandomForestClassificationModel 

model_1 = RandomForestClassificationModel.load(os.path.join(sys.argv[1], 'model_1')) 
model_2 = RandomForestClassificationModel.load(os.path.join(sys.argv[1], 'model_2')) 

这应该解决问题。这是做这件事的最好方法吗?或者可以使用Spark库中的功能将模型捆绑在一起更好?