例で使用されるスクリプト
これらのスクリプトには、Embedded Python Executionの例のREST APIで使用されるユーザー定義関数を作成するためのPythonコードが含まれています。Embedded Python Execution関数エンドポイントのREST APIで使用するには、スクリプトをPython関数ではなく文字列としてOracle Machine Learning for Python (OML4Py)スクリプト・リポジトリに保存する必要があります。
スクリプトの作成例およびOML4Py関数の使用例は、Autonomous DatabaseサービスのOMLノートブックを参照してください。
一部のスクリプトで使用されるデータ
次のPythonコードでは、一部のスクリプトで使用されるデータを含むoml_iris
オブジェクトを作成します。
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()
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.
oml_iris = oml.create(pd.concat([x, y], axis=1), table = 'IRIS')
compute_random_mean
compute_random_mean
関数は、乱数セットの平均を返します。次では、スクリプトを定義し、スクリプト・リポジトリに格納します。
compute_random_mean = """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])"""
oml.script.create("compute_random_mean", compute_random_mean, is_global=True, overwrite=True)
group_count
group_count
関数は、Species列の各カテゴリのカウントを、Sepal_Length列でソートした結果とともに返します。この例では、group_count
関数を定義する文字列を作成し、スクリプト・リポジトリに保存します。
この関数は、oml_iris
オブジェクトのデータを使用します。
次では、スクリプトを定義し、スクリプト・リポジトリに格納します。
group_count = """def group_count(dat):
import oml
import pandas as pd
return pd.DataFrame([(dat["Species"][0], dat["Sepal_Length"][0], dat.shape[0])],
columns = ["Species", "Sepal_Length", "Count"])"""
oml.script.create("group_count", func=group_count, is_global=True, overwrite=True)
my_predict
my_predict
関数は、LinearRegressionモデルに基づいて予測を返します。
次の例では、LinearRegressionモデルを作成してOML4Pyデータストアに格納します。次に、my_predict
関数を定義し、スクリプト・リポジトリに格納します。
from sklearn import linear_model
# 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_
oml.ds.save(objs={'regr':regr}, name="ds_regr", grantable=True, overwrite=True)
my_predict = """def my_predict(dat):
import pandas as pd
import oml
obj_dict = oml.ds.load(name="ds_regr", to_globals=False)
regr = obj_dict["regr"]
pred = regr.predict(dat[['Sepal_Length',
'Sepal_Width',
'Petal_Length']])
return pd.concat([dat[['Species', 'Petal_Width']],
pd.DataFrame(pred,
columns=['Pred_Petal_Width'])],
axis=1)"""
oml.script.create("my_predict", func=my_predict, is_global=True, overwrite=True)
pred_lm
pred_lm
関数は、LinearRegressionモデルから予測を返します。
次の例では、pred_lm
関数を定義してスクリプト・リポジトリに格納します。
pred_lm = """def pred_lm(dat):
from sklearn import linear_model
import oml
lm = linear_model.LinearRegression()
X = dat[["Petal_Width"]]
y = dat[["Petal_Length"]]
mod = lm.fit(X, y)
pred = mod.predict(dat[["Petal_Width"]])"""
oml.script.create("pred_lm", func=pred_lm, is_global=True, overwrite=True)
RandomRedDots
RandomRedDots
関数は、単純なDataFrame
を作成し、2つのランダムな赤い点のプロットを生成します。この例では、関数を定義し、スクリプト・リポジトリにスクリプトとして格納します。
RandomRedDots = """def RandomRedDots (num_dots_1=100, num_dots_2=10):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
d = {'id': range(1,10), 'val': [x/100 for x in range(1,10)]}
df = pd.DataFrame(data=d)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.scatter(range(0,int(num_dots_1)), np.random.rand(int(num_dots_1)),c='r')
fig.suptitle("Random Red Dots")
fig2 = plt.figure(2)
ax2 = fig2.add_subplot(111)
ax2.scatter(range(0,int(num_dots_2)), np.random.rand(int(num_dots_2)),c='r')
fig2.suptitle("Random Red Dots")
return df"""
oml.script.create("RandomRedDots", func=RandomRedDots, is_global=True, overwrite=True)
return_df
return_df
関数は、pandas.DataFrame
を返します。
次では、スクリプトを定義し、スクリプト・リポジトリに格納します。
return_df = """def return_df(num, scale):
import pandas as pd
id = list(range(0, int(num)))
res = [i/scale for i in id]
return pd.DataFrame({"ID":id, "RES":res})"""
oml.script.create("return_df", func=return_df, is_global=False, overwrite=True)