10.4.3 指定したデータに対するユーザー定義Python関数の実行

oml.table_apply関数を使用して、dataパラメータで指定したデータに対してPython関数を実行します。

oml.table_apply関数は、データベース環境によって生成および管理されるPythonエンジンでユーザー定義Python関数を実行します。funcパラメータでは、Python関数を指定することも、OML4Pyスクリプト・リポジトリ内のユーザー定義Python関数の名前を指定することもできます。

この関数の構文は次のとおりです。

oml.table_apply(data, func, func_owner=None, graphics=False, **kwargs)

data引数は、func関数が操作するデータを含むoml.DataFrameです。

func引数は、実行する関数です。これには次のいずれかを指定できます。

  • Python関数

  • OML4Pyスクリプト・リポジトリ内のユーザー定義Python関数の名前を表す文字列

  • Python関数を定義する文字列
  • oml.script.load関数によって返されるoml.script.script.Callableオブジェクト

オプションのfunc_owner引数は文字列またはNone (デフォルト)で、引数funcが登録済ユーザー定義Python関数名の場合に、登録済ユーザー定義Python関数の所有者を指定します。

graphics引数は、イメージを検索するかどうかを指定するブール値です。デフォルト値は、Falseです。

**kwargsパラメータを使用すると、func関数に追加の引数を渡すことができます。oml_で始まる特殊な制御引数は、funcで指定された関数に渡されるのではなく、関数の実行前または実行後の動作を制御します。

関連項目: 特殊な制御引数について

oml.table_apply関数は、Pythonオブジェクトまたはoml.embed.data_image._DataImageを返します。ユーザー定義Python関数でイメージがレンダリングされない場合、oml.table_applyは、関数によって返されたPythonオブジェクトを返します。それ以外の場合は、oml.embed.data_image._DataImageオブジェクトを返します。

関連項目: 出力について

例10-7 oml.table_apply関数の使用方法

この例では、インメモリー・データを使用して回帰モデルを構築した後、oml.table_apply関数を使用し、IRIS表の最初の10行でそのモデルを使用して予測を行います。

import oml
import pandas as pd
from sklearn import datasets 
from sklearn import linear_model

# Load the iris data set and create a pandas.DataFrame for it.
iris = datasets.load_iris()

x = pd.DataFrame(iris.data, 
                 columns = ['Sepal_Length','Sepal_Width',
                            'Petal_Length','Petal_Width'])
y = pd.DataFrame(list(map(lambda x: 
                           {0: 'setosa', 1: 'versicolor', 
                            2:'virginica'}[x], iris.target)), 
                 columns = ['Species'])

# Drop the IRIS database table if it exists.
try:
    oml.drop('IRIS')
except: 
    pass

# Create the IRIS database table.
oml_iris = oml.create(pd.concat([x, y], axis=1), table = 'IRIS')

# Build a regression model using in-memory data.
iris = oml_iris.pull()
regr = linear_model.LinearRegression()
regr.fit(iris[['Sepal_Width', 'Petal_Length', 'Petal_Width']], 
         iris[['Sepal_Length']])
regr.coef_

# Use oml.table_apply to predict using the model on the first 10 
# rows of the IRIS table.
def predict(dat, regr):
    import pandas as pd
    pred = regr.predict(dat[['Sepal_Width', 'Petal_Length', 
                             'Petal_Width']])
    return pd.concat([dat,pd.DataFrame(pred)], axis=1)

res = oml.table_apply(data=oml_iris.head(n=10), 
                      func=predict, regr=regr)
res

この例のリスト

>>> import oml
>>> import pandas as pd
>>> from sklearn import datasets 
>>> from sklearn import linear_model
>>> 
>>> # Load the iris data set and create a pandas.DataFrame for it.
... iris = datasets.load_iris()
>>>
>>> x = pd.DataFrame(iris.data, 
...                  columns = ['Sepal_Length','Sepal_Width',
...                             'Petal_Length','Petal_Width'])
>>> y = pd.DataFrame(list(map(lambda x: 
...                            {0: 'setosa', 1: 'versicolor', 
...                             2:'virginica'}[x], iris.target)), 
...                  columns = ['Species'])
>>>
>>> # Drop the IRIS database table if it exists.
... try:
...     oml.drop('IRIS')
... except: 
...     pass
>>>
>>> # Create the IRIS database table.
... oml_iris = oml.create(pd.concat([x, y], axis=1), table = 'IRIS')
>>>
>>> # Build a regression model using in-memory data.
... iris = oml_iris.pull()
>>> regr = linear_model.LinearRegression()
>>> regr.fit(iris[['Sepal_Width', 'Petal_Length', 'Petal_Width']], 
...          iris[['Sepal_Length']])
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, 
         normalize=False)
>>> regr.coef_
array([[ 0.65083716,  0.70913196, -0.55648266]])
>>>
>>> # Use oml.table_apply to predict using the model on the first 10
... # rows of the IRIS table.
... def predict(dat, regr):
... import pandas as pd
... pred = regr.predict(dat[['Sepal_Width', 'Petal_Length', 
...                          'Petal_Width']])
... return pd.concat([dat,pd.DataFrame(pred)], axis=1)
...
>>> res = oml.table_apply(data=oml_iris.head(n=10), 
...                       func=predict, regr=regr)
>>> res   Sepal_Length  Sepal_Width  Petal_Length  Petal_Width
0           4.6          3.6             1          0.2
1           5.1          2.5             3          1.1
2           6.0          2.2             4          1.0
3           5.8          2.6             4          1.2
4           5.5          2.3             4          1.3
5           5.5          2.5             4          1.3
6           6.1          2.8             4          1.3
7           5.7          2.5             5          2.0
8           6.0          2.2             5          1.5
9           6.3          2.5             5          1.9

      Species         0
0      setosa  4.796847
1  versicolor  4.998355
2  versicolor  5.567884
3  versicolor  5.716923
4  versicolor  5.466023
5  versicolor  5.596191
6   virginica  5.791442
7   virginica  5.915785
8   virginica  5.998775
9   virginica  5.971433