自定义函数用于PMMLPipeline中

预测模型标记语言(Predictive Model Markup Language,PMML)是一种可以呈现预测分析模型的事实标准语言。标准东西的好处就是,各种开发语言都可以使用相应的包,把模型文件转成这种中间格式,而另外一种开发语言,可以使用相应的包导入该文件做线上预测。

不过,当训练和预测使用同一种开发语言的时候,PMML 就没有必要使用了,因为任何中间格式都会牺牲掉独有的优化。公司内部一般是采用Python语言做模型训练,线上采用 Java 载入模型做预测。

离线部分负责模型训练和导出模型,线上导入模型并且做预测。当然特征工程部分主要做特征变换,例如 分桶,单值编码,归一化等。

from sklearn_pandas import DataFrameMapper
from sklearn2pmml import PMMLPipeline
heart_data = pandas.read_csv("heart.csv")
#用Mapper定义特征工程
mapper = DataFrameMapper([
    (['sbp'], MinMaxScaler()),
    (['tobacco'], MinMaxScaler()),
    ('ldl', None),
    ('adiposity', None),
    (['famhist'], LabelBinarizer()),
    ('typea', None),
    ('obesity', None),
    ('alcohol', None),
    (['age'], FunctionTransformer(np.log)),
]) 

#用pipeline定义使用的模型,特征工程等
pipeline = PMMLPipeline([
(‘mapper’, mapper),
(“classifier”, linear_model.LinearRegression())
])

pipeline.fit(heart_data[heart_data.columns.difference([“chd”])], heart_data[“chd”])
#导出模型文件
sklearn2pmml(pipeline, “lrHeart.xml”, with_repr = True)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

在工作中可能需要将自定义函数装入pipeline,并最终生成pmml文件。
示例代码如下:

#模仿MinMaxScaler等类,构造自定义类
class A:
	def fit(self,x,params):
		pass
	def predict(self,x):
		return 3*x
 pipeline = PMMLPipeline([('test',A())])
 pipeline.predict(1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

结果如下:
自定义函数用于PMMLPipeline中