11.5.7.2 ユーザー定義Python関数の作成および格納

oml.script.create関数を使用して、ユーザー定義Python関数をスクリプト・リポジトリに追加します。

oml.script.create関数を使用すると、単一のユーザー定義Python関数をOML4Pyスクリプト・リポジトリに格納できます。その後、ユーザー定義Python関数を、Embedded Python Execution関数oml.do_evaloml.group_applyoml.index_applyoml.row_applyおよびoml.table_applyfunc引数として指定できます。

ユーザー定義Python関数は、プライベートまたはグローバルのいずれかにできます。プライベート・ユーザー定義Python関数は、所有者が他のユーザーに読取り権限を付与しないかぎり、所有者のみが使用できます。グローバル・ユーザー定義Python関数は、すべてのユーザーが使用できます。

oml.script.createの構文は次のとおりです。

oml.script.create(name, func, is_global=False, overwrite=False)

name引数は、Pythonスクリプト・リポジトリ内のユーザー定義Python関数の名前を指定する文字列です。

func引数は、実行するPython関数です。この引数には、Python関数またはPython関数の定義を含む文字列を指定できます。readlineがコマンド履歴を取得できない場合は、インタラクティブ・セッションで文字列を指定する必要があります。

is_global引数は、グローバル・ユーザー定義Python関数を作成するかどうかを指定するブール値です。デフォルト値はFalseで、ユーザー定義Python関数が現行のセッション・ユーザーのみが使用できるプライベート関数であることを示します。is_globalTrueの場合は、関数がグローバルであり、すべてのユーザーに読取り権限と実行権限があることを示します。

overwrite引数は、ユーザー定義Python関数がすでに存在する場合に上書きするかどうかを指定するブール値です。デフォルト値は、Falseです。

例11-11 oml.script.create関数の使用

この例では、スクリプト・リポジトリにユーザー定義Python関数を2つ格納します。次に、oml.script.dir関数の様々な引数を使用して、スクリプト・リポジトリの内容をリストします。

irisデータセットをseabornライブラリからPandas DataFrameとしてロードします。oml.create関数を使用して、IRISデータベース表およびこの表のプロキシ・オブジェクトを作成します。

%python

from sklearn import datasets
import pandas as pd
import oml

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

# Create objects containing data for the user-defined functions to use.
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'])
                 
# Create the IRIS database table and the proxy object for the table.

try:
  oml.drop(table="IRIS")
except:
  pass
  
oml_iris = oml.create(pd.concat([x, y], axis=1), table = 'IRIS')

ユーザー定義関数build_lm1を作成し、oml.script.create関数を使用してOML4Pyスクリプト・リポジトリに格納します。パラメータ"build_lm1"は、ユーザー定義関数の名前を指定する文字列です。パラメータfunc=build_lm1は、実行するPython関数です。Embedded Python Executionでユーザー定義Python関数を実行します。

%python

# Define a function.

build_lm1 = '''def build_lm1(dat):
  from sklearn import linear_model
  regr = linear_model.LinearRegression()
  import pandas as pd
  dat = pd.get_dummies(dat, drop_first=True)
  X = dat[["Sepal_Width", "Petal_Length", "Petal_Width", "Species_versicolor", "Species_virginica"]]
  y = dat[["Sepal_Length"]]
  regr.fit(X, y)
  return regr'''

# Create a private user-defined Python function.
oml.script.create("build_lm1", func=build_lm1, overwrite=True)

# Run the user-defined Python function in embedded Python execution
res = oml.table_apply(oml_iris, func="build_lm1", oml_input_type="pandas.DataFrame")

res
res.coef_

出力は次のようになります。

array([[ 0.49588894,  0.82924391, -0.31515517, -0.72356196, -1.02349781]])

別のユーザー定義関数build_lm2を定義し、この関数をグローバル・スクリプトとしてOML4Pyスクリプト・リポジトリに格納します。Embedded Python Executionでユーザー定義Python関数を実行します。

%python

# Define another function

build_lm2 = '''def build_lm2(dat):
  from sklearn import linear_model
  regr = linear_model.LinearRegression()
  X = dat[["Petal_Width"]]
  y = dat[["Petal_Length"]]
  regr.fit(X, y)
  return regr'''

# Save the function as a global script to the script repository, overwriting any existing function with the same name.
oml.script.create("build_lm2", func=build_lm2, is_global=True,  overwrite=True)

res = oml.table_apply(oml_iris, func="build_lm2", oml_input_type="pandas.DataFrame")
res

出力は次のようになります。

LinearRegression()

現在のユーザーのみが使用できるスクリプト・リポジトリ内のユーザー定義Python関数をリストします。

%python

oml.script.dir()

出力は、次のようなものです。


                name  ...                date
0          build_lm1  ... 2022-12-15 19:02:44
1          build_mod  ... 2022-12-12 23:02:31
2      myFitMultiple  ... 2022-12-14 22:30:43
3  sample_iris_table  ... 2022-12-14 22:21:24

[4 rows x 4 columns]

現行ユーザーが使用できるすべてのユーザー定義Python関数をリストします。

%python

oml.script.dir(sctype='all')

出力は、次のようなものです。


     owner  ...                date
0   PYQSYS  ... 2022-02-11 06:06:44
1   PYQSYS  ... 2022-10-19 16:59:50
2   PYQSYS  ... 2022-10-19 16:59:52
3   PYQSYS  ... 2022-10-19 16:59:53

すべてのユーザーが使用できるユーザー定義Python関数をリストします。

%python

oml.script.dir(sctype='global')

出力は、次のようなものです。


                   name  ...                date
0                 GLBLM  ... 2022-02-11 06:06:44
1         RandomRedDots  ... 2022-10-19 16:59:50
2        RandomRedDots2  ... 2022-10-19 16:59:52
3        RandomRedDots3  ... 2022-10-19 16:59:53
4                  TEST  ... 2021-08-13 17:37:02
5                 TEST4  ... 2021-08-13 17:42:49
6              TEST_FUN  ... 2021-08-13 22:38:54