Showing posts with label Oracle Machine Learning. Show all posts
Showing posts with label Oracle Machine Learning. Show all posts

Friday, May 20, 2022

Oracle’s latest MySQL HeatWave cloud database simplifies use of machine learning

Oracle’s, MySQL HeatWave Cloud Database, Machine Learning, Oracle Database Exam Prep, Database Preparation, Database Career, Database Skills, Database Jobs

Machine learning is delivering real profits to more companies by automating decision-making and enhancing digital products. Yet the flood of data pouring into these statistical prediction systems has created another problem: How to get reams of data ready for powerful computers to analyze amid of a dearth of machine learning expertise.

Twenty-seven percent of companies surveyed by McKinsey & Company last year reported that at least 5% of their operating profit was attributable to artificial intelligence (AI) usage, up from 22% of companies in 2020. In the survey of 1,843 global companies, 56% said they’re using AI in at least one area, chiefly to automate customer service, improve products, segment customers, and model risk.

Yet organizations have their data hived away in myriad databases with different departments using different approaches. Ferrying information to machine learning systems and putting it in a form that’s ready to analyze adds cost and time drag. “AI needs data, and for enterprises, moving data around is cumbersome, slow, and expensive,” says Holger Mueller, vice president and principal analyst at tech advisory firm Constellation Research.

The latest version of Oracle MySQL offers a better approach: Build machine learning models into the database, so you can leave the data where it is. “Bringing the machine learning to the data is a smart architecture and design choice,” Mueller says.

First released two years ago, MySQL HeatWave runs as a service on Oracle Cloud Infrastructure and lets users of the widely adopted MySQL Database combine transaction processing and data analysis in a single database. It runs database queries in computer memory to increase their speed.

Machine learning built in

The latest iteration of the software puts machine learning capabilities inside the MySQL HeatWave Database and can automate the process of creating and training ML models, then unleashing them on live data. MySQL HeatWave can train models on available data and tune them to improve accuracy based on how well they predict outcomes. That means when organizations’ data is inside MySQL Database, as much of it already is, they can skip the work of extracting it, changing its format, and loading it into another ML system—a process that can take hours. Developers and data analysts can also build ML models using the familiar database SQL language without having to learn new tools or languages.

“HeatWave is easy to use, period,” says Matt Kimball, an analyst at Moor Insights & Strategy. “The biggest barrier to adoption in the world of ML is complexity—organizations can’t find the right talent and the best hardware. With HeatWave, they can realize the promise of machine learning more quickly.”

Sales of cloud data warehouses are expected to grow sharply this year as businesses use them for tasks, such as managing supply chains, hunting for sales opportunities, or analyzing medical data. The systems tap databases, the web, business applications, and sensors to gather data in one place, analyze it, and give companies a clearer view of operations, sales, and customer behavior.

Oracle published machine learning benchmarks performed across a large number of publicly available machine learning datasets using different cloud providers—research noted by several analysts as an industry first. On average, on the smallest cluster, MySQL HeatWave ML-trained machine learning models were 25 times faster at 1% of the cost of Amazon Web Services’ (AWS) Redshift ML. The benchmarks based on public ML datasets show MySQL HeatWave delivering better price performance than Google’s BigQuery, Microsoft Azure Synapse, and Snowflake, as well as AWS’s Redshift with its query accelerator.

Less time spent using a cloud service can mean lower computing bills, and the new MySQL HeatWave version also lets customers scale up without downtime.

Last year, Oracle introduced software called My SQL Autopilot for using AI to optimize and automate the MySQL HeatWave service. “Autopilot used machine learning to operate the database. Now it’s about using ML on the data,” says Mueller.

MySQL HeatWave can also take models tuned in MySQL and use them to answer queries from popular machine learning notebook services for code and data, such as Jupyter and Apache Zeppelin.

Oracle plans to release MySQL HeatWave to run on other cloud providers’ infrastructure, including AWS, Oracle Executive Chairman and Chief Technology Officer Larry Ellison said during a conference call with financial analysts last month.

Edward Screven, Oracle’s chief corporate architect, said during an online presentation that companies are finding it hard to achieve their machine learning ambitions. “If you use conventional tools, if you use what comes out of the box from most vendors, from most clouds, machine learning is hard, and it's expensive,” he said. In contrast, “you don’t need to be an expert to use machine learning with your data stored in MySQL HeatWave.”

The new capabilities are available at no extra charge for MySQL HeatWave customers in all of Oracle’s global cloud regions. Oracle is also making both the ML and TPC-DS benchmark tests public for customers to perform themselves. “That really lends credibility to the price and price-performance claims,” says Moore Insights’ Kimball.

Source: oracle.com

Monday, April 18, 2022

Easy Deployment of Machine Learning Models with Serialization Model Classes

Training a great model can take a lot of work. Getting that model into production should be quick and easy. ADS has a set of classes that take your model and push it to production with a few quick steps.

The first step is to create a model serialization object. This object wraps your model and has a number of methods to assist in deploying it. There are different model classes for different model classes. For example, if you have a PyTorch model you would use the PyTorchModel class. If you have a TensorFlow model you would use the TensorFlowModel class. ADS has model serialization for many different model classes. However, it is not feasible to have a model serialization class for all model types. Therefore, the GenericModel can be used for any class that has a .predict() method.

Read More: Database Certifications

After creating the model serialization object, the next step is to use the .prepare() method to create the model artifacts. The score.py file is created and it is customized to your model class. You may still need to modify it for your specific use case but this is generally not required. The .prepare() method also can be used to store metadata about the model, code used to create the model, input and output schema, and much more.

If you make changes to the score.py file, call the .verify() method to confirm that the load_model() and predict() functions in this file are working. This speeds up your debugging as you do not need to deploy a model to test it.

The .save() method is then used to store the model in the model catalog. A call to the .deploy() method creates a load balancer and the instances needed to have an HTTPS access point to perform inference on the model. Using the .predict() method, you can send data to the model deployment endpoint and it will return the predictions.

Oracle Database Exam Prep, Oracle Database Certification, Oracle Database Career, Oracle Database Learning, Oracle Database Skills, Oracle Database Jobs

This blog post uses a TensorFlow model as its example. The process for the other serialization model classes is the same.

The TensorFlowModel class in ADS is designed to allow you to rapidly get a TensorFlow model into production. The .prepare() method creates the model artifacts that are needed to deploy a functioning model without you having to configure it or write code. However, you can customize the required score.py file.

The following steps take your trained TensorFlow model and deploy it into production with a few lines of code.

Create a Model


The first step is to create a model that you wish to deploy.

Initialize


Instantiate a TensorFlowModel() object with a TensorFlow model. Each instance accepts the following parameters:

◉ artifact_dir: str: Artifact directory to store the files needed for deployment.

◉ auth: (Dict, optional): Defaults to None. The default authentication is set using the ads.set_auth API. To override the default, use ads.common.auth.api_keys() or ads.common.auth.resource_principal() and create the appropriate authentication signer and the **kwargs required to instantiate the IdentityClient object.

◉ estimator: Callable: Any model object generated by the TensorFlow framework.

◉ properties: (ModelProperties, optional): Defaults to None. The model properties that are used to save and deploy the model.

By default, properties is populated from the appropriate environment variables if it’s not specified. For example, in a notebook session, the environment variables for project id and compartment id are preset and stored in PROJECT_OCID and NB_SESSION_COMPARTMENT_OCID by default. So properties populates these variables from the environment variables and uses the values in methods such as .save() and .deploy(). However, you can explicitly pass in values to overwrite the defaults. When you use a method that includes an instance of properties, then properties records the values that you pass in. For example, when you pass inference_conda_env into the .prepare() method, then properties records this value. To reuse the properties file in different places, you can export the properties file using the .to_yaml() method and reload it into a different machine using the .from_yaml() method.

Summary Status


You can call the .summary_status() method after a model serialization instance such as AutoMLModel, GenericModel, SklearnModel, TensorFlowModel, or PyTorchModel is created. The .summary_status() method returns a Pandas dataframe that guides you through the entire workflow. It shows which methods are available to call and which ones aren’t. Plus it outlines what each method does. If extra actions are required, it also shows those actions.

The following image displays an example summary status table created after a user initiates a model instance. The table’s Step column displays a Status of Done for the initiate step. And the Details column explains what the initiate step did such as generating a score.py file. The Step column also displays the prepare(), verify(), save(), deploy(), and predict() methods for the model. The Status column displays which method is available next. After the initiate step, the prepare() method is available. The next step is to call the prepare() method.

Oracle Database Exam Prep, Oracle Database Certification, Oracle Database Career, Oracle Database Learning, Oracle Database Skills, Oracle Database Jobs

Model Deployment


Prepare

The prepare step is performed by the .prepare() method. It creates several customized files used to run the model after it is deployed. These files include:

◉ input_schema.json: A JSON file that defines the nature of the features of the X_sample data. It includes metadata such as the data type, name, constraints, summary statistics, feature type, and more.

◉ model.h5: This is the default filename of the serialized model for PyTorch models. Other serialization models use different formats and the file extension is changed to reflect this. You can change it with the model_file_name attribute. You can use the as_onnx parameter to save it in the ONNX format.

◉ output_schema.json: A JSON file that defines the nature of the dependent variable in the y_sample data. It includes metadata such as the data type, name, constraints, summary statistics, feature type, and more.

◉ runtime.yaml: This file contains information that is needed to set up the runtime environment on the deployment server. It has information about which conda environment was used to train the model, and what environment should be used to deploy the model. The file also specifies what version of Python should be used.

◉ score.py: This script contains the load_model() and predict() functions. The load_model() function understands the format the model file was saved in, and loads it into memory. The .predict() method is used to make inferences in a deployed model. There are also hooks that allow you to perform operations before and after inference. You are able to modify this script to fit your specific needs.

The .prepare() method serializes the model and prepares and saves the score.py and runtime.yaml files.

Verify

If you update the score.py file included in a model artifact, you can verify your changes, without deploying the model. With the .verify() method, you can debug your code without having to save the model to the model catalog and then deploying it. The .verify() method takes a set of test parameters and performs the prediction by calling the predict() function in score.py. It also runs the load_model() function to load the model.

The verify() method tests whether the .predict() API works in the local environment.

In TensorFlowModel, data serialization is supported for JSON serializable objects. Plus, there is support for a dictionary, string, list, np.ndarray, and tf.python.framework.ops.EagerTensor. Not all these objects are JSON serializable, however, support to automatically serializes and deserialized is provided. What data formats depend on the serialization model class. However, the generally support objects that are JSON serializable. Check the documentation for what formats are support for each serialization model class.

Save

After you are satisfied with the performance of your model and have verified that the score.py file is working, use the .save() method to save the model to the model catalog. The .save() method bundles up the model artifacts, stores them in the model catalog, and returns the model OCID.

The .save() method stores the model artifacts in the model catalog.

The .save() method reloads score.py and runtime.yaml files from disk. This will pick up any changes that have been made to those files. If ignore_introspection=False then it conducts an introspection test to determine if the model deployment might have issues. If potential problems are detected, it will suggest possible remedies. Lastly, it uploads the artifacts to the model catalog, and returns the model OCID. You can also call .instrospect() to conduct the test any time after you call .prepare().

Deploy

You can use the .deploy() method to deploy a model. You must first save the model to the model catalog, and then deploy it.

The .deploy() method returns a ModelDeployment object. Specify deployment attributes such as display name, instance type, number of instances, maximum router bandwidth, and logging groups.

Predict

To get a prediction for your model, after your model deployment is active, call the .predict() method. The .predict() method sends a request to the deployed endpoint, and computes the inference values based on the data that you input in the .predict() method.

The .predict() method returns a prediction of input data that is run against the model deployment endpoint.

Delete a Deployment


Use the .delete_deployment() method on the serialization model object to delete a model deployment. You must delete a model deployment before deleting its associated model from the model catalog.

Each time you call the .deploy() method, it creates a new deployment. Only the most recent deployment is attached to the object.

The .delete_deployment() method deletes the most recent deployment.

Example


import tempfile
import tensorflow as tf

from ads.catalog.model import ModelCatalog
from ads.common.model_metadata import UseCaseType
from ads.model.framework.tensorflow_model import TensorFlowModel

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential(
    [
        tf.keras.layers.Flatten(input_shape=(28, 28)),
        tf.keras.layers.Dense(128, activation="relu"),
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(10),
])
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"])
model.fit(x_train, y_train, epochs=1)

# Deploy the model, test it and clean up.
artifact_dir = tempfile.mkdtemp()
tensorflow_model = TensorFlowModel(estimator=model, artifact_dir= artifact_dir)
tensorflow_model.prepare(
    inference_conda_env="generalml_p37_cpu_v1",
    training_conda_env="generalml_p37_cpu_v1",
    use_case_type=UseCaseType.MULTINOMIAL_CLASSIFICATION,
    X_sample=x_test,
    y_sample=y_test,
)

tensorflow_model.verify(x_test[:1])
model_id = tensorflow_model.save()
tensorflow_model_deployment = model.deploy()
tensorflow_model.predict(x_test[:1])
tensorflow_model.delete_deployment(wait_for_completion=True)
ModelCatalog(compartment_id=os.environ['NB_SESSION_COMPARTMENT_OCID']).delete_model(model_id)

Source: oracle.com

Monday, April 4, 2022

Extend Enterprise Manager 13.5 to gain Machine Learning driven insights

This post is part 2 in a 3 part series on how to get Oracle Enterprise Manager data into OCI Object Storage, how to leverage that data in OCI Operations Insight (this post) and how to leverage that data in OCI Logging Analytics . If you haven't read part 1, please set aside some time to read that.

You have the Oracle Enterprise Manager data in OCI Object Storage, now what?

Oracle Enterprise Manager (EM) is Oracle’s premier monitoring solution for on-premises and Cloud environments. Oracle Cloud Infrastructure services can take advantage of this valuable set of telemetry data to perform further resource analysis.

There are currently two OCI services that can analyze this data:

Oracle Cloud Infrastructure Operations Insights is an OCI native service that provides 360-degree insight into database and host resource utilization and capacity.

Oracle Cloud Logging Analytics is a cloud solution in Oracle Cloud Infrastructure that lets you index, enrich, aggregate, explore, search, analyze, correlate, visualize and monitor all log data from your applications and system infrastructure on cloud or on-premises. 

In this blog, we will highlight the kind of activities you can perform with the EM data in Operations Insights.

OCI Operations Insights using the Enterprise Manager data to discover the targets from Object Storage

◉ Operations Insights consists of the following integrated applications: 

◉ Capacity Planning (Databases & Hosts)

◉ Oracle SQL Warehouse

◉ Exadata Insights 

◉ AWR Hub

Features of Operations Insights are:

1. Analyze resource usage of databases/hosts across the enterprise

2. Forecast future demand for resources based on historical trends

3. Compare SQL Performance across databases and identify common patterns

4. Identify SQL performance trends across enterprise-wide databases

Operations Insights supports the following target types:

1. Autonomous Data Warehouse

2. Autonomous Transaction Processing

3. On-premises Oracle databases (11.2.04 and greater)

4. Pluggable Databases 12.1.0.2 and greater

5. Hosts (Linux only) where Management Agents are deployed or are monitored by Enterprise Manager (Version 13.5 Release Update 1 or later)

Prerequisites for configuring OCI Operations Insights 

◉ Enterprise Manager 13.5 Release Update 1 or above

◉ Database Plug-in version 13.5.1.0.0 or above

Data transfer from Enterprise Manager to Operations Insights is configured in two steps: 

◉ Set up target-level data transfer from Enterprise Manager to OCI Object Storage.

◉ Set up data transfer from OCI Object Storage to Operations Insights. 

Analyze Database Resources with OCI Operations Insights and utilize capacity planning for your organization

Operations Insights Capacity Planning functionality provides insight into resource and usage of the databases, thus allowing you to meet both peak and long-term database capacity for the organization.

From the upper left of the Oracle Cloud console select the navigation icon (looks like a hamburger) and then drop down the menu and navigate to → Observability & Management → Administration. Select EM Bridges and create the bridge to access the data from OCI Object Store Bucket. Follow the steps and add the required Dynamic Groups and Policies.

Select Database Fleet, Host Fleet & Exadata Fleet to add the targets exported from Enterprise Manager.

From the upper left of the Oracle Cloud console select the navigation icon (looks like a hamburger) and then drop down the menu and navigate to → Observability & Management → Capacity Planning → Databases.

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 1:  Database Capacity Planning

CPU Insights with Insights / Aggregate / Machine Learning feature prediction

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 2:  Database CPU for scp

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 3:  Trend & Forecast (emrep_iad1qg_EMPDB)

Similar capacity insights available for Storage, Memory and Database I/O

Analyze Host Resources with OCI Operations Insights

Operations Insights enables you to view current and predicted memory usage for both individual hosts and across multiple hosts. 

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 4:  Host Capacity Planning for scp

Hosts CPU Insights/ Aggregate / Machine Learning feature prediction

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 5:  Host CPU for Operations Insights

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 6:  Trend & Forecast

Analyze Exadata Insights with Operations Insights

Exadata Insights provides visibility into performance of critical workloads running on shared Exadata infrastructure monitored by Enterprise Manager. A single integrated view of all Exadata systems across your enterprise helps identify issues and troubleshoot them quickly. 

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 7:  Exadata System Capacity Planning for Exadatas 

Rack view and Key Metrics

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 8:  Rack view and key metrics

Exadata Database CPU /Storage/Memory/IO Insights

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 9:  Exadata Database CPU (Storage, Memory, IO Insights) 

Exadata Host CPU / Memory Insights

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 10:  Exadata Host CPU and Memory Insights

Exadata Storage Server analysis with OCI Operations Insights

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 11:  Exadata Storage Server analysis with OCI Operations Insights
 
SQL Warehouse with Operations Insights

Using the Oracle SQL Warehouse function of Operations Insights to analyze the SQL performance problems for enterprise-wide applications across a fleet of databases. In addition, Operations Insights provides trends and key insights to SQL performance issues thereby helps to be proactive in avoiding future problems.

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 12:  SQL Warehouse with Operations Insights

Top SQLs by CPU Utilization

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 13:  Top SQLs by CPU utilization

Top SQLs by I/O Utilization

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 14:  Top SQls by I/O utilization

AWR Hub with Operations Insights

AWR Hub helps to consolidate and store detailed performance data from the Automatic Workload Repository of your important Oracle Autonomous Databases.

Machine Learning, Extend Enterprise Manager 13.5, Oracle Database, Database Exam, Database Exam Prep, Database Preparation, Database Career, Database Tutorial and Material, Database Skills, Database Jobs
Figure 15:  AWR Hub

To summarise, we can utilize the data from Enterprise Manager to get better insights and analytics with OCI services such as Operations Insights.


Source: oracle.com

Monday, March 1, 2021

Using Oracle Machine Learning for Python - building predictive models

Oracle Database Tutorial and Material, Oracle Database Learning, Oracle Database Certification, Oracle Database Guides, Database Career, Database Exam Study

In my previous post, we introduced some basic features of OML4Py. In this post, I'll illustrate using some in-database machine learning algorithms.

Creating in-database predictive models

In this example, we use the Random Forest algorithm and the optional cost matrix input to predict Species from the IRIS table. First, we get a DataFrame proxy object to the IRIS table, use the overloaded split function to obtain training and test data sets, which are also proxy objects (data remains in the database).  We then create and display a demo cost matrix - just for illustration - before building a Random Forest model. Note that the cost matrix is also a named database table, RF_COST.

Read More: 1Z0-062: Oracle Database 12c Administration

IRIS = oml.sync(table = "IRIS")        # obtain proxy object

IRIS_TRAIN, IRIS_TEST = IRIS.split()   # split data using default ratio

TRAIN_x = IRIS_TRAIN[0].drop('Species')

TRAIN_y = IRIS_TRAIN[0]['Species']

# Create a cost matrix table in the database

cost_matrix = [['setosa', 'setosa', 0],

  ['setosa', 'virginica', 0.2],

  ['setosa', 'versicolor', 0.8],

  ['virginica', 'virginica', 0],

  ['virginica', 'setosa', 0.5],

  ['virginica', 'versicolor', 0.5],

  ['versicolor', 'versicolor', 0],

  ['versicolor', 'setosa', 0.4],

  ['versicolor', 'virginica', 0.6]]

COST = oml.create(pd.DataFrame(cost_matrix,

                               columns = ['ACTUAL_TARGET_VALUE', 

                                          'PREDICTED_TARGET_VALUE', 

                                          'COST']),

                  "RF_COST")

COST.pull().pivot(index='ACTUAL_TARGET_VALUE',         

                  columns='PREDICTED_TARGET_VALUE',values='COST')

With the output:

PREDICTED_TARGET_VALUE   setosa   versicolor   virginica

ACTUAL_TARGET_VALUE

setosa                      0.0          0.8         0.2

versicolor                  0.4          0.0         0.6

virginica                   0.5          0.5         0.0

To build our Random Forest model, we create an rf object, specifying a maximum tree depth of 4, and invoke fit on our training data with the cost matrix. To display model details, we print the object. Note that the Random Forest model also reports attribute importance.

from oml import rf

rf_mod = rf(tree_term_max_depth = '4')

rf_mod = rf_mod.fit(TRAIN_x, TRAIN_y, COST)

rf_mod   # Show model details

With the output:

Algorithm Name: Random Forest

Mining Function: CLASSIFICATION

Target: Species

Settings:

                    setting name            setting value

0                      ALGO_NAME       ALGO_RANDOM_FOREST

1           CLAS_COST_TABLE_NAME      "PYQUSER"."RF_COST"

2              CLAS_MAX_SUP_BINS                       32

3          CLAS_WEIGHTS_BALANCED                      OFF

4                   ODMS_DETAILS              ODMS_ENABLE

5   ODMS_MISSING_VALUE_TREATMENT  ODMS_MISSING_VALUE_AUTO

6               ODMS_RANDOM_SEED                        0

7                  ODMS_SAMPLING    ODMS_SAMPLING_DISABLE

8                      PREP_AUTO                       ON

9                 RFOR_NUM_TREES                       20

10           RFOR_SAMPLING_RATIO                       .5

11          TREE_IMPURITY_METRIC       TREE_IMPURITY_GINI

12           TREE_TERM_MAX_DEPTH                        4

13         TREE_TERM_MINPCT_NODE                      .05

14        TREE_TERM_MINPCT_SPLIT                       .1

15         TREE_TERM_MINREC_NODE                       10

16        TREE_TERM_MINREC_SPLIT                       20

Computed Settings:

  setting name setting value

0    RFOR_MTRY             2

Global Statistics:

   AVG_DEPTH  AVG_NODECOUNT  MAX_DEPTH  MAX_NODECOUNT  MIN_DEPTH  \

0       3.25            5.6        4.0            6.0        4.0   

   MIN_NODECOUNT  NUM_ROWS  

0            4.0     102.0  

Attributes:

SEPAL_LENGTH

SEPAL_WIDTH

PETAL_LENGTH

PETAL_WIDTH

Partition: NO

Importance:

  ATTRIBUTE_NAME ATTRIBUTE_SUBNAME  ATTRIBUTE_IMPORTANCE

0   PETAL_LENGTH              None              0.584287

1    PETAL_WIDTH              None              0.512901

2   SEPAL_LENGTH              None              0.136424

3    SEPAL_WIDTH              None              0.038918

Use this Random Forest in-database model to make predictions

The rf_mod object is itself a proxy object to its corresponding in-database model. We predict using the IRIS_TEST proxy object and optionally specify supplemental columns from the original data. Supplemental columns are useful to compare actual target values against predicted values, or to include unique keys for subsequent row identification or joining with other tables. You may recall that row order is not implicit on results from relational databases unless a sort (i.e., ORDER BY) is specified by the user. Why? Sorting of often unnecessary and a potentially expensive operation depending on data size. The predicted results in pred are also a DataFrame proxy object, since the result could be large (e.g., millions or billions of rows).

pred = rf_mod.predict(IRIS_TEST.drop('Species'), 

                      supplemental_cols = test_dat[:, ['SEPAL_LENGTH', 

                                                       'SEPAL_WIDTH',

                                                       'PETAL_LENGTH', 

                                                       'Species']])

print("Shape:",pred.shape)

pred.head(10)

With the output:

Shape: (48, 5)

Out[16]:

   SEPAL_LENGTH  SEPAL_WIDTH  PETAL_LENGTH Species PREDICTION

0           4.9          3.0           1.4  setosa     setosa

1           4.9          3.1           1.5  setosa     setosa

2           4.8          3.4           1.6  setosa     setosa

3           5.8          4.0           1.2  setosa     setosa

4           5.1          3.5           1.4  setosa     setosa

5           5.0          3.4           1.6  setosa     setosa

6           5.2          3.5           1.5  setosa     setosa

7           5.4          3.4           1.5  setosa     setosa

8           4.9          3.1           1.5  setosa     setosa

9           5.0          3.2           1.2  setosa     setosa

Oracle Database Tutorial and Material, Oracle Database Learning, Oracle Database Certification, Oracle Database Guides, Database Career, Database Exam Study
Next, let's compute a confusion matrix for the model predictions to assess model accuracy. Using the overloaded crosstab function, we compute the confusion matrix between the actual values in Species and the predicted result in the PREDICTION column directly in the database.

res_ct = pred.crosstab('Species','PREDICTION',pivot=True)

print("Type:",type(res_ct))

print("Columns:",res_ct.columns)

res_ct.sort_values(by='Species')

With the output:

Type: 

Columns: ['Species', 'count_(setosa)', 'count_(versicolor)', 'count_(virginica)']

     Species  count_(setosa)  count_(versicolor)  count_(virginica)

0      setosa              16                   0                  0

1  versicolor               0                  13                  2

2   virginica               0                   0                 17

Thursday, February 25, 2021

Getting started with Oracle Machine Learning for Python

Oracle Machine Learning, Python, Oracle Database Exam Prep, Oracle Database Certification, Oracle Database Preparation, Database Prep, Oracle Database Exam Prep

As noted in Introducing Oracle Machine Learning for Python, OML4Py is included with Oracle Autonomous Database, making the open source Python scripting language and environment ready for the enterprise and big data. 

To get started with OML4Py, log into your Oracle Machine Learning Notebooks account and create a new notebook. If you don't have one yet, you can create an Autonomous Database account using your Oracle Always Free Services and follow this OML Notebooks tutorial.

Load the OML package

In the initial paragraph, specify %python as your interpreter. At this point, you can invoke Python code. However, to use OML4Py, import the package oml. Click the "run this paragraph" button. You can optionally invoke oml.isconnected to verify your connection, which should return true.

%python

import oml

oml.isconnected()

Load a Pandas DataFrame to the database

There are several way to load data into Oracle Autonomous Database. In this first example, we create a table using the sklearn iris data set. We combine the target and predictors into a single Pandas DataFrame and load this DataFrame object into an Oracle Autonomous Database  table using the create function.

from sklearn.datasets import load_iris

import pandas as pd

iris = 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'])

iris_df = pd.concat([x,y], axis=1)

IRIS = oml.create(iris_df, table="IRIS")

print("Shape:",IRIS.shape)

print("Columns:",IRIS.columns)

IRIS.head(4)

The script above produces the following output. Note that we access shape and columns properties on the proxy object, just as we would with a Pandas DataFrame. Similarly, we invoke the overloaded head function on the IRIS proxy object.

Shape: (150, 5)

Columns: ['SEPAL_LENGTH', 'SEPAL_WIDTH', 'PETAL_LENGTH', 'PETAL_WIDTH', 'Species']

Out[6]:

   SEPAL_LENGTH  SEPAL_WIDTH  PETAL_LENGTH  PETAL_WIDTH Species

0           5.1          3.5           1.4          0.2  setosa

1           4.9          3.0           1.4          0.2  setosa

2           4.7          3.2           1.3          0.2  setosa

3           4.6          3.1           1.5          0.2  setosa

This table is also readily available in the user schema under the name IRIS, just as any other database table.

Using overloaded functions

Using the numeric columns, we compute the correlation matrix on the in-database table IRIS using the overloaded corr function. Here, we see that petal length and petal width are highly correlated.

IRIS.corr()

With the output:

              SEPAL_LENGTH  SEPAL_WIDTH  PETAL_LENGTH  PETAL_WIDTH

SEPAL_LENGTH      1.000000    -0.109369      0.871754     0.817954

SEPAL_WIDTH      -0.109369     1.000000     -0.420516    -0.356544

PETAL_LENGTH      0.871754    -0.420516      1.000000     0.962757

PETAL_WIDTH       0.817954    -0.356544      0.962757     1.000000

OML4Py overloads graphics functions as well. Here, we use boxplot to show the distribution of the numeric columns. In such overloaded functions, the statistical computations take place in the database - avoiding data movement and leveraging Autonomous Database as a high performance compute engine - returning only the summary statistics needed to produce the plot.

import matplotlib.pyplot as plt

plt.style.use('seaborn')

plt.figure(figsize=[10,5]))

oml.graphics.boxplot(IRIS[:, :4], notch=True, showmeans = True,

                     labels=IRIS.columns[:4])

plt.title('Distribution of IRIS Attributes')

plt.ylabel('cm');

Oracle Machine Learning, Python, Oracle Database Exam Prep, Oracle Database Certification, Oracle Database Preparation, Database Prep, Oracle Database Exam Prep

In-database attribute importance


Let's rank the relative importance of each variable (a.k.a., attribute or predictor) to predict the target 'Species' from the IRIS table.

We define the ai (attribute importance) object, compute the result, and show the attribute importance ranking.

In the result, notice that petal width is most predictive of the target species. The importance value produced by this algorithm provides a relative ranking to be used to distinguish importance among variables.

from oml import ai

# here we use sync to get handle to existing table
IRIS = oml.sync(table = "IRIS")
IRIS_x = IRIS.drop('Species')
IRIS_y = IRIS['Species']

ai_obj = ai()  # Create attribute importance object
ai_obj = ai_obj.fit(IRIS_x, IRIS_y)
ai_obj 

With the output:

Algorithm Name: Attribute Importance

Mining Function: ATTRIBUTE_IMPORTANCE

Settings: 
                   setting name            setting value
0                     ALGO_NAME              ALGO_AI_MDL
1                  ODMS_DETAILS              ODMS_ENABLE
2  ODMS_MISSING_VALUE_TREATMENT  ODMS_MISSING_VALUE_AUTO
3                 ODMS_SAMPLING    ODMS_SAMPLING_DISABLE
4                     PREP_AUTO                       ON

Global Statistics: 
  attribute name  attribute value
0       NUM_ROWS              150

Attributes: 
PETAL_LENGTH
PETAL_WIDTH
SEPAL_LENGTH
SEPAL_WIDTH

Partition: NO

Importance: 

       variable  importance  rank
0   PETAL_WIDTH    1.050935     1
1  PETAL_LENGTH    1.030633     2
2  SEPAL_LENGTH    0.454824     3
3   SEPAL_WIDTH    0.191514     4

Change your service level


In your notebook, you can change the service level of your connection to Oracle Autonomous Database to take advantage of different parallelism options. Available parallelism is relative to your autonomous database compute resource settings. Click the gear icon in the upper right (as indicated by the arrow in the figure), then click individual interpreters to turn them on or off, and click and drag each interpreter box to change the default service level. The 'low' binding runs your functions and queries without parallelism, 'medium' allows limited parallelism, and 'high' allows your functions and queries to use up to the maximum number of compute resources allocated to your Autonomous Database.

Oracle Machine Learning, Python, Oracle Database Exam Prep, Oracle Database Certification, Oracle Database Preparation, Database Prep, Oracle Database Exam Prep

Wednesday, February 24, 2021

Introducing Oracle Machine Learning for Python

Oracle Machine Learning for Python, Oracle Database Certification, Oracle Database Career, Database Preparation

Data scientists and developers know the power of Python and Python's wide-spread adoption is a testament to its success. Now, Python users can extend this power when analyzing data in Oracle Autonomous Database. Oracle Machine Learning for Python (OML4Py) makes the open source Python scripting language and environment ready for the enterprise and big data.

Designed for problems involving both large and small data volumes, Oracle Machine Learning for Python integrates Python with Oracle Autonomous Database, allowing users to run Python commands and scripts for data exploration, statistical analysis, and machine learning on database tables and views using Python syntax. Familiar Python functions are overloaded to translate Python functionality into SQL for in-database processing - achieving performance and scalability - transparently.

Python users can take advantage of parallelized in-database algorithms to enable scalable model building and data scoring - eliminating costly data movement. Further, Python users can develop and deploy user-defined Python functions that leverage the parallelism and scalability of Autonomous Database, and deploy those same user-defined Python functions using environment-managed Python engines through a REST API.

Oracle Machine Learning for Python also introduces automated machine learning (AutoML), which consists of: automated algorithm selection to select the algorithm most appropriate for the provided data, automated feature selection to enhance model accuracy and performance, and automated model tuning to improve model quality. AutoML enhances data scientist productivity by automating repetitive and time-consuming tasks, while also enabling non-experts to produce models without needing detailed algorithm-specific knowledge.

Oracle Machine Learning for Python, Oracle Database Certification, Oracle Database Career, Database Preparation

Access Oracle Machine Learning for Python in Autonomous Database using Oracle Machine Learning Notebooks, where you can use Python and SQL in the same Apache Zeppelin-based notebook - allowing the most appropriate API for the task. Take advantage of team collaboration and job scheduling features to further your data science project goals.

Oracle Machine Learning for Python has a range of template example notebooks included with Oracle Autonomous Database that highlight various features. Zeppelin notebooks illustrating OML4Py features are also available in the Oracle Machine Learning GitHub repository.

Source: oracle.com

Thursday, October 8, 2020

Machine Learning Performance on Autonomous Database

Oracle Machine Learning, Oracle Database Tutorial and Material, Oracle Database Exam Prep, Oracle Database Learning, Oracle Database Prep

In many organizations, a data science project likely involves the data scientist pulling data to a separate analytics server - analyzing and preparing data and building machine learning models locally. As enterprises grow their data science teams and data volumes expand, common access to data and the ability to analyze that data in place can dramatically reduce time-to-project-deployment and overall complexity.

Building models and scoring data at scale is a hallmark for Oracle’s in-database machine learning - Oracle Machine Learning. Combine this with Oracle Autonomous Database - the converged database with auto-scale capabilities - and a team of data scientists can work comfortably in the same environment. In this blog post, we take a look at factors affecting machine learning model building performance as well as performance numbers illustrating the performance and scalability possible with Oracle Machine Learning. In a subsequent post, we'll discuss scoring performance.

Factors affecting performance


Many factors affect machine learning performance, including:

◉ Data volume – whether building models or scoring data, the most obvious factor is the amount of data involved – typically measured in the number of rows and columns, or simply gigabytes.

◉ Data movement and loading – related to data volume is the performance impact of moving data from one environment to another, or from disk into the analytics processing engine. This time needs to be considered when comparing machine learning tools and processes. 

◉ Choice of algorithm – different algorithms can have vastly different computational requirements, e.g., Naïve Bayes and Decisions Tree algorithms have low computational demands compared with those of Generalized Linear Models or Support Vector Machine.

◉ Data complexity – some patterns in data are easily identified by an algorithm and result in a model converging quickly. Other patterns, e.g., non-linear, can require many more iterations. In other cases, the cardinality of categorical variables or the density/sparsity of data can significantly impact performance.

◉ Algorithm implementation – open source and even proprietary algorithms are often implemented in a non-parallel or single-threaded manner, meaning that, even when run on multi-processor hardware, no performance benefit is realized. Such traditional single-threaded algorithms can often be redesigned to take advantage of multi-processor and multi-node hardware, through parallelized and distributed algorithms implementation. Enabling parallelism is often fundamental for improving performance and scalability.

◉ Concurrent users – one data scientist working on a single model on a dedicated machine may or may not see adequate performance relative to the factors identified above. However, when multiple users try to work concurrently to build and evaluate models or score data, the impact on the overall performance for these users may significantly degrade or even result in failures due to exhausting memory or other system resources. The ability for an environment to scale up resources to meet demand alleviates such impact. 

◉ Load on the system – while the number of concurrent machine learning users impacts performance, the non-ML sources (interactive users and scheduled jobs) can both impact and be impacted by ML sources. Compute environments that can manage and balance such uses can provide better overall performance

Enter Oracle Autonomous Database


Oracle Autonomous Database includes the in-database algorithms of Oracle Machine Learning (OML), which addresses the factors cited above that impact machine learning performance. By virtue of being in the database, OML algorithms operate on data in the database such that no data movement is required, effectively eliminating latency for loading data into a separate analytical engine either from disk or extracting it from the database. The OML in-database algorithm implementations are also parallelized—can table advantage of multiple CPUs—and distributed—can take advantage of multiple nodes as found with Oracle Exadata and Oracle Autonomous Database.

Oracle Autonomous Database further supports performance by enabling different service levels to both manage the load on the system, by controlling the degree of parallelism jobs can use, and auto-scaling, which adds compute resources on demand—up to 3X for CPU and memory to accommodate both ML and non-ML uses.

Performance results


To illustrate how Oracle Autonomous Database with Oracle Machine Learning performs, we conducted tests on a 16 CPU environment, involving a range of data sizes, algorithms, parallelism, and concurrent users. Oracle Autonomous Database supports three service levels: high, medium, and low. ‘High’ limits the number of concurrent jobs to three, each of which can use up to the number of CPUs allocated to database instance (here, up to 16 CPUs). ‘Medium’ allows more concurrent users but limits the number of CPUs each job can consume (here, 4CPUs). ‘Low’ allows even more concurrent use but only single-threaded execution, i.e., no parallelism.

Let's begin by comparing the single user experience with four popular in-database classification algorithms: Decision Tree (DT), Generalized Linear Model (GLM), Naive Bayes (NB), and Support Vector Machine (SVM). We start with the medium service level, which caps the number of CPUs at 4, and for a 16 CPU environment, the number of concurrent jobs at 20 (1.25 * 16). We use the ONTIME data set with 8 columns (equating to 70 coefficients when accounting for categorical variables).

Oracle Machine Learning, Oracle Database Tutorial and Material, Oracle Database Exam Prep, Oracle Database Learning, Oracle Database Prep

Notice the linear scalability across the range of data set sizes, i.e., a doubling in the number of rows is roughly doubling the run time. While there is some variation in the individual job execution times, this plot depicts the average execution time.

Next we look at the effect of the high service level, which enables a job to use up to the number of CPUs allocated to the database instance, in this case 16 CPUs.

Oracle Machine Learning, Oracle Database Tutorial and Material, Oracle Database Exam Prep, Oracle Database Learning, Oracle Database Prep

As we noted earlier, different algorithms respond differently to data, but even to the number of available resources. In some cases, increased parallelism can actually adversely impact performance as we see with SVM above due to the overhead of introducing parallelism for "smaller" data sets. However, at higher data volumes, the additional CPU resources clearly improve performance by about 50% for 800M rows. The remaining algorithms saw performance improvements across the range. As with the medium service level, we see effectively linear scalability across data sizes.

Let's now turn our attention to concurrent users. We start with the medium service level using the Generalized Linear Model (GLM) algorithm. It is interesting to note that since each run is limited to 4 CPUs, auto-scale had it's most significant impact at 8 concurrent users. At 4 concurrent users and 4 CPUs each, this consumed the 16 CPU, so this should not be surprising. When we turn auto-scale on, there are more CPUs available for more concurrent users. This illustrates how a team of data scientists can work in the same environment with modest impact on one another and that this can be further mitigated with auto-scale.

Oracle Machine Learning, Oracle Database Tutorial and Material, Oracle Database Exam Prep, Oracle Database Learning, Oracle Database Prep

Here, we look at the Support Vector Machine (SVM) algorithm regression. The performance benefits with auto-scale enabled are particularly beneficial for 4 and 8 concurrent users with a ~30% reduction in execution time for 400M rows.

Oracle Machine Learning, Oracle Database Tutorial and Material, Oracle Database Exam Prep, Oracle Database Learning, Oracle Database Prep

As discussed above, Oracle Autonomous Database with Oracle Machine Learning provides scalability and performance for data science teams, while providing powerful machine learning tools and autonomous data management capabilities.