簡體   English   中英

在 sklearn2pmml PMMLipeline 中自定義 function

[英]Custom function in sklearn2pmml PMMLPipeline

我正在嘗試創建一個機器學習 model,以根據中風患者對各種問卷和評估的回答提出治療建議。 例如,患者將被要求對手指、肘部、肩部和胸肌的僵硬程度進行評分(每個評分為 0 到 100)或回答 14 個與心理健康相關的問題(每個評分為 0 到 3 )。

我想大致如下創建一個sklearn管道:

1. 匯總患者反應。 例如,四個僵硬反應應該被平均以創建一個單一的“僵硬”值,而十四個心理健康問題應該被總結為一個單一的“心理健康”值。 “剛度”和“心理健康”值將成為 model 中的特征。

2. 一旦以這種方式聚合了特征,決策樹分類器就會在標記數據上進行訓練,以將每個患者分配給適當的治療。

3.將訓練好的流水線導出為pmml文件進行生產

我認為這必須通過一些這樣的代碼來實現:

from sklearn2pmml.pipeline import PMMLPipeline

from sklearn2pmml import sklearn2pmml

from sklearn.tree import DecisionTreeClassifier

from somewhere import Something

pipeline = PMMLPipeline([
    ("input_aggregation", Something()),
    ("classifier", DecisionTreeClassifier())
])

pipeline.fit(patient_input, therapy_labels)
 
sklearn2pmml(pipeline, "ClassificationPipeline.pmml", with_repr = True)

我一直在研究文檔,我可以弄清楚將 PCA 應用於一組列,但不知道如何做一些簡單的事情,比如通過求和或平均來折疊一組列。 有人對我如何做到這一點有任何提示嗎?

謝謝你的幫助。

您只需要定義一個自定義 function 並在Pipeline中使用它。

這是完整的代碼:

from sklearn.preprocessing import FunctionTransformer
import numpy as np
from sklearn2pmml import make_pmml_pipeline

# fake data with 7 columns
X = np.random.rand(10,7)

n_rows = X.shape[0]

def custom_function(X):
    #averiging 4 first columns, sums the others, column-wise
    return np.concatenate([np.mean(X[:,0:5],axis = 1).reshape(n_rows,1), np.sum(X[:,5:],axis=1).reshape(n_rows,1)],axis = 1)

# Now, if you run: `custom_function(X)` it should return an array (10,2).

pipeline = make_pmml_pipeline(
FunctionTransformer(custom_function),
    )

示例代碼:

from sklearn_pandas import DataFrameMapper
from sklearn2pmml.preprocessing import Aggregator

pipeline = PMMLPipeline([
  ("mapper", DataFrameMapper([
    (["stiffness_1", "stiffness_2", "stiffness_3", "stiffness_4"], Aggregator(function = "mean")),
    (["mental_health_1", "mental_health2", .., "mental_health_14"], Aggregator(function = "sum"))
  ])),
  ("classifier", DecisionTreeClassifier())
])
pipeline.fit(X, y)

說明 - 您可以使用sklearn_pandas.DataFrameMapper定義列組,並對它應用轉換。 為了轉換到 PMML 工作,您需要提供變壓器 class,而不是直接 function。 也許您所有的轉換需求都由sklearn2pmml.preprocessing.Aggregator轉換器 class 處理。 如果沒有,您可以隨時定義自己的。

雖然@makis 提供了一個 100% 有效的 Python 示例,但它不適用於 Python 到 PMML 的情況,因為轉換器無法解析/處理自定義 Python 函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM