12.5.6 ユーザー定義Python関数の複数回実行

oml.index_apply関数を使用して、データベース環境によって生成されたPythonエンジンでPython関数を複数回実行します。

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

oml.index_apply(times, func, func_owner=None, parallel=None, graphics=False, **kwargs)

times引数は、func関数を実行する回数を指定するintです。

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

  • Python関数

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

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

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

parallel引数は、Embedded Python Executionジョブで使用する推奨並列度を指定するブール値、intまたはNone (デフォルト)です。次の値のいずれかを指定できます。

  • 特定の並列度では、1以上の正の整数

  • 並列度なしの場合はFalseNoneまたは0

  • デフォルトのデータ並列度の場合はTrue

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

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

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

例12-10 oml.index_apply関数の使用

この例では、乱数のセットの平均を指定の回数返す関数を定義します。

import oml
import pandas as pd

def compute_random_mean(index):
    import numpy as np
    import scipy
    from statistics import mean 
    np.random.seed(index)
    res = np.random.random((100,1))*10
    return mean(res[1])
res = oml.index_apply(times=10, func=compute_random_mean)
type(res)
res

この例のリスト

>>> import oml
>>> import pandas as pd
>>>
>>> def compute_random_mean(index):
...     import numpy as np
...     import scipy
...     from statistics import mean 
...     np.random.seed(index)
...     res = np.random.random((100,1))*10
...     return mean(res[1])
...
>>> res = oml.index_apply(times=10, func=compute_random_mean)
>>> type(res)
<class 'list'>
>>> res
[7.203244934421581, 0.25926231827891333, 7.081478226181048,
5.4723224917572235, 8.707323061773764, 3.3197980530117723,
7.7991879224011464, 9.68540662820932, 5.018745921487388, 
0.207519493594015]