About Embedded Python Execution
Embedded Python execution is a feature of Oracle Machine Learning for Python (OML4Py) that allows users to invoke user-defined Python functions directly in an Oracle database instance.
See Embedded Python Execution in Oracle Machine Learning for Python User’s Guide for more information.
To demonstrate how to use embedded execution, the following example prepares a spatial regression model. This model is used in the subsequent topics in this chapter which describe how to invoke a Python function using embedded execution, including creating a function that uses that model to make predictions, and then using that function for embedded execution from Python, SQL and REST.
The example steps are as follows:
- Defines the regressor model using the
block_groups
SpatialDataFrame
andSpatialErrorRegressor
. - Creates a Spatial Pipeline with a pre-processing step to standardize the data and the regressor as the last step.
- Trains the model using
MEDIAN_INCOME
as the target variable.
from oraclesai.preprocessing import spatial_train_test_split
from oraclesai.weights import KNNWeightsDefinition
from oraclesai.regression import SpatialErrorRegressor
from oraclesai.pipeline import SpatialPipeline
from sklearn.preprocessing import StandardScaler
# Define variables
X = block_groups[["MEDIAN_INCOME", "MEAN_AGE", "HOUSE_VALUE", "geometry"]]
# Define training and test sets
X_train, X_test, _, _, _, _ = spatial_train_test_split(X, y="MEDIAN_INCOME", test_size=0.2, random_state=32)
# Create instance of SpatialErrorRegressor
spatial_error_model = SpatialErrorRegressor(spatial_weights_definition=KNNWeightsDefinition(k=5))
# Add the model into a Spatial Pipeline along with a pre-processing step
spatial_error_pipeline = SpatialPipeline([("scaler", StandardScaler()), ("spatial_error", spatial_error_model)])
# Train the model with MEDIAN_INCOME as the target variable
spatial_error_pipeline.fit(X_train, "MEDIAN_INCOME")
Once the model is trained, save the model into an OML4Py datastore.
oml.ds.save({'spatial_error': spatial_error_pipeline},
'spatial_error_ds', description='some description',
overwrite=True)