Tuesday, March 27, 2018

Custom Model Scripts for Oracle Analytics



In this blog post we will discuss how to use custom models in OAC. We will walk-through the process of developing python scripts compatible with OAC, to train and apply a model using your own Machine Learning algorithm.

At the time of this blog, Oracle Analytics Cloud (OAC) is shipped with more than 10 Machine Learning algorithms which fall under Supervised (Classification, Regression) and Unsupervised(Clustering) Learning. List of inbuilt algorithms in OAC include CART, Logistic Regression, KNN, KMeans, Linear Regression, Support Vector Machine and Neural Networks (for an exhaustive list of inbuilt algorithms in OAC please refer to our earlier blog post). These inbuilt algorithms cover majority of the real world business use cases. However sometimes users are faced with cases/datasets where they need use to use a different algorithm to achieve their goal.

In such cases OAC lets users write their own scripts to Train and Apply a model using algorithm of their choice. We need to develop two scripts for working with custom models: First script to train your model and Second script to score/apply the model you just trained. Like other custom Advanced Analytics (Python or R) scripts Train and Apply model scripts need to be embedded in XML format.


Oracle Analytics-Library has an example for custom Train/Apply Model using Support Vector Regression (SVR). Please refer that sample to know more about the required XML structure before proceeding further. We'll use that sample to walk through these script parts.



Model-Train-Script:

1) Capturing Parameters:

    Data is typically prepared and pre-processed before it is sent for Training a model. Pre-processing
    involves filling missing values, converting categorical values to numerical values (if needed) and 
    standardizing the data. The way this data pre-processing is done can influence the accuracy of a
    model to a good extent. In OAC users are provided with parameters in Train Model UI to
    choose/influence the methods to be used for pre-processing. Also through the same UI users are
    provided a bunch of options to tune their model. All the parameters sent from this User Interface
    need to be captured before we start processing the data. For example in Train Model script for SVR
    following snippet of code reads all the parameters:

         ## Read the optional parameters into variables
         target = args['target']
         max_null_value_percent = float(args['maximumNullValuePercent'])
         numerical_impute_method = args['numericalColumnsImputationMethod']
         ...

2) Data Pre-processing(optional):

     Before we train a model data needs to be cleansed and normalized if necessary to get better
     prediction. In some cases Training data may already be cleansed and processed and be ready for
     training. But if the data is not cleansed and prepared user can define their own functions to
     perform the cleansing operation or use inbuilt methods in OAC to perform these operations.
     Following blog discusses in detail how to use inbuilt methods in OAC to perform
     cleanse/prepare the data for Training a model.

3) Train/Create Model:
     Now we are ready for actually training the model. Train Model process can be sub-divided into 2
     steps: 1) Splitting the data for testing the model 2) Train the model which contain model
     performance/accuracy details.

    Train-Test split: It is a good strategy to keep aside some randomized portion of the Training data
    for testing. This portion of data will be used for evaluating the model performance in terms of
    accuracy. Amount of data to be used for Training and Testing is controlled by a user parameter
    called split. And there is an inbuilt method for performing this split in a randomized fashion so as
    to avoid any bias or class imbalance problems. Following snippet of code performs this Train-Test
    split:
 
        # split data into test and train
        train_X, test_X, train_y, test_y = train_test_split(features_df, target_col, test_size=test_size,
        random_state=0)


    Train Model: Now we have datasets ready for Training and testing the model. It's time to train the
    model using inbuilt train methods for that particular algorithm. fit() is the inbuilt method for most
    of the algorithms implemented in python. Following snippet of code does that for SVR algorithms:

        # construct model formula
        svr = SVR(kernel=kernel, gamma = 0.001, C= 10)
        SVR_Model = svr.fit(train_X, train_y)

4) Save Model:

    Model that we created in the previous step needs to be saved/persisted so that it can be accessed
    during Apply/Scoring Model phase.
 
   Save Model as pickle Object: Created models are saved/stored as pickle objects and they are re-
   accessed during Apply model phase using reference name. There are inbuilt methods in OAC to
   save the model as pickle object. Following snippet of code saves the model as pickle object:

        # Save the model as a pickel object. And create a reference name for the object.
        pickleobj={'SVRegression':SVR_Model}
        d = base64.b64encode(pickle.dumps(pickleobj)).decode('utf-8')
 
   In this case SVRRegression is the reference name for the model created. The pickle doesnt have to
   be just the model. In addition to the model other information and objects can also be saved as pickle
   file. For example if wish to save additional flags standardizer indexes along with the model, you
   can create a dictionary object which contains the model and the flag/indexer and save this entire
   dictionary as a pickle object.

5) Add Related Datasets (optional): Now that we have the model, let us see how well this model
   performs. In the previous step we have set aside some part of the data for testing the model. Now
   using that testing dataset let us calculate some accuracy metrics and store them in Related datasets.
   This is an optional step and in cases where users are confident about model's accuracy they can skip
   this step. However if users wish to view the accuracy metrics or populate them in quality tab they
   can use inbuilt methods in OAC to create the related datasets. More information on how to add
   these Related datasets can be found in this blog: How to create Related datasets

6) Populate Quality Tab (optional): In the model Inspect pane, there is a tab called Quality. This
    tab visualizes the model accuracy details. Users can view the quality tab and evaluate the model
    accuracy and decide if he/she wants to tune the model further or use it for prediction. Please note
    that this is also an optional step and not mandatory. However if users wish to view the model
    quality details in Quality tab then they can use inbuilt functions in OAC. More details on inbuilt
    functions that populate quality tab can be found in this blog How to Populate Quality Tab.

Now the Model along with related datasets is all prepared and saved in a pickle object. This marks the end of Train Model phase. The script returns the model to the framework and it is stored in dataset storage. If the train model executes successfully you should find the model in Machine Learning > Models tab. For example I have created a model called SVR Donations using the SV Regression scripts uploaded in the analytics-library:

                                    

Model-Apply-Script:

Apply script should have the same name as Train script except for train part i.e. for example it should follow nomenclature: OAC.ML.Algo_Name.apply.xml. Apply script accepts the model name, and other data pre-processing parameters and user parameters as input to the script. Most of the pre-processing steps are same as what we have done in Train Model scripts

1) Capturing Parameters
2) Data Pre-processing: Same inbuilt methods can be used for cleansing (filling missing values), Encoding and Standardizing the Scoring data.

After the data is cleansed and standardized it can be used for Prediction/Scoring. 

Load Model and Predict:
    Using the reference name we gave to the model in Train Script, retrieve the model pickle object and predict the results for Cleansed and Standardized scoring data. Following code in SVR Apply model script does that:

       ## Load the pickle object that we saved during Train Model phase. It is stored as an element 
       in dictionary. Fetch it using the reference name given.

       pickleobj = pickle.loads(base64.b64decode(bytes(model.data, 'utf-8')))
       SVR_Model=pickleobj['SVRegression']
    
       ## Predict values.
       y_pred=SVR_Model.predict(data)
       y_pred_df = pd.DataFrame(y_pred.reshape(-1, 1), columns=['PredictedValue'])

If includeInputColumns option is set to True, the framework appends the predicted result to input columns and return the complete dataframe.

This concludes the process of developing scripts for Train and Apply of Custom models.


Related Blogs: Prepare data using inbuilt functions in OAC, How to add Related Datasets, How to Populate Quality Tab

Are you an Oracle Analytics customer or user?

We want to hear your story!

Please voice your experience and provide feedback with a quick product review for Oracle Analytics Cloud!
 

How to Populate Quality Tab in ML Model Inspect page in Oracle Analytics Cloud

In this blog post we will discuss about how to Populate Quality Tab of a Machine Learning Model's Inspect page in OAC.

Assessing quality of a Machine Learning model is an important step in evaluating its performance. Various metrics like RSE, RAE Residuals , R-Squared Adjusted etc help in assessing the quality of the model prediction. If the error metrics are not satisfactory or does not meet user's goals, he/she can tune the model model further till the required level of accuracy is reached. So it is important to expose this quality information of a model in an intuitive and comprehensive fashion so that users can take next course of actions as necessary. Quality tab in Inspect page of ML model in Oracle Analytics Cloud aims to visualize and give complete information on model accuracy details. Here is a snapshot of Quality tab for Linear Regression Model that predicts Bike Rental Count:




In this blog we will talk about how to populate this Quality tab for a custom model. Quality Tab is populated by adding required Related datasets in Train Model script. More details on how to add a related dataset can be found in this blog. Quality tab is auto-populated if user adds the following related datasets:

For Numeric Prediction: If Residuals and Statistics datasets are added as Related datasets in Train Model script, ML framework in OAC takes information from that dataset and populates the Quality tab. Graph is populated using Residuals dataset and all the error metrics are populated using Statistics Dataset. Image shown above shows how Quality tab of a Numeric Prediction model looks like. Here is a sample code that shows how to add Statistics and Residuals Related datasets:

        #residuals dataset
        residuals_mappings = None
        residuals_ds = ModelDataset("Residuals", residuals_df, residuals_mappings)
        model.add_output_dataset(residuals_ds)

        # statistics dataset
        statistics_mappings = None
        statistics_ds = ModelDataset("Statistics", statistics_df, statistics_mappings)
        model.add_output_dataset(statistics_ds)

For Classification: For Binary and Multi-Classification models Confusion Matrix and Statistics Related datasets are used to populate the Quality tab. Here is a sample snapshot of Quality tab for Classification models:



Confusion Matrix Related dataset is used to populate the Confusion matrix table that can be seen in the image and Statistics Related dataset is used to populate the metrics. Here is a sample code that shows how to add Confusion Matrix and Statistics related datasets:
            metrics['Statistics'] = stats
            metrics['Confusion Matrix'] = confMatrix
            ....
            self.add_datasets(metrics=metrics, model=model)

Quality tab is updated automatically if user changes the values of user or model tuning parameters and trains the model. 

Related Blogs: How to build Train/Apply Model Custom Scripts in OAC, How to create Related DatasetsHow to use inbuilt methods in OAC to Prepare data for Training/Applying ML Model 

Are you an Oracle Analytics customer or user?

We want to hear your story!

Please voice your experience and provide feedback with a quick product review for Oracle Analytics Cloud!
 

Pre-Processing and Preparing Data for ML Predictions in OAC

In this blog post we will talk about how to use inbuilt methods in OAC to cleanse and prepare data used for Training a Machine Learning model in OAC.

One of the important steps in Training a Machine Learning model is to cleanse and prepare the data that we are going to use to train the model. What exactly do we mean by "cleanse and prepare the data":

  "It is the process of detecting and correcting (or removing) corrupt or inaccurate records from a
    record set, table, or database and refers to identifying incomplete, incorrect, inaccurate or
    irrelevant parts of the data and then replacing, modifying, or deleting the dirty or coarse data."


It is important to cleanse and prepare data because if we train a model with missing column values or anomalies/outliers in the data which can either be garbage data or simple outliers then the model prediction accuracy can go awry. To solve this problem Machine Learning feature in Oracle Analytics cloud provides some inbuilt methods to perform data cleansing/preparation which can be invoked in Train model scripts.

    In this blog post we will learn about how to cleanse/prepare Training data in a Custom Train Model script using inbuilt methods in Machine Learning in Oracle Analytics Cloud. Data cleansing/preparation process can be broken down into three steps: Data Imputation (filling missing values), Encoding (Converting Categorical to numerical values if necessary) and Standardization (Normalization). All the functions needed to perform these operations are implemented in a python module called datasetutils with in OAC. Users can develop their own functions or use the existing module. Here is a snapshot of the parameters accepted from UI for each of these operations while Training a model:

                            

Here is brief description about each of the data preparation functions:

 1) Data Imputation: Data imputation is a process of filling missing values. There are multiple
     inbuilt imputation methods. Users are given option to choose the imputation method for filling the
     missing values for both numerical(Mean, Median, Min, Max) and Categorical(Most Frequent,
     Least Frequent) variables. datasetutils python module in OAC contains a function called fill_na()
     that performs data imputation. This code accepts the methods for imputation as parameters and
     returns a dataframe with data imputed for categorical and numerical columns. Following snippet
     of code shows a sample usage of fill_na() function.:
 
     # fill nan columns with mean, max, min, median values for numeric and most frequent, least
        frequent for categorical

     df = datasetutils.fill_na(df, max_null_percent=max_null_value_percent,
                 numerical_impute_method=numerical_impute_method, categorical_impute_method =
                 categorical_impute_method)


 2) Encoding: Encoding is a process of converting Categorical variables to numerical values. This is
      usually required in cases where regression needs to be performed. There are two inbuilt methods
      to perform encoding, they are: Onehot and Indexer. features_encoding() function in datasetutils
      module performs encoding. Following snippet of code performs encoding:

      # encoding categorical features
      data, input_features, categorical_mappings = datasetutils.features_encoding(df, target,     
      None, 
encoding_method=encoding_method, type = "regression")

  3) Standardization: 
Standardization is a process of normalizing the data to reduce the effects of
      skews introduced due to outliers. standardize_clean_data() function in datasetutils module is an
      inbuilt method in OAC to perform standardization. Following is a sample snippet of code that
      performs standardization and returns a dataframe with standardized data by normalizing
      outliers:

      # Standardize data. This is to make sure that the data is normalized so as to reduce the
         influence of Outliers

      target_col = data[[target]]
      if standardization_flag:
            features_df = datasetutils.standardize_clean_data(data, input_features)
      else:
            features_df = data[features]

All these functions can be invoked directly from Train model custom scripts by importing datasetutils module in the beginning of Train Model script.

Related Blogs: How to build Train/Apply custom model scripts in OAC, How to Create Related Datasets, How to Populate Quality Tab

Are you an Oracle Analytics customer or user?

We want to hear your story!

Please voice your experience and provide feedback with a quick product review for Oracle Analytics Cloud!
 

How to Create Related Datasets for ML Models in Oracle Analytics Cloud

In this blog post we will discuss how to Add Related datasets for custom Machine Learning models in OAC.

After a Machine Learning model is created it is important to evaluate how well the model performs, before we go ahead and apply that model. To evaluate how well a model performs there are various accuracy metrics like Mean Absolute Error (MAE), Root Mean Squared Error(RMSE), Relative Absolute error(RAE), Residuals etc for numeric prediction/Regression algorithms and False Positive Rate(FPR), False Negative Error, Confusion Matrix etc for classification algorithms. Machine Learning feature in Oracle Analytics cloud has inbuilt methods to compute most of these accuracy metrics and store them in Related datasets. Related datasets are the tables/datasets which contain information about the model like accuracy metrics and prediction rules. In our previous blog spot named Understanding the Performance of a Oracle DV Machine Learning models using related datasets feature we have covered in depth about Related datasets.

     In this blog post we will talk about how to add such related datasets in Custom Train model code. There are inbuilt methods in Oracle Analytics Cloud to add related datasets. User has to define the structure of these datasets i.e., columns these tables/datasets should contain, data type for all these columns and aggregation rules for these columns(if they are numeric). Once the required related datasets are added they can be found under Related Tab in Model Inspect pane:



Let us discuss in detail how to add Related datasets for a model:

ModelDataset() class implemented in Model module is a generic class that represents related datasets. Pass the name of the dataset that you are trying to create as an argument to ModelDataset() along with column names and mappings. This will return a related dataset. Generic Model class has an inbuilt method called add_output_dataset() which adds the passed dataset/dataframe as related dataset for that model. Following lines of code shows how to add a sample Related dataset called "Predicted Results" using df1 dataframe.

   df1=pd.DataFrame({target:y_test, \
                     "PredVal":y_pred1, \
                     "PredProb":[y_pred_prob1[i][list(clf1.classes_).index(y_pred1[i])] for i in range(len(y_pred1))]})

   df1_mappings = pd.DataFrame({
               'name':[target,'PredVal','PredProb','Target','Model Name'],
               'datatype':["varchar(100)","varchar(100)", double","varchar(100)","varchar(2000)"],
               'aggr_rule':["none","none", "avg","none","none"]})   

 model.add_output_dataset(ModelDataset("Predicted Results", df1, df1_mappings))

Mappings dataframe contains column names mapped to corresponding datatypes and aggregation rules. Some of these related datasets are used by the framework to populate Quality Tab in the Model Inspect page. More details on how to populate Quality tab can be found in this blog: How to populate Quality tab.

Related Blogs: How to build Train/Apply custom model scripts in OACHow to Populate Quality Tab, How to use inbuilt methods in OAC to Prepare data for Training/Applying ML Model 

Are you an Oracle Analytics customer or user?

We want to hear your story!

Please voice your experience and provide feedback with a quick product review for Oracle Analytics Cloud!