8.4 Oracle Machine Learning for Pythonモデルのエクスポート

Pythonからomlモデルをエクスポートし、SQLでスコアリングできます。

モデルのエクスポート

OML4Pyアルゴリズム・モデルのexport_sermodel関数を使用すると、シリアライズされた形式でモデルをエクスポートできます。その後、そのモデルをSQLでスコアリングできます。モデルを永続表に保存するには、新しい表の名前を渡す必要があります。モデルがパーティション化されている場合は、オプションで、エクスポートする個々のパーティションを選択できます。選択しない場合は、すべてのパーティションがエクスポートされます。

ノート:

モデル構築の際にデータに適用したデータ変換は、インポートしたモデルでスコアリングする際にもデータに適用する必要があります。

例8-2 トレーニングしたoml.svmモデルをデータベース表にエクスポート

この例では、irisデータセットを使用してx変数とy変数を作成します。その後、永続データベース表IRISとoml.DataFrameオブジェクトoml_irisを表のプロキシとして作成します。

この例では、irisデータセットを前処理し、データセットをトレーニング・データとテスト・データに分割します。次に、データセットのトレーニング・データに従ってoml.svmモデルを適合させ、適合したモデルをシリアライズされた形式でデータベース内のsvm_sermodという名前の新しい表に保存します。

import oml
import pandas as pd
from sklearn import datasets

# 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'])

try:
    oml.drop('IRIS')
    oml.drop('IRIS_TEST_DATA')
except: 
    pass

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

df = oml.sync(table = "IRIS").pull()

# Add a case identifier column.
df.insert(0, 'ID', range(0,len(df)))

# Create training data and test data.
IRIS_TMP = oml.push(df).split()
train_x = IRIS_TMP[0].drop('Species')
train_y = IRIS_TMP[0]['Species']
test_dat = IRIS_TMP[1]

# Create the iris_test_data database table.
oml_test_dat = oml.create(test_dat.pull(), table = "IRIS_TEST_DATA")

# Create an oml SVM model object.
svm_mod = oml.svm('classification',
                  svms_kernel_function = 
                    'dbms_data_mining.svms_linear')
              
# Fit the SVM model with the training data.
svm_mod = svm_mod.fit(train_x, train_y, case_id = 'ID')

# Export the oml.svm model to a new table named 'svm_sermod' 
# in the database.
svm_export = svm_mod.export_sermodel(table='svm_sermod')
type(svm_export)

# Show the first 10 characters of the BLOB content from the 
# model export.
svm_export.pull()[0][1:10]

この例のリスト

>>> import oml
>>> import pandas as pd
>>> from sklearn import datasets
>>>
>>> # 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'])
>>>
>>> try:
...    oml.drop('IRIS')
...    oml.drop('IRIS_TEST_DATA')
...except: 
...    pass
>>> # Create the IRIS database table.
... oml_iris = oml.create(pd.concat([x, y], axis=1), table = 'IRIS')
>>>
>>> df = oml.sync(table = "IRIS").pull()
>>>
>>> # Add a case identifier column.
... df.insert(0, 'ID', range(0,len(df)))
>>> 
>>> # Create training data and test data.
... IRIS_TMP = oml.push(df).split()
>>> train_x = IRIS_TMP[0].drop('Species')
>>> train_y = IRIS_TMP[0]['Species']
>>> test_dat = IRIS_TMP[1]
>>>
>>> # Create the iris_test_data database table.
... oml_test_dat = oml.create(test_dat.pull(), table = "IRIS_TEST_DATA")
>>>
>>> # Create an oml SVM model object.
... svm_mod = oml.svm('classification',
...                   svms_kernel_function = 
                        'dbms_data_mining.svms_linear')
>>>
>>> # Fit the SVM model with the training data.
... svm_mod = svm_mod.fit(train_x, train_y, case_id='ID')
>>>
>>> # Export the oml.svm model to a new table named 'svm_sermod' 
... # in the database.
... svm_export = svm_mod.export_sermodel(table='svm_sermod')
>>> type(svm_export)
<class 'oml.core.bytes.Bytes'>
>>>
>>> # Show the first 10 characters of the BLOB content from the 
... # model export.
... svm_export.pull()[0][1:10]
b'\xff\xfc|\x00\x00\x02\x9c\x00\x00'

モデルのインポート

SQLでは、DBMS_DATA_MINING.IMPORT_SERMODELプロシージャを使用して、シリアライズされた形式のOML4PyモデルをOracle Machine Learning for SQLモデルにインポートできます。このプロシージャには、モデルをエクスポートした表のBLOBコンテンツと作成するモデルの名前を渡します。インポート・プロシージャでは、モデルをスコアリングできます。モデルの詳細を問い合せるために必要なモデルのビューや表は作成されません。SQLファンクションPREDICTIONを使用して、インポートしたモデルをテスト・データに適用し、予測結果を取得できます。

例8-3 シリアライズされたSVMモデルをSQLでOML4SQLモデルとしてインポート

この例では、SVM分類モデルのシリアライズ・コンテンツをsvm_sermod表から取得します。IMPORT_SERMODELプロシージャを使用して、表のコンテンツを含むmy_iris_svm_classifierという名前のモデルを作成します。また、新しくインポートしたモデルmy_iris_svm_classifierを使用して、iris_test_data表に保存されているテスト・データを予測し、予測結果をターゲット・クラスと比較します。

-- After starting SQL*Plus as the OML4Py user.
-- Import the model from the serialized content.

DECLARE
  v_blob blob;
  
BEGIN
  SELECT SERVAL INTO v_blob FROM "svm_sermod";
  dbms_data_mining.import_sermodel(v_blob, 'my_iris_svm_classifier');
END;
/

-- Set the output column format.
column TARGET_SPECIES format a15
column PREDICT_SPECIES format a15

-- Make predictions and display cases where mod(ID,3) equals 0.
SELECT ID, "Species" AS TARGET_SPECIES,
  PREDICTION(my_iris_svm_classifier USING "Sepal_Length", "Sepal_Width", 
             "Petal_Length", "Petal_Width") 
             AS PREDICT_SPECIES
             FROM "IRIS_TEST_DATA" WHERE MOD(ID,3) = 0;
           
-- Drop the imported model
BEGIN
  DBMS_DATA_MINING.DROP_MODEL(model_name => 'my_iris_svm_classifier');
END;
/

予測によって、次の結果が生成されます。

ID TARGET_SPECIES PREDICT_SPECIES
-- -------------- ---------------
 0 setosa         setosa
24 setosa         setosa
27 setosa         setosa
33 setosa         setosa
36 setosa         setosa
39 setosa         setosa
48 setosa         setosa
54 versicolor     versicolor
57 versicolor     versicolor
93 versicolor     versicolor
114 virginica     virginica
120 virginica     virginica
132 virginica     virginica
13 rows selected.