Before using this information and the product it supports, be sure to read the information in Appendix H. Notices.
This edition applies to Version 8.2 of IBM DB2 Intelligent Miner Scoring, program number 5765-F36, and to all subsequent releases and modifications until otherwise indicated in new editions.
This edition replaces SH12-6745-00.
IBM(R) DB2(R) Intelligent Miner(TM) Scoring is an application that integrates the model application functionality of Intelligent Miner for Data with the DB2 Universal Database(TM).
Intelligent Miner Scoring enables you to import and apply mining models, and to access the results.
Throughout this book, the following abbreviations are used:
This book describes how to use IM Scoring and IM Scoring Java Beans. It also provides a full reference resource to the database objects provided by IM Scoring.
References in this book to DB2 refer to DB2 UDB Version 8.1.
For more information on:
This book is intended for the following users:
In DB2, the names of the scoring methods, functions, data types, tables, and table columns are created in uppercase letters, even if you used, for example, lowercase letters. In this book, these names are represented in mixed case for better readability.
CREATE TABLE "BANKING_SCORING" ( "CLIENT_ID" CHAR(9) NOT NULL PRIMARY KEY, "AGE" REAL, "GENDER" CHAR(2), "MARITAL_STATUS" CHAR(12), "PROFESSION" CHAR(24), "NBR_YEARS_CLI" REAL, "SAVINGS_ACCOUNT" CHAR(3), "HAS_LIFE_INSURANCE" CHAR(3), "INT_CREDITCARD" CHAR(3), "ONLINE_ACCESS" CHAR(3), "JOINED_ACCOUNTS" CHAR(3), "BANKCARD" CHAR(3), "AVERAGE_BALANCE" DECIMAL(10,2), "NO_CRED_TRANS" REAL, "NO_DEBIT_TRANS" REAL ) NOT LOGGED INITIALLY
The following table shows the formatting conventions used in this book.
| Convention used | How it is used |
|---|---|
| Interface elements, for example, menu bars, buttons, and labels are shown in boldface. | Click OK. |
| Menu instructions are shown in boldface and sequential instructions are separated by arrows. | Click File --> Export. |
| Command syntax is shown in a monospaced font. | db2 -stf idmtab.db2 |
The names of the following are shown in a monospaced
font:
|
The SQL INSERT command inserts the model into a column of the table CLUSTERMODELS, which is configured for the data type DM_ClusteringModel. |
| Variables within syntax descriptions, which you should replace by a real value, are shown in italics. If they consist of more than one word they are placed between angle brackets. | idmdisabledb <db name> |
| Italics are used to highlight the introduction of a new term. | These functions are also referred to as user-defined functions and to indicate that a variable should be replaced. |
The following table shows the abbreviations used in this book.
| Abbreviation | Full form |
|---|---|
| CRM | Customer Relationship Management |
| GUI | Graphical user interface |
| ICU | International Components for Unicode |
| PMML | Predictive Model Markup Language |
| RBF | Radial Basis Function |
| RPM | Redhat Package Manager |
| SQL | Structured Query Language |
| UDF | User-defined function |
| UDM | User-defined method |
| UDT | User-defined data type |
| XML | Extensible Markup Language |
This book is divided into the following parts:
The appendixes provide reference information.
In the reference part of this book, the syntax for IM Scoring's functionality is described using the following structure:
The >>--- symbol indicates the beginning of a statement.
The ---> symbol indicates that the statement syntax is continued on the next line.
The >--- symbol indicates that a statement is continued from the previous line.
The -->< symbol indicates the end of a statement.
>>-required item-----------------------------------------------><
>>-+---------------+------------------------------------------->< '-optional item-'
If you must choose one of the items, one item of the stack appears on the main path.
>>-+-required choice1-+---------------------------------------->< '-required choice2-'
If choosing none of the items is an option, the entire stack appears below the main path.
>>-+------------------+---------------------------------------->< +-optional choice1-+ '-optional choice2-'
A repeat arrow above a stack indicates that you can make more than one choice from the stacked items.
.----------------------. V | >>---+------------------+-+------------------------------------>< +-optional choice1-+ '-optional choice2-'
Your feedback is important in helping us to provide you with the most accurate and high-quality information possible. If you have any comments about this book:
This section introduces you to the new features in IM Scoring.
You can import additional data mining models in PMML format, for example, created by SAS EM or SPSS Clementine. The export and import of PMML models is easier than before. Other programs, such as SAS EM and SPSS Clementine allow to directly import PMML models from their workbenches. For more information refer to:
The standards for data mining are outlined in ISO/IEC 13249; the description appears in Part 6: Data Mining of the standards specification. This specification has the general title Information technology - Database languages - SQL Multimedia and Application Packages.
IM Scoring shares common infrastructure like XML parsing, error handling, tracing, licensing, and diagnostics with IM Modeling.
You should consider the following consistency notices when using IM Scoring V8.2:
insert into IDMMX.RegressionModels ("MODELNAME", "MODEL")
values ( 'sample' , IDMMX.DM_impRegFile( '/tmp/sample.xml' ) ) ;
The IBM DB2 Intelligent Miner is a set of the following products:
These products provide rapid enablement of IM analytics that are embedded in Business Intelligence (BI), eCommerce, or traditional Online Transaction Processing (OLTP) application programs. They are available as separately priced products. They are also available in the IBM DB2 Data Warehouse Edition, except for IM for Data.
In addition to the set of IM products, the following features for Intelligent Miner are available for free on alphaWorks(R) at the alphaWorks home page:
IM Scoring and IM Modeling constitute a software development kit (SDK). They consist of Oracle cartridges (IM Scoring only) or DB2 extensions that include an SQL API. You can embed the SQL API in business applications to exploit the data mining functions from this business application.
The SQL API consists of the following layers that provide different granularity and a different degree of abstraction:
In DB2, professionals can interactively issue SQL statements from the command center or from the command line processor. They can also start Intelligent Miner functions from one of these interfaces.
Intelligent Miner V8.2 provides an add-in demo that is based on an Excel spreadsheet. This demo illustrates the functionality of the SQL API and how to use it. With this demo, you can prototype IM functions to develop a proof-of-concept without dealing with the complexity of the SQL API.
To assist application developers, Intelligent Miner V8.2 provides a WebSphere Studio Plug-in. This plug-in contains graphical wizards and editors that are integrated in the WebSphere Studio Plug-in environment. With these tools, application developers can graphically model mining tasks and generate the SQL to embed IM SQL functionality into their business applications.
Depending on the experience, the personal preferences, the mining skills, and the complexity of the problem to solve, you can choose between the following approaches to develop a mining solution:
Figure 1 shows a typical scenario of how you can use the IM products in your business environment:
For more information refer to:
IM Scoring provides scoring technology as database extenders, DB2 extenders, and Oracle cartridges. It enables application programs to apply PMML models to large databases, subsets of databases, or single rows or cases. Application programs use the SQL API, which consists of user-defined functions (UDFs) and user-defined methods (UDMs), to perform the scoring operation. The PMML models might have been created by one of the Intelligent Miner products or by other applications and tools that support PMML models.
The following table shows the different PMML models that can be applied by different mining algorithms.
| Data mining function | PMML model type | Mining algorithm | Generated by IM for Data | Generated by IM Modeling |
|---|---|---|---|---|
| Clustering | Center-based clustering | Center-based Clustering algorithm | yes | no |
| Distribution-based clustering | Distribution-based Clustering algorithm | yes | yes | |
| Classification | Neural networks | Neural Classification algorithm | yes | no |
| Decision tree | Tree Classification algorithm | yes | yes | |
| Regression | Logistic Regression algorithm | no | no | |
| Regression | Regression | Linear Regression algorithm | yes | no |
| composite MiningModel (see Notes) | Transform Regression algorithm | no | yes | |
| Proprietary XML | RBF Prediction algorithm | yes | no | |
| Neural networks | Neural Regression algorithm | yes | no |
IM Scoring includes IM Scoring Java Beans, which enables you to score a single data record in a Java application given a PMML model. This can be used to integrate scoring in e-business applications, for example, for real-time scoring in customer relationship management (CRM) systems.
IM Modeling provides IM Modeling technology as DB2 extenders. It enables SQL application programs to develop analytic models based on data accessed by DB2 Universal Database Version 8.1 or Version 8.2 SQL. Using the SQL API, you can build Associations, Distribution-based Clustering, Tree Classification, and Transform Regression PMML models that are stored in DB2 tables. They can be processed by IM Scoring or IM Visualization.
IM Modeling is easy to understand for users who are familiar with the mining functions in IM for Data.
IM Visualization provides the following JAVA visualizers to present data modeling results for analysis:
You can use the Intelligent Miner Visualizers to visualize PMML-conforming mining models. Applications can call these visualizers to present model results, or you can deploy the visualizers as applets in a Web browser for ready dissemination. The models might have been developed by using IM Modeling or other applications and tools that support interoperability through the use of PMML models, or models of the Intelligent Miner for Data might have been exported as PMML models. Models are stored as flat files, or you can directly visualize mining models from the database. The models in the database have been created by IM Modeling or they have been imported into the database using the import functions of IM Scoring.
The focus of the PMML standard is interoperability for scoring. The best results with IM Visualization can be achieved if the PMML models contain IM Visualization extensions such as distribution statistics or quality information as produced by IM Modeling. For more information on IM Visualization extensions contact your IBM representative.
IM Visualization Version 8.2 provides the following enhancements:
The Intelligent Miner Visualizers Version 8.1 are also included in Intelligent Miner for Data Version 8.1.
Intelligent Miner for Data Version 8.1 is an independent product that provides the following mining functions to build and apply mining models based on database or flat file data:
The Processing functions can be used only on database tables.
IM for Data Version 8.1 is a stand-alone data mining application (workbench) for end users and primarily statisticians with advanced data mining skills. It includes the Intelligent Miner Visualizers and the PMML conversion component of IM Scoring, which allows you to export mining models in PMML format.
This chapter introduces you to the general concepts you need to know to work with IM Scoring. IM Scoring is an add-on service to DB2 that extends the capabilities of DB2 to include data mining functions. Mining models are built using:
You use IM Scoring as follows:
The model is stored in the database in a standardized XML format (PMML). You can directly visualize the mining model from the database using IM Visualization in stand-alone mode or as a Web applet. You can use IM Scoring to apply the model to new data.
Figure 2 shows that PMML models can be applied to new rows of data (ApplicationData) using the Scoring Apply function, which computes a scoring Result that contains the scores and predictions. The ResultSpec object is optional and allows to customize the scoring result.
This section introduces you to the different data mining functions that are supported by IM Scoring. These data mining functions contain different PMML model types and mining algorithms. Each model type includes different algorithms to deal with the individual data mining functions.
For example, the Clustering data mining function includes the PMML model types Distribution-based Clustering and Center-based Clustering. The scoring functions for Clustering include the Distribution-based Clustering algorithm and the Center-based Clustering algorithm.
IM Scoring supports the data mining functions provided by:
The Associations mining function finds items that are consistently associated with each other in a meaningful way. For example, you can analyze purchase transactions to discover combinations of goods that are often purchased together. The Associations mining function answers the question: If certain items are present in a transaction, what other item or items are likely to be present in the same transaction?
Classification is the process of automatically creating a model of classes from a set of records that contain class labels. The classification technique analyzes records that are already known to belong to a certain class, and creates a profile for a member of that class from the common characteristics of the records. You can then use a data mining application tool to apply this model to new records, that is, records that have not yet been classified. This enables you to predict if the new records belong to that particular class.
When a model is applied, IM Scoring assigns a class label and a confidence value to each individual record being scored.
The clustering technique consists of a range of algorithms that group data records on the basis of how similar they are. For example, a data record might consist of a description of customers. In this case, clustering would group similar customers together, and at the same time it would maximize the differences between the different customer groups formed in this way. The groups that are found are known as clusters. Each cluster tells a specific story about customer identity or behavior, for example, about their demographic background, or about their preferred products or product combinations. In this way, customers can be grouped in homogeneous groups that are very similar to each other.
When a model is applied, IM Scoring assigns a cluster ID, a cluster score, a quality value, and a confidence value to each individual record being scored. The cluster score, quality value, and confidence value are different measures that indicate how well the record fits into the assigned cluster.
Regression is similar to classification except for the type of the predicted value. Rather than predicting a class label, regression is predicting a numeric value. Furthermore, regression can determine which input fields are most relevant to predict the target field values. The predicted value might not be identical with any value contained in the data used to build the model. An example application is customer ranking by expected profit.
When a model is applied, IM Scoring assigns a predicted value and, for an RBF model, a region ID to each individual customer being scored.
PMML is a standard format for data mining models. Based on XML, the PMML format provides a standard that enables data mining models to be shared between the applications of different vendors. The intention is to provide a vendor-independent method for defining models. In this way, proprietary issues and incompatibilities are no longer a barrier to the exchange of models between applications.
For more information on PMML support refer to Appendix A. IM Scoring conformance to PMML.
IM Scoring applies PMML models to data in DB2. The PMML models are stored as binary large objects (BLOBs) in the database. IM Scoring provides UDFs to import models into the database.
You can use the following sources of PMML models:
This section describes the tools that can create PMML models for IM Scoring.
Table 3 shows the mining functions and algorithms supported by IM Modeling. The models that IM Modeling creates reside in a DB2 table. These models are in a format that enables IM Scoring to apply them directly.
Figure 3 provides an overview of the interplay of:
IM Modeling extracts knowledge from historic data and builds a data mining model. This model contains the rules and patterns found in the data. This step is also referred to as training a model.
The model is stored in the database in a standardized XML format (PMML).
IM Scoring can be used to apply the model to new data.
You can use IM for Data to build and store models for all mining functions that are supported as shown in Table 3.
To migrate IM for Data models, you can:
Figure 4 shows the process by which a mining model that was built with IM for Data is exported from IM for Data, imported into a DB2 database, and applied to selected data. To use the IM Scoring mining functions:
The mining technology is based on open standards like SQL/MM, PMML, and XML. Other products, such as SAS EM and SPSS Clementine, allow to directly export PMML models from their workbenches. These models can then be imported into the database using the import functions of IM Scoring. For more information refer to:
Depending on your real-time requirements you can invoke the Scoring apply function in different ways. It is important to consider how often the data to be scored changes and how often you need to recompute the scores.
See Storing scoring results permanently for an example of batch scoring with persistent results.
See Recomputing scores in real time for an example of setting triggers.
In this case you have the following options:
See Optimizing performance and scoring a single record for examples of using the model cache.
Here you find a general introduction to the SQL/MM API terminology and statements.
The SQL/MM API is a standardized open SQL API, that:
The following list familiarizes you with the SQL API terminology:
Figure 5 maps the conceptual objects to the DB2 user-defined types (UDTs) used in IM Scoring. This figure shows an example for clustering.
In Figure 5 the Scoring function DM_applyClusModel receives the following parameters:
The REC2XML function creates an XML string value representing the database row, because this parameter contains a list of column name/value pairs for all columns in a row.
As the scores are computed in a scalar user-defined function, the scoring step can be embedded in arbitrary SQL statements.
WITH "CLUSTERVIEW"( "CLIENT_ID", "CLUSTERRESULT" ) AS
(
SELECT "CLIENT_ID",
IDMMX.DM_applyClusModel( C."MODEL" ,
IDMMX.DM_impApplData(rec2xml( 1.0, 'COLATTVAL', '',
B."AGE",B."GENDER",B."MARITAL_STATUS",B."PROFESSION",
B."BANKCARD",B."NO_CRED_TRANS",B."NO_DEBIT_TRANS" ) ) )
FROM "BANKING_SCORING" B, IDMMX."CLUSTERMODELS" C
WHERE C."MODELNAME"='DemoBanking'
)
SELECT "CLIENT_ID",
IDMMX.DM_getClusterID( "CLUSTERRESULT" ) AS "CLUSTERID",
CAST( IDMMX.DM_getQuality( "CLUSTERRESULT" )
AS DEC(5,4)) AS "QUALITY"
FROM "CLUSTERVIEW";
WITH "CLUSTERVIEW"( "CLIENT_ID", "CLUSTERRESULT" ) AS
(
SELECT "CLIENT_ID",
IDMMX.DM_applyClusModel( 'DemoBanking',
rec2xml( 1.0, 'COLATTVAL', '',
"AGE","GENDER","MARITAL_STATUS","PROFESSION","BANKCARD",
"NO_CRED_TRANS","NO_DEBIT_TRANS" ) )
FROM "BANKING_SCORING"
)
SELECT "CLIENT_ID",
IDMMX.DM_getClusterID( "CLUSTERRESULT" ) AS "CLUSTERID",
CAST( IDMMX.DM_getQuality( "CLUSTERRESULT" )
AS DEC(5,4)) AS "QUALITY"
FROM "CLUSTERVIEW";
The aim of this chapter is to get you up and running quickly in using the IM Scoring samples. It provides information on the tasks that you need to complete to get started. Refer to DB2 Intelligent Miner Modeling, DB2 Intelligent Miner Scoring, DB2 Intelligent Miner Visualization: Installing the Intelligent Miner products for a detailed description on how to install and configure IM Scoring.
Refer to Sample files and Completing the practice exercises to find samples and to become more familiar with the IM Scoring mining functions. These sections guide you through a tutorial of practice exercises on sample data. By using the data and scripts provided with the IM Scoring package and the instructions given in these sections, you become familiar, for example, with the following actions:
All the tasks in the practice exercises are completed by means of sample scripts. The scripts include standard SQL commands, such as INSERT, and scoring functions, such as DM_impClusFile. The contents of the scripts are given in these sections so that you can see how the SQL statements are structured. You can use these sample scripts as a basis for your own scripts.
IM Scoring provides a set of samples to help you to get familiar with the UDFs and UDTs.
The UDTs, UDFs, and UDMs (refer to Scoring data types, methods, and functions) provided with IM Scoring must be created in the databases that you want to use with IM Scoring. To do this, use the idmenabledb command, which is available in the bin directory of your IM Scoring installation. You must also specify the database name (dbname) in this command:
idmenabledb dbname fenced dbcfg
In this example the following options are selected:
For more information see:
If you already have PMML models, you can generate SQL scripts from them by using the idmmkSQL tool. These scripts will contain template SQL statements that import and apply the model. The SQL script contains placeholders that you replace with the names of concrete database objects in order to finally get the executable SQL script.
For more information, see:
You can find a practice exercise in using the idmmkSQL tool at Using idmmkSQL to work with your own mining models.
The IM Scoring package includes sample files consisting of a series of practice exercises in using IM Scoring. This tutorial material enables you to:
For more information refer to Introducing data mining functions.
For more information refer to Using IM Scoring Java Beans.
The IM Scoring sample files reside in the samples/ScoringDB2 directory of your IM Scoring installation. This directory contains the mining model, data, and scripts that you require to complete the exercises in this chapter.
On Windows(R) you can also use the shortcut IBM DB2 -> Business Intelligence Tools -> Intelligent Miner Scoring 8.2 -> Samples in the program folder.
The IM Scoring Java Beans examples are available in samples/ScoringBean.
Table 4 and Table 5 list the files that are included in the samples directory and explain the purpose of each.
| Sample file | Description |
|---|---|
| readme.txt | A README file containing instructions on how to use the sample files. |
| bankingScoring.data | A flat file containing records relating to the customers of a bank. This is the data to which you will apply the model. |
| bankingImport.db2 | A script that creates the DB2 sample table BANKING_SCORING, imports the file bankingScoring.data, and inserts the data into the new table. |
| clusDemoBanking.pmml | A Distribution-based Clustering model in PMML format. The model was built from data for a bank's customers who have a particular type of account. Customers are grouped according to similarities of age, income, number of siblings, gender, and account type. |
| bankingInsert.db2 | A script that imports the model, which is stored in the file clusDemoBanking.pmml, and then inserts the model into the table IDMMX.CLUSTERMODELS. |
| bankingExtract.db2 | A script that extracts the:
|
| bankingApplyView.db2 | A script that applies the imported Clustering model to the specified data from the table BANKING_SCORING. The script then obtains values from the calculated results using a common table expression. |
| bankingApplyTable.db2 |
A script that:
|
| bankingApplyResultSpec.db2 | A script that applies the imported Clustering model to the specified data from the table BANKING_SCORING using a result specification. Only the score and the quality for Cluster ID 3 are calculated. The script then obtains values from the calculated results using a common table expression. |
| bankingCacheModels.db2 | A script that manages the model cache to optimize performance and score a single record provided by the application. It loads Clustering models into IDMMX.CLUSTERMODELS from the file clusterModels.001. |
| bankingTriggerScoring.db2 |
This script uses triggers to recompute scores in real time whenever a data record changes. |
| bankingDelete.db2 | The script:
|
| clusterModels.del | The exported compressed model used in the script bankingCacheModels.db2. |
| clusterModelBlobs.001 | The exported compressed model used in the script bankingCacheModels.db2. |
| compressV7Models.db2 | The script compresses models that have been created with IM Scoring V 7.1. For more information refer to Migrating from IM Scoring V7.1 and Migrating from IM Scoring Version 8.1. |
| db2ExportModels | The template script to export a model from a table in the database to a file. |
| db2ImportModels | The template script to import a model from a file to a table in the database. |
| Sample file | Description |
|---|---|
| SampleDemoBanking.java | A sample program that applies a model in a DB2 database using the Java Single Record Scorer. |
| 93er_cars.pmml | A Polynomial Regression model |
| Sample93erCars.java | A sample Java program |
| readme.txt | A README file |
Before you can complete the practice exercises, you must install IM Scoring and configure the system environment as described in DB2 Intelligent Miner Modeling, DB2 Intelligent Miner Scoring, DB2 Intelligent Miner Visualization: Installing the Intelligent Miner products.
The tutorial introduces the following tasks:
db2 connect to dbnameIn this exercise, you create a table and import the banking data. You will later apply the mining model to this data.
To create a table and import the sample data, which is contained in the file bankingScoring.data, run the sample script bankingImport.db2 by using the following command:
db2 -stf bankingImport.db2
In the first part of the script bankingImport.db2, the DB2 table BANKING_SCORING is created, its columns are specified, and data types are defined for each column.
UPDATE COMMAND OPTIONS USING C off; CREATE TABLE "BANKING_SCORING" ( "CLIENT_ID" CHAR(9) NOT NULL PRIMARY KEY, "AGE" REAL, "GENDER" CHAR(2), "MARITAL_STATUS" CHAR(12), "PROFESSION" CHAR(24), "NBR_YEARS_CLI" REAL, "SAVINGS_ACCOUNT" CHAR(3), "HAS_LIFE_INSURANCE" CHAR(3), "INT_CREDITCARD" CHAR(3), "ONLINE_ACCESS" CHAR(3), "JOINED_ACCOUNTS" CHAR(3), "BANKCARD" CHAR(3), "AVERAGE_BALANCE" DECIMAL(10,2), "NO_CRED_TRANS" REAL, "NO_DEBIT_TRANS" REAL ) NOT LOGGED INITIALLY;
In the second part of the script the flat file bankingScoring.data is imported and inserted into the new table.
IMPORT FROM bankingScoring.data OF DEL INSERT INTO "BANKING_SCORING" ( "CLIENT_ID", "AGE", "GENDER", "MARITAL_STATUS", "PROFESSION", "NBR_YEARS_CLI", "SAVINGS_ACCOUNT", "HAS_LIFE_INSURANCE", "INT_CREDITCARD", "ONLINE_ACCESS", "JOINED_ACCOUNTS", "BANKCARD", "AVERAGE_BALANCE", "NO_CRED_TRANS", "NO_DEBIT_TRANS");
The third part of the script creates the view "BANKING_SCORING_N", which is used to score a model with a model signature that does not match the column names of this view.
CREATE VIEW "BANKING_SCORING_N"
("N_CUSTNO","N_AGE","N_GENDER","N_STAT","N_PROF","N_CARD",
"N_CTRANS","N_DTRANS")
AS SELECT "CLIENT_ID","AGE","GENDER","MARITAL_STATUS",
"PROFESSION","BANKCARD",
"NO_CRED_TRANS","NO_DEBIT_TRANS"
FROM "BANKING_SCORING";
In this exercise, you import the sample mining model into the DB2 database and store it in a DB2 table, which has a column configured for mining models.
To import the sample mining model, which is stored in the file clusDemoBanking.pmml, use the following command to run the sample script bankingInsert.db2:
db2 -stf bankingInsert.db2
The following script shows an example for AIX(R). It uses the function DM_impClusFile, which is specific to IM Scoring, to import the mining model contained in the file clusDemoBanking.pmml. The SQL INSERT command inserts the mining model into a column in the table CLUSTERMODELS, and sets the name of the model to DemoBanking. The table IDMMX.CLUSTERMODELS is configured for the data type DM_ClusteringModel.
INSERT INTO IDMMX."CLUSTERMODELS" ("MODELNAME","MODEL") VALUES
( 'DemoBanking', IDMMX.DM_impClusFile(
'/usr/opt/IMinerX/V8.2/samples/ScoringDB2/clusDemoBanking.pmml'));
You can apply mining models and obtain the results in one of the following ways:
The model used can be:
In addition, you can use a scoring result specification to customize the scoring results. The sample scripts shown in the following sections introduce you to these choices. For more information refer to Deployment scenarios.
Figure 6 gives an overview of applying a model.
In this exercise, you apply the Distribution-based Clustering model to the banking data to determine the customer segment for each customer in table BANKING_SCORING. The model is referenced by model name 'DemoBanking'. It is implicitly read from table IDMMX.CLUSTERMODELS into the model cache.
To apply the sample mining model and obtain the results of applying the model, use the following command to run the script bankingApplyView.db2:
db2 -stf bankingApplyView.db2
The first part of the script bankingApplyView.db2 applies a Clustering model to determine the customer segment for each customer in table BANKING_SCORING. The model is referenced by the model name DemoBanking. It is implicitly read from table IDMMX.CLUSTERMODELS into the model cache. The data values are obtained using a call to the DB2 function REC2XML. The displayed result contains the segment for each customer (CLUSTERID) and how good the customer fits into this segment (QUALITY).
WITH "CLUSTERVIEW"( "CLIENT_ID", "CLUSTERRESULT" ) AS
(
SELECT "CLIENT_ID",
IDMMX.DM_applyClusModel( 'DemoBanking',
rec2xml( 1.0, 'COLATTVAL', '',
"AGE","GENDER","MARITAL_STATUS","PROFESSION","BANKCARD",
"NO_CRED_TRANS","NO_DEBIT_TRANS" ) )
FROM "BANKING_SCORING"
)
SELECT "CLIENT_ID",
IDMMX.DM_getClusterID( "CLUSTERRESULT" ) AS "CLUSTERID",
CAST( IDMMX.DM_getQuality( "CLUSTERRESULT" ) AS DEC(5,4)) AS "QUALITY"
FROM "CLUSTERVIEW";
The next part of the sample script bankingApplyView.db2 performs the same scoring run. It joins the table that contains the data rows and the model table. The model uses a value of type BLOB with the model name DemoBanking. It is read from table IDMMX.CLUSTERMODELS explicitly.
WITH "CLUSTERVIEW"( "CLIENT_ID", "CLUSTERRESULT" ) AS
(
SELECT "CLIENT_ID",
IDMMX.DM_applyClusModel( C."MODEL" ,
IDMMX.DM_impApplData(rec2xml( 1.0, 'COLATTVAL', '',
B."AGE",B."GENDER",B."MARITAL_STATUS",B."PROFESSION",B."BANKCARD",
B."NO_CRED_TRANS",B."NO_DEBIT_TRANS" ) ) )
FROM "BANKING_SCORING" B, IDMMX."CLUSTERMODELS" C
WHERE C."MODELNAME"='DemoBanking'
)
SELECT "CLIENT_ID",
IDMMX.DM_getClusterID( "CLUSTERRESULT" ) AS "CLUSTERID",
CAST( IDMMX.DM_getQuality( "CLUSTERRESULT" ) AS DEC(5,4)) AS "QUALITY"
FROM "CLUSTERVIEW";
The following part of the script bankingApplyView.db2 shows how to map different column names in the input table to the names required by the model.
WITH
"DATAVIEW" ("CLIENT_ID","AGE","GENDER","MARITAL_STATUS","PROFESSION",
"BANKCARD","NO_CRED_TRANS","NO_DEBIT_TRANS") AS
...
The common table expression DATAVIEW maps the column names in the table/view (N_CUSTNO) and the field names in the model (CLIENT_ID).
(
SELECT "N_CUSTNO","N_AGE","N_GENDER","N_STAT","N_PROF","N_CARD","N_CTRANS",
"N_DTRANS"
FROM "BANKING_SCORING_N"
),
In the common table expression CLUSTERVIEW the model DemoBanking, referenced by name, is applied to selected data from the DATAVIEW common table expression by using the DM_applyclusModel function.
"CLUSTERVIEW"( "CLIENT_ID", "CLUSTERRESULT" ) AS
(
SELECT "CLIENT_ID",
IDMMX.DM_applyClusModel( C."MODEL" ,
IDMMX.DM_impApplData(rec2xml( 1.0, 'COLATTVAL', '',
D."AGE",D."GENDER",D."MARITAL_STATUS",D."PROFESSION",D."BANKCARD",
D."NO_CRED_TRANS",D."NO_DEBIT_TRANS" ) ) )
FROM "DATAVIEW" D, IDMMX."CLUSTERMODELS" C
WHERE C."MODELNAME"='DemoBanking'
)
SELECT "CLIENT_ID",
IDMMX.DM_getClusterID( "CLUSTERRESULT" ) AS "CLUSTERID",
CAST( IDMMX.DM_getQuality( "CLUSTERRESULT" ) AS DEC(5,4)) AS "QUALITY"
FROM "CLUSTERVIEW";
The input table data values (all attributes of one customer) are concatenated into an XML row string using the DB2 scalar function REC2XML.
Finally, the script obtains the cluster ID and the Clustering quality from CLUSTERRESULT using the functions DM_getClusterID and DM_getQuality.
To apply the sample mining model, store results, and obtain results values, run the script bankingApplyTable.db2 by using the following command:
db2 -stf bankingApplyTable.db2
The script file bankingApplyTable.db2 creates the DB2 table BANKING_SCORES for the mining results by defining the names and the data types of the columns. The column CLUSTER_RESULT is designated for the results that are calculated. The column is configured for the data type DM_ClusResult. The script then applies the DemoBanking model to selected data from the BANKING_SCORING table by using the DM_applyClusModel function. It stores the mining results into the BANKING_SCORES table.
Finally, it obtains the cluster ID and the Clustering quality from the CLUSTER_RESULT column of the new table by using the functions DM_getClusterID and DM_getQuality. Only the ClusterID and the Clustering quality of the customers older than 50 are retrieved by joining the tables BANKING_SCORING and BANKING_SCORES.
The following part of the sample avoids that the log file of large tables gets too full. If you execute large scoring runs in batch that write transaction data into tables, deactivate transaction logging as follows:
alter table activate not logged initiallyFor more information refer to the DB2 SQL Reference.
The following part of the sample script defines that the DB2 table BANKING_SCORING is created and its columns are specified. Data types are defined for each column in this script file:
CREATE TABLE "BANKING_SCORES" (
"CLIENT_ID" CHAR(9) NOT NULL PRIMARY KEY,
"CLUSTER_RESULT" IDMMX.DM_ClusResult
) NOT LOGGED INITIALLY;
INSERT INTO BANKING_SCORES ("CLIENT_ID", "CLUSTER_RESULT")
SELECT "CLIENT_ID",
IDMMX.DM_applyClusModel( C."MODEL" ,
IDMMX.DM_impApplData(rec2xml( 1.0, 'COLATTVAL', '',
B."AGE",B."GENDER",B."MARITAL_STATUS",B."PROFESSION",B."BANKCARD",
B."NO_CRED_TRANS",B."NO_DEBIT_TRANS" ) ) )
FROM "BANKING_SCORING" B, IDMMX."CLUSTERMODELS" C
WHERE C."MODELNAME"='DemoBanking';
The following part of the sample script commits a unit of work and reactivates autocommit:
COMMIT; UPDATE COMMAND OPTIONS USING C ON;
The following statement joins the tables BANKING_SCORING and BANKING_SCORES to retrieve the scores for records with 'AGE > 50'.
SELECT B."CLIENT_ID", CAST(B."AGE" AS SMALLINT) AS "AGE",
IDMMX.DM_getClusterID( S."CLUSTER_RESULT" ) AS "CLUSTERID",
CAST( IDMMX.DM_getQuality( S."CLUSTER_RESULT" )
AS DEC(5,4)) AS "QUALITY"
FROM BANKING_SCORING B JOIN BANKING_SCORES S ON
B."CLIENT_ID"=S."CLIENT_ID"
WHERE B."AGE" > 50;
You can also apply models and compute cluster IDs in a single SQL query. The following example shows an SQL query of this kind:
SELECT B."CLIENT_ID",
B."AGE",
B."GENDER",
B."MARITAL_STATUS",
B."PROFESSION",
IDMMX.DM_getClusterID(
IDMMX.DM_applyClusModel( C."MODEL" ,
IDMMX.DM_impApplData(rec2xml( 1.0, 'COLATTVAL', '',
B."AGE",
B."GENDER",
B."MARITAL_STATUS",
B."PROFESSION",
B."BANKCARD",
B."NO_CRED_TRANS",
B."NO_DEBIT_TRANS" ) ) ) )
FROM "BANKING_SCORING" B, IDMMX."CLUSTERMODELS"
C WHERE C."MODELNAME"='DemoBanking';
In this exercise, you apply the Distribution-based Clustering model to banking data and get the values of the calculated results. The result specification defines that your are only interested in cluster ID 3.
To apply the sample mining model and obtain the results of applying the model, use the following command to run the script bankingApplyResultSpec.db2:
db2 -stf bankingApplyResultSpec.db2
The sample script bankingApplyResultSpec.db2 defines a common table expression, "CLUSTERVIEW"( "CLIENT_ID","CLUSTERRESULT" ), to hold the results of applying a model. The script then applies the DemoBanking model to selected data from the banking table by using the DM_applyClusModel function with three parameters. The third parameter is a result specification for the cluster with ID=3. Use the DM_ClusResultSpec object to obtain quality and score for cluster with ID 3 for each customer in table BANKING_SCORING. The data values are obtained by calling the DB2 function REC2XML:
WITH "CLUSTERVIEW"( "CLIENT_ID","CLUSTERRESULT" ) AS
(
SELECT "CLIENT_ID", IDMMX.DM_applyClusModel( C."MODEL" ,
IDMMX.DM_impApplData(
rec2xml( 1.0, 'COLATTVAL', '',
B."AGE",B."GENDER",B."MARITAL_STATUS",B."PROFESSION",B."BANKCARD",
B."NO_CRED_TRANS",B."NO_DEBIT_TRANS" ) ) ,
IDMMX.DM_ClusResultSpec()..DM_setCluster(3) )
FROM "BANKING_SCORING" B, IDMMX."CLUSTERMODELS" C
WHERE C."MODELNAME"='DemoBanking'
)
SELECT "CLIENT_ID", 3 AS "CLUSTERID",
CAST( IDMMX.DM_getQuality( "CLUSTERRESULT",3 ) AS DEC(5,4)) AS "QUALITY"
FROM "CLUSTERVIEW" ;
In this exercise, you apply the Distribution-based Clustering model to the banking data and manage the model cache to optimize performance and score a single record provided by the application. This example loads two additional Clustering models into IDMMX.CLUSTERMODELS.
To apply the sample mining model and obtain the results of applying the model, run the script bankingCacheModels.db2 by using the following command:
db2 -stf bankingCacheModels.db2
The first part of the sample script bankingCacheModels.db2 loads two additional Clustering models into IDMMX.CLUSTERMODELS:
IMPORT FROM clusterModels.del OF DEL MODIFIED BY LOBSINFILE
INSERT INTO IDMMX."CLUSTERMODELS" ( "MODELNAME", "MODEL"); Then it closes all models to get reproducible results in this sample:
CALL IDMMX.DM_closeAllModels(1) ;
To optimize model caching the following sample code increases the size of the model cache to the number of models concurrently used in your database instance. To set the model cache size, define:
CALL IDMMX.DM_setEnv( 'IDM_MX_MAX_OPEN_MODELS', '10');
The following specification explicitly loads models into the model cache and gives them their name as an alias name prefixed with "CACHED_"::
SELECT IDMMX.DM_openModel("MODEL", 'CACHED_'||"MODELNAME") AS "MODELID"
FROM IDMMX."CLUSTERMODELS" WHERE "MODELNAME" LIKE 'DEMOMODEL_%';The sample code explicitly loads a model into the cache using the alias CachedDemoBanking and pins it:
INSERT INTO "MODELIDS"
SELECT "MODELNAME", IDMMX.DM_openModel("MODEL", 'CachedDemoBanking')
FROM IDMMX."CLUSTERMODELS" WHERE "MODELNAME" = 'DemoBanking';The sample code shows which models are currently in the cache:
CREATE VIEW "CACHEVIEW" AS
SELECT "MODELID",
CAST("MODELNAME" AS CHAR(20)) AS "MODELNAME",
CAST("MODELALIAS" AS CHAR(20)) AS "MODELALIAS", "PINNED"
FROM TABLE(IDMMX.DM_getOpenModels()) CT;
SELECT * FROM "CACHEVIEW"; The sample code uses one of the cached models for scoring a whole table:
SELECT "CLIENT_ID",IDMMX.DM_getClusterID(IDMMX.DM_applyClusModel(
'CachedDemoBanking', rec2xml( 1.0, 'COLATTVAL', '',
"AGE","GENDER","MARITAL_STATUS","PROFESSION","BANKCARD",
"NO_CRED_TRANS","NO_DEBIT_TRANS" ))) AS "CLUSTERID"
FROM "BANKING_SCORING";
It also uses the model cache for record scoring. In this sample the record to be scored can be dynamically provided by the SQL application without first storing it in the database. The following statement scores a single record with data values provided by the application:
WITH
"SCORER_INPUT"("AGE","GENDER","MARITAL_STATUS","PROFESSION","BANKCARD",
"NO_CRED_TRANS","NO_DEBIT_TRANS") AS
(
VALUES( 78.0,'F','widowed','pensioner','NO',28.0,89.0)
),
"SCORER_RESULT"("RESULT") AS
(
SELECT IDMMX.DM_applyClusModel('CachedDemoBanking',
rec2xml( 1.0,'COLATTVAL','',"AGE","GENDER","MARITAL_STATUS",
"PROFESSION","BANKCARD","NO_CRED_TRANS","NO_DEBIT_TRANS" ))
FROM "SCORER_INPUT"
)
SELECT
IDMMX.DM_getClusterID("RESULT") AS "CLUSTERID",
IDMMX.DM_getQuality("RESULT") AS "QUALITY"
FROM
"SCORER_RESULT";The following definition unloads a specific model from the cache:
SELECT "MODELID", IDMMX.DM_closeModel("MODELID") AS "UNLOAD_STATUS"
FROM "MODELIDS" WHERE "MODELNAME" = 'DemoBanking';The following statement shows that the model was unloaded:
SELECT * FROM "CACHEVIEW";
The following specification shows how the model cache is used implicitly for scoring (unpinned models). Unpinned models are cached until the configured cache size is reached.
SELECT "CLIENT_ID",IDMMX.DM_getClusterID(IDMMX.DM_applyClusModel('DemoBanking',
rec2xml( 1.0, 'COLATTVAL', '',
"AGE","GENDER","MARITAL_STATUS","PROFESSION","BANKCARD",
"NO_CRED_TRANS","NO_DEBIT_TRANS" ))) AS "CLUSTERID"
FROM "BANKING_SCORING";
SELECT * FROM "CACHEVIEW";
The following sample code cleans up the model cache and closes all models:
CALL IDMMX.DM_closeAllModels(1); DROP VIEW "CACHEVIEW"; DROP TABLE "MODELIDS";
To delete the demo models, the sample contains the following definition:
DELETE FROM IDMMX."CLUSTERMODELS" WHERE "MODELNAME" LIKE 'DEMOMODEL_%';
In this exercise, you use triggers to recompute scores in real time whenever a data record changes.
Use the following command to run the script bankingTriggerScoring.db2:
db2 -std@ -f bankingTriggerScoring.db2
The sample script defines model caching to optimize performance. The following part of the sample script sets the model cache size to contain 10 models:
CALL IDMMX.DM_setEnv('IDM_MX_MAX_OPEN_MODELS','10')@The following part of the sample code creates the table BANKING_SCORING_WITH_TRIGGER:
CREATE TABLE "BANKING_SCORING_WITH_TRIGGER" ( "CLIENT_ID" CHAR(9) NOT NULL PRIMARY KEY, "AGE" REAL, "GENDER" CHAR(2), "MARITAL_STATUS" CHAR(12), "PROFESSION" CHAR(24), "NBR_YEARS_CLI" REAL, "SAVINGS_ACCOUNT" CHAR(3), "HAS_LIFE_INSURANCE" CHAR(3), "INT_CREDITCARD" CHAR(3), "ONLINE_ACCESS" CHAR(3), "JOINED_ACCOUNTS" CHAR(3), "BANKCARD" CHAR(3), "AVERAGE_BALANCE" DECIMAL(10,2), "NO_CRED_TRANS" REAL, "NO_DEBIT_TRANS" REAL, -- folowing two fields computed by IM Scoring in triggers "CLUSTERID" INTEGER, "QUALITY" DOUBLE ) @
The following part of the sample code imports rows:
IMPORT FROM bankingScoring.data OF DEL INSERT INTO "BANKING_SCORING_WITH_TRIGGER" ( "CLIENT_ID", "AGE", "GENDER", "MARITAL_STATUS", "PROFESSION", "NBR_YEARS_CLI", "SAVINGS_ACCOUNT", "HAS_LIFE_INSURANCE", "INT_CREDITCARD", "ONLINE_ACCESS", "JOINED_ACCOUNTS", "BANKCARD", "AVERAGE_BALANCE", "NO_CRED_TRANS", "NO_DEBIT_TRANS")@
The following trigger computes column CLUSTERID and QUALITY when a new record is inserted. The model DemoBanking is loaded from table IDMMX.CLUSTERMODELS into the model cache:
CREATE TRIGGER "NEW_SCORE" NO CASCADE
BEFORE INSERT ON "BANKING_SCORING_WITH_TRIGGER"
REFERENCING NEW AS new_customer FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
DECLARE res IDMMX.DM_CLUSRESULT;
SET res =
IDMMX.DM_applyClusModel('DemoBanking',
rec2xml( 1.0, 'COLATTVAL', '',
new_customer."AGE",new_customer."GENDER",new_customer."MARITAL_STATUS",
new_customer."PROFESSION",new_customer."BANKCARD",
new_customer."NO_CRED_TRANS",new_customer."NO_DEBIT_TRANS" ) );
SET new_customer."CLUSTERID" = IDMMX.DM_getClusterID( res );
SET new_customer."QUALITY" = IDMMX.DM_getQuality ( res );
END
@ The following part of the sample code contains a trigger to update column CLUSTERID and QUALITY whenever a record is changed:
CREATE TRIGGER "UPDATE_SCORE" NO CASCADE
BEFORE UPDATE ON BANKING_SCORING_WITH_TRIGGER
REFERENCING NEW AS new_customer FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
DECLARE res IDMMX.DM_CLUSRESULT;
SET res =
IDMMX.DM_applyClusModel( 'DemoBanking',
rec2xml( 1.0, 'COLATTVAL', '',
new_customer."AGE",new_customer."GENDER",new_customer."MARITAL_STATUS",
new_customer."PROFESSION",new_customer."BANKCARD",
new_customer."NO_CRED_TRANS",new_customer."NO_DEBIT_TRANS" ) );
SET new_customer."CLUSTERID" = IDMMX.DM_getClusterID( res );
SET new_customer."QUALITY" = IDMMX.DM_getQuality ( res ); The following specification computes scores for all records that do not have a score (inserted before trigger creation or by the DB2 load utility):
UPDATE "BANKING_SCORING_WITH_TRIGGER" SET "AGE" = "AGE"
WHERE "CLUSTERID" IS NULL@
SELECT "CLIENT_ID", "BANKCARD", "CLUSTERID","QUALITY"
FROM "BANKING_SCORING_WITH_TRIGGER"@
The following statement updates a record and the UPDATE_SCORE trigger recomputes the score:
UPDATE "BANKING_SCORING_WITH_TRIGGER" SET "BANKCARD"='YES' WHERE "CLIENT_ID"='00501583'@ SELECT "CLIENT_ID", "BANKCARD", "CLUSTERID","QUALITY" FROM "BANKING_SCORING_WITH_TRIGGER" WHERE "CLIENT_ID"='00501583'@
The following statement inserts a record and the NEW_SCORE trigger computes the score:
INSERT INTO "BANKING_SCORING_WITH_TRIGGER"
( "CLIENT_ID","AGE","GENDER","MARITAL_STATUS","PROFESSION","NBR_YEARS_CLI",
"SAVINGS_ACCOUNT","HAS_LIFE_INSURANCE","INT_CREDITCARD","ONLINE_ACCESS",
"JOINED_ACCOUNTS","BANKCARD","AVERAGE_BALANCE","NO_CRED_TRANS",
"NO_DEBIT_TRANS")
VALUES ('00129241',+6.60000E+001,'F','married','worker',+3.00000E+000,'YES',
'NO','NO','NO','YES','YES',+00016319.00,+5.10000E+001,+3.66000E+002)
@
To score a model, you need to know the model signature. The model signature is the number and type of fields required as input. You can use IM Visualization to explore your models. In this exercise, you extract information from a model using the IM Scoring SQL APIs.
The model from which you extract information is the one that you inserted into the database as part of the exercise in the section Importing a mining model.
The information that you extract is:
To extract the information, run the script bankingExtract.db2 by using the following command:
db2 -stf bankingExtract.db2
In the first part of the script bankingExtract.db2, the SELECT statement extracts:
SELECT
SUBSTR(IDMMX.DM_getClusMdlName("MODEL"),1,20) AS MODELNAME,
IDMMX.DM_getNumClusters("MODEL") as NUMBER_CLUSTERS,
IDMMX.DM_getClusMdlSpec("MODEL")..DM_getNumFields() AS NUMBER_FIELDS,
CAST (IDMMX.DM_getMdlQuality("MODEL") AS DEC(5,2)) AS "MODEL_QUALITY"
FROM IDMMX."CLUSTERMODELS" WHERE "MODELNAME"='DemoBanking';
Use the following statement to show clusters in a Clustering model:
SELECT
"ID" AS "CLUSTERID",
CAST ("NAME" AS CHAR(20)) AS "CLUSTERNAME",
"SIZE",
CAST ("HOMOGENEITY" AS DEC(5,2)) AS "HOMOGENEITY"
FROM TABLE (IDMMX.DM_getClusters((
SELECT "MODEL" FROM IDMMX."CLUSTERMODELS"
WHERE "MODELNAME"='DemoBanking'))) AS "CLUSTERS"
ORDER BY SIZE DESC;
The following sample code shows the field importance in a Clustering model. The returned field names are the field names that must be used to apply the Clustering model in IM Scoring.
SELECT
CAST ("FIELDNAME" AS CHAR(20)) AS "FIELDNAME",
CAST ("IMPORTANCE" AS DEC(5,2)) AS "IMPORTANCE",
CASE "MININGTYPE"
WHEN 0 THEN 'CATEGORICAL'
WHEN 1 THEN 'NUMERICAL'
END AS "MINING_FIELD_TYPE"
FROM TABLE (IDMMX.DM_getFields((
SELECT "MODEL" FROM IDMMX."CLUSTERMODELS"
WHERE "MODELNAME"='DemoBanking'))) AS "FIELDS"
ORDER BY "IMPORTANCE" DESC;
In this exercise, you use IM Scoring Java Beans to score records. To do this, you use the sample program Sample93erCars.java, which you can find in the IM Scoring installation directory under samples/ScoringBean.
In the example, the minimum price of a car is predicted, given the basic characteristics for a car. The data used to train and generate the mining model contained a large number of fields, including:
The training data also contained the actual Minimum Price (in $1000), which was used as the predicted field when the mining model was generated. When IM Scoring Java Beans is used with this model, the scorer predicts the minimum car price for new, previously unseen data.
First, IM Scoring Java Beans is set up to be used for scoring runs. The section of code that follows shows the source code that is used to do this. Here, a constructor is provided that takes as its input parameter the name of the file in which the mining model is stored.
In the example, the model file 93er_cars.pmml is located in the same directory as the sample program. The constructor calls the method initModel(String modelFile), where the instance variable scorer is initialized with the new mining model. This initialization can be done by means of the constructor of the RecordScorer class, or by using the openModel(String modelFile) method.
This operation can take some time, because the mining model is loaded into memory, parsed, and interpreted for scoring. When this is complete, the initialized scorer is prepared for scoring.
Source code: Setting up the RecordScorer
public Sample93erCars(String modelFile ) {
initModel( modelFile );
}
public void initModel( String modelFile ) {
try {
// set the new model file and load the model as preparation for
// following scoring runs
if ( scorer == null ) {
scorer = new RecordScorer( modelFile );
} else scorer.openModel( modelFile );
} catch ( ModelException e ) {
e.printStackTrace();
}
}
When the setup of RecordScorer is complete, it can be used immediately for scoring on a record-by-record basis and for the reading of results. The source code given in Source code: Applying scoring on a record-by-record basis shows how this works.
The record that you want to score is the input for the doScoring(Map record) method. The call to scorer.score(record) computes the scoring result. The result is stored as an instance variable in the scorer object, and can be accessed now by means of the getPredictedValue() method. To keep the scoring API as simple and small as possible, there are no extra result objects provided for each of the model types. Instead, the RecordScorer provides a set of methods that are used to access the computed result fields. If a method is called that does not suit the actual model type, a ResultException is thrown. A call to getClusterID(), for example, instead of to getPredictedValue() in the code given in Source code: Applying scoring on a record-by-record basis would result in such an exception.
Source code: Applying scoring on a record-by-record basis
/**
* Applies scoring: Gets a record as input, applies scoring
* and displays the output.
* @param record the record used for scoring
*/
public void doScoring( Map record ) {
if ( scorer != null ) {
try {
// do scoring now
scorer.score( record );
// Before reading the results, validate that the
// model type is set to regression.
if ( scorer.getModelType() == Scorer.REGRESSION_TYPE ) {
double predictedValue = scorer.getPredictedValue();
displayPredictionResult( record, predictedValue,
"minimum car price" );
}
} catch ( Exception e ) {
// an error occurred while scoring the record
e.printStackTrace();
}
}
}
The code given in Source code: Accessing model metadata shows how access is gained to the metadata of the mining model that is used. For a specified model, it is possible to retrieve the active mining fields that are used, as well as the mining types of these fields. A field that is used by the mining model for the computation of the scoring result is known as an active mining field. In the method displayActiveFields(), the active fields and their related mining types are displayed.
Source code: Accessing model metadata
/**
* Displays the active fields of the mining model that was used.
* The active fields are the ones that are used by the mining
* model for scoring.
*/
public void displayActiveFields() {
if ( scorer != null ) {
String[] activeFields = scorer.getFieldNames();
if ( activeFields != null ) {
System.out.println( "\nActive Fields: " );
for ( int i=0; i<activeFields.length; i++ ) {
System.out.print( "Field Name: " + activeFields[i] );
if ( scorer.isCategoricalField( activeFields[i] ) ) {
System.out.println( ", Mining Type: categorical" );
} else {
System.out.println( ", Mining Type: numerical" );
}
}
}
}
}
The code given here in Source code: The main program shows the main program. Here, the following scenario is demonstrated:
Source code: The main program
public static void main( String[] args ) {
File file = new File( "93er_cars.pmml" );
Sample93erCars obj = new Sample93erCars( file.getAbsolutePath() );
HashMap record = new HashMap();
// A customer starts with the specification of some basic features
// that the car should have. The engine should be powerful, with
// 200 horsepower. The car should have good safety features,
// so that 2 airbags should be available.
// As well, it should use only a moderate amount of gas when
// being driven in the city.
// The estimated minimum price is predicted.
record.put( "Horsepower", new Integer(200) );
record.put( "Air Bags standard", new Integer(2) );
record.put( "City MPG", new Integer(17) );
carPricePredictor.doScoring( record );
// After hearing the estimated price, the customer gets more
// specific, and asks for some more features.
// The car should not be longer than 185 inches, and should be
// at least 68 inches wide.
record.put( "Width (inches)", new Integer(68) );
record.put( "Length (inches)", new Integer(185) );
carPricePredictor.doScoring( record );
// The customer now details the requirements for the engine and the
// driving behavior, and wants to know the new estimated price.
record.put( "Number of cylinders", new Integer(8) );
record.put( "RPM", new Integer(5500) );
record.put( "U-turn space (feet)", new Integer(40) );
carPricePredictor.doScoring( record );
// Finally, the customer adds some details about how the inside of
// the car should look.
// Note: If you look at the model 93er_cars.pmml, you will see that
// "Passenger capacity" and "Luggage capacity (cu.feet)" do not
// appear at all. This means that these features do not affect
// the predicted price. Even if the model does not contain these
// fields, they can be specified in the record.
record.put( "Rear seat room (inches)", new Integer(28) );
record.put( "Passenger capacity", new Integer(28) );
record.put( "Luggage capacity (cu. feet)", new Integer(30) );
carPricePredictor.doScoring( record );
}
To compile the Java program Sample93erCars.java:
This will generate the class file Sample93erCars.class.
To start the program, type java Sample93erCars.
The code given here in Results output for Sample93erCars shows the output of the program. The output demonstrates how the price varies with the new features that the car should have.
Results output for Sample93erCars:
Active Fields: Field Name: Width (inches), Mining Type: numerical Field Name: U-turn space (feet), Mining Type: numerical Field Name: City MPG, Mining Type: numerical Field Name: Air Bags standard, Mining Type: numerical Field Name: Rear seat room (inches), Mining Type: numerical Field Name: Horsepower, Mining Type: numerical Field Name: RPM, Mining Type: numerical Field Name: Number of cylinders, Mining Type: numerical Field Name: Length (inches), Mining Type: numerical Prediction result: Horsepower: 200 City MPG: 17 Air Bags standard: 2 ========================================= Minimum Car Price (in $1000): 30.45425764285364 Prediction result: Length (inches): 185 Horsepower: 200 Width (inches): 68 City MPG: 17 Air Bags standard: 2 ========================================= Minimum Car Price (in $1000): 32.57913872719416 Prediction result: Number of cylinders: 8 Length (inches): 185 U-turn space (feet): 40 Horsepower: 200 RPM: 5500 Width (inches): 68 City MPG: 17 Air Bags standard: 2 ========================================= Minimum Car Price (in $1000): 36.47348105441428 Prediction result: Width (inches): 68 U-turn space (feet): 40 City MPG: 17 Passenger capacity: 28 Air Bags standard: 2 Rear seat room (inches): 28 Horsepower: 200 RPM: 5500 Number of cylinders: 8 Luggage capacity (cu. feet): 30 Length (inches): 185 ========================================= Minimum Car Price (in $1000): 36.41880910964151
In this exercise, you generate a template SQL script using the command line tool idmmkSQL. You then edit the template SQL script to create the final script and execute it.
To do this exercise, you must first have successfully completed the steps described in Creating a table and importing data.
To generate a template SQL script that contains the necessary SQL statements to perform a scoring run:
idmmkSQL -d db2 clusDemoBanking.pmml clusDemoBanking.db2This generates the file clusDemoBanking.db2.
This depends on your operating system and your installation directory.
Column CLIENT_ID is used to identify the records. This appears twice in the file.
To run the script clusDemoBanking.db2, use the following command:
db2 -stf clusDemoBanking.db2
The script:
You can display the results using the following SQL statement:
SELECT * FROM RESULTTABLE
The results are the same as with the scripts bankingApplyView.db2, which you executed in a previous exercise.
In this exercise, you learn how to delete the entries from the sample tables that you have created during the exercises.
To run the script bankingDelete.db2, use the following command:
db2 -stf bankingDelete.db2
The following sample script:
UPDATE COMMAND OPTIONS USING O OFF; UPDATE COMMAND OPTIONS USING S OFF; DROP VIEW "BANKING_SCORING_N"; DROP VIEW "CACHEVIEW"; DROP TABLE "BANKING_SCORING"; DELETE FROM IDMMX."CLUSTERMODELS" WHERE "MODELNAME"='DemoBanking'; DELETE FROM IDMMX."CLUSTERMODELS" WHERE "MODELNAME" LIKE 'DEMOMODEL_%'; DROP TABLE "BANKING_SCORES"; DROP TABLE "MODELIDS"; DROP TRIGGER "NEW_SCORE"; DROP TRIGGER "UPDATE_SCORE"; DROP TABLE "BANKING_SCORING_WITH_TRIGGER";
This chapter guides you through the use of IM Scoring to perform data mining tasks within a DB2 database. Use IM Scoring to:
The database objects supplied with IM Scoring consist of the following:
These database objects are grouped together in the schema IDMMX. To access a UDT, UDF, or UDM, you must specify its fully-qualified name, for example, data type IDMMX.DM_ClusteringModel.
The data types, methods, and functions are designed along the proposed SQL Standard ISO/IEC 13249-6 SQL/MM Part 6: Data Mining.
Reference supplies overview lists and full descriptions of all the database objects supplied with IM Scoring.
The user-defined data types are used for identifying and storing mining models and results in DB2 tables. User-defined data types are also referred to as user-defined types or UDTs.
The user-defined data types provided by IM Scoring consist of distinct types and structured types.
Use user-defined methods to create or modify user-defined structured types. You can call the methods that are defined for a type by using either a method syntax or a function syntax.
Example:
In an appropriate context, specify the method name followed by, in parentheses, the structured type instance and the list of arguments.
Example:
select IDMMX.DM_getNumFields( IDMMX.DM_getClusMdlSpec(modelcolumn) )...
If the structured type instance is NULL, the method is not called, and NULL is returned.
IM Scoring provides scoring functions, also referred to as user-defined functions (UDFs), which enable you to:
Before you can use the UDTs, UDFs, and UDMs from SQL statements, they must be created in the database as database objects. This section contains instructions on how to create the database objects necessary for IM Scoring.
An example is provided in Creating database objects.
To create the database objects that are necessary, you must first enable the database for the use of IM Scoring. To enable the database, use the IM Scoring command idmenabledb, which is in the bin directory of your IM Scoring installation; for example:
idmenabledb mydb
The idmenabledb command gets the database name as an input parameter. It connects to the database, and creates the UDTs, UDFs, and UDMs in the database in the schema IDMMX. To execute idmenabledb, you must have SYSADM or DBADM authority.
You must call the idmenabledb command for each database that you want to use with IM Scoring.
The idmenabledb command is shared between IM Scoring and IM Modeling. You must call it only once for each database if you have both products installed. The command detects automatically which products are installed. It also detects which UDTs, UDFs, and UDMs already exist in the database and which ones must be created. To migrate from IM Scoring V7.1 to IM Scoring V8.2, you must call idmenabledb on the databases that were enabled for IM Scoring V7.1.
If you call idmenabledb and the only parameter that you specify is the database name, all the UDFs and UDMs are created in fenced mode. They run in a process separate from the DB2 server process. All model UDTs are created for a maximum size of 10 MB. Additional options allow you to change these default values.
For more information refer to The idmenabledb command.
The IM Scoring command idmdisabledb drops from the database all the IM Scoring UDTs, UDFs, and UDMs that were created. Call this command if you want to discontinue using a database with IM Scoring, or before you uninstall IM Scoring.
The idmdisabledb command gets the database name as its input parameter. It connects to the database and drops all the UDTs, UDFs, and UDMs that were created when the database and the schema IDMMX were enabled. To execute idmdisabledb, you must have SYSADM or DBADM authority.
You can only drop database objects if they do not depend on other database objects. If you have created tables using IM Scoring UDTs as column types, or if you have created triggers using some IM Scoring UDFs or UDMs, you must drop these database objects first, before you call idmdisabledb. It is possible that the only dependent database objects that you have are the sample tables created with idmenabledb. These tables are dropped if you call idmdisabledb with the tables option.
The idmdisabledb command is shared between IM Modeling and IM Scoring. If you have both products installed, you have to call the command only once for each database. If both products are installed, it is not possible to disable a database only for the use of one product. If a database was enabled for both products, the database should be disabled before any product is uninstalled.
The IM Scoring command idmcheckdb enables you to check whether a database is enabled or not.
The idmcheckdb command gets the database name as input. It connects to the database and returns a message saying whether the database is already enabled for IM Scoring, IM Modeling, or both.
idmcheckdb mydb The database "mydb" is enabled for IM Modeling Version 8.2 and IM Scoring Version 8.2 in fenced mode.
The idmcheckdb command also lists the database tables, which contain one or several objects of a type created for IM Scoring or IM Modeling.
This section shows how to obtain mining models to be scored in IM Scoring. Introducing IM Scoring familiarizes you with the tools for creating mining models. It also introduces you to the different model formats that can be used.
IM Modeling provides an SQL interface consisting of a set of database objects. These objects enable you to build data mining models in PMML 2.1 format from information held in IBM DB2 databases. IM Modeling writes the data mining models that it creates into tables, and these models can be directly used by IM Scoring. IM Modeling provides all model types that can be used by IM Scoring.
IM for Data stores models as results objects within an internal structure, and allows you to export these objects to an external file.
To export a results object, follow these steps:
If you export a model in PMML or XML format, an XML encoding is written into the file. The XML encoding is determined by the language environment and the locale of the IM for Data client V8.1.
For more information refer to Appendix F. Using IM Scoring in a multilanguage environment.
You can convert mining models in Intelligent Miner format to PMML 2.1 format by using the command line tool idmxmod. The input model in Intelligent Miner format must exist as a flat file. The output model in PMML format is also contained in a flat file.
For instructions on using this command line tool, see The idmxmod command.
The IM Scoring functions for importing mining models read a file that contains the mining model or a CLOB value from a database table that contains a PMML model. Each import function returns the mining model as data of one of the data types specific to IM Scoring.
You can use an SQL command to insert the returned data into a DB2 table where a column has been configured for the appropriate data type.
The IM Scoring package contains sample tables that are configured for the imported models.
Errors can occur in the following circumstances:
The import functions import a mining model from a file and return it as a value of the appropriate data type. Table 6 shows the relationship between the import function, the returned data type, and the sample table. For XML files, the XML encoding specification in the XML header is respected. If the encoding specification does not exist, UTF8 is assumed. For more information on encoding, see Appendix F. Using IM Scoring in a multilanguage environment.
| Import function | Data type | Table |
|---|---|---|
| DM_impClusFile | DM_ClusteringModel | IDMMX.CLUSTERMODELS |
| DM_impClasFile | DM_ClasModel | IDMMX.CLASSIFMODELS |
| DM_impRegFile | DM_RegressionModel | IDMMX.REGRESSIONMODELS |
| DM_impRuleFile | DM_RuleModel | IDMMX.RULEMODELS |
Figure 7 illustrates the relationship between model type, scoring functions, and the data type of the column in the DB2 table.
You can use the following command from the command line to import the file myclusters.xml and insert it into the CLUSTERMODELS table in your schema:
db2 insert into IDMMX.CLUSTERMODELS (MODELNAME, MODEL)
values ('CustomerSegments', IDMMX.DM_impClusFile('/tmp/myclusters.xml'))
With IM Scoring's import functions, you can override the encoding specification given in the XML file and explicitly specify the encoding to be assumed for the file to be imported.
The import functions of IM Scoring listed in Table 7 use a specific XML encoding to import a mining model from a file and return it as a value of the appropriate data type.
Specifying an XML encoding can be required, for example, if the encoding specified in the file is an unsupported name for a supported code page, or if the encoding of the file has been changed without changing the encoding written in the file.
Table 7 shows the relationship between the import function, the returned data type, and the sample table. The encoding of characters in the imported file is given explicitly. For more information on encodings, see Appendix F. Using IM Scoring in a multilanguage environment.
| Import function | Data type | Table |
|---|---|---|
| DM_impClusFileE | DM_ClusteringModel | IDMMX.CLUSTERMODELS |
| DM_impClasFileE | DM_ClasModel | IDMMX.CLASSIFMODELS |
| DM_impRegFileE | DM_RegressionModel | IDMMX.REGRESSIONMODELS |
| DM_impRuleFileE | DM_RuleModel | IDMMX.RULEMODELS |
You can use the following command from the command line to import the file myclusters.xml and insert it into the CLUSTERMODELS table in your schema:
db2 insert into IDMMX.CLUSTERMODELS (MODELNAME, MODEL)
values( 'CustomerSegments',
IDMMX.DM_impClusFileE('/tmp/myclusters.xml', 'iso-8859-1' )
You can use import functions that import a PMML model that already resides in a database table column as a CLOB value.
Table 8 shows the relationship between the import function, the returned data type, and the sample table.
| Import function | Data type | Table |
|---|---|---|
| DM_impClusModel | DM_ClusteringModel | IDMMX.CLUSTERMODELS |
| DM_impClasModel | DM_ClasModel | IDMMX.CLASSIFMODELS |
| DM_impRegModel | DM_RegressionModel | IDMMX.REGRESSIONMODELS |
| DM_impRuleModel | DM_RuleModel | IDMMX.RULEMODELS |
The following is an example of the use of these import functions.
db2 insert into IDMMX.CLUSTERMODELS (MODELNAME, MODEL) select modelname,
IDMMX.DM_impClusModel( model) from PMMLCLUSTERMODELS
It can be time consuming to manually write the SQL scripts that contain the necessary SQL statements for applying a model to a set of input records. This is especially the case if there are a lot of mining fields. For this reason, IM Scoring provides a separate tool, the idmmkSQL command, that generates from mining models the SQL statements that you need. The tool:
The template script contains placeholders for actual values like table names or file names. You have to manually insert these values into the template to get the final SQL script.
The idmmkSQL command supports the different ways of building input data records for the application functions that are provided by IM Scoring. The tool has a command line interface. The type of SQL and the method of building input data records can be controlled by command line parameters.
For instructions on using this tool, see The idmmkSQL command.
You can extract, for example, the following information from a model in the database:
To extract the information, you define a script and then run the script. An example of how to extract information is provided in Extracting information from a model.
This section contains instructions on applying mining models. It is important to get the best possible result when you apply a model to new data records. To ensure this, provide a value in a data record for each active field in the model. The data record consists of a set of field names and their values. The field names in the set match the names of the active fields in the model.
If necessary, you can access information about the active fields in your model. For a sample script that does this, see Extracting information from a model.
Use the DM_getFields table function to identify the model fields and their importance. For more information refer to DM_getFields.
Errors can occur if any of the following is the case:
IM Scoring includes functions that apply imported mining models to selected data. Table 9 lists each function together with a brief summary of how it is used.
| Application function | Purpose |
|---|---|
| DM_applyClusModel | Applies a model to selected data to produce results
data, grouped into clusters. Clusters are identified when the model is built.
They identify similar characteristics in data.
A possible use of this function is in producing targeted mailshots. |
| DM_applyClasModel | Applies a model to selected data to produce results
data that is classified according to rules established when the model is built.
A possible use of this function is in classifying insurance risks. |
| DM_applyRegModel | Applies a model to selected data to calculate a predicted
value. The predicted value is based on the values of input fields, according
to a pattern established when the model is built.
A possible use of this function is in ranking customers. |
Each function has the following input arguments:
<row><column name="DEPTNO">D01</column> <column name="MGRNO" null= "true"/> <column name="ADMRDEPT">A00</column></row>
There are several ways of how to construct this XML string. The most convenient and best performing way is to use the DB2 REC2XML function. For the apply functions that expect an object of type DM_ApplicationData, you must use the DM_impApplData function to convert the REC2XML output of type VARCHAR into type DM_ApplicationData. For example:
IDMMX.DM_impApplData( REC2XML( ... ) )
The following list shows how to invoke the various types of the DM_applyXXXModel functions:
Where XXX can be CLAS, CLUS, or REG. An example is:
IDMMX.DM_applyClusModel( 'DemoBanking', rec2xml( 1.0, 'COLATTVAL', '', "AGE","GENDER","MARITAL_STATUS" ) )
Where XXX can be CLAS, CLUS, or REG. An example is:
SELECT IDMMX.DM_applyClusModel( C."MODEL" ,
IDMMX.DM_impApplData(rec2xml( 1.0, 'COLATTVAL', '',
B."AGE",B."GENDER",B."MARITAL_STATUS") ) )
FROM "BANKING_SCORING" B, IDMMX."CLUSTERMODELS"
C WHERE C."MODELNAME"='DemoBanking'
Clustering and Classification in addition allow to customize the scoring result with a third optional parameter:
IDMMX.DM_applyClusModel( 'DemoBanking', rec2xml( 1.0, 'COLATTVAL', '', "AGE","GENDER","MARITAL_STATUS" ), IDMMX.DM_ClusResultSpec()..DM_setCluster(3) )
SELECT IDMMX.DM_applyClusModel( C."MODEL" , IDMMX.DM_impApplData( rec2xml( 1.0, 'COLATTVAL', '', B."AGE",B."GENDER",B."MARITAL_STATUS") ) , IDMMX.DM_ClusResultSpec()..DM_setCluster(3) ) FROM "BANKING_SCORING" B, IDMMX."CLUSTERMODELS" C WHERE C."MODELNAME"='DemoBanking'
The function returns results data that contains the values that the mining logic calculates.
The field names contained in the XML data record value are mapped to the fields in the applied model using the following logic:
Use the DB2 built-in function REC2XML for performance-critical applications to build a data record. REC2XML gets a number of control parameters and a list of columns as input. The output is an XML string containing pairs consisting of column names and values. This XML string can be used as the input to the DM_impApplData function. This function returns the XML string as data type DM_ApplicationData, which is the correct data type to be used as input parameter to some of the application functions.
For example:
select IDMMX.DM_impApplData(rec2xml
(1.0, 'COLATTVAL', '', CHARCOL, DOUBLECOL)) ...
REC2XML is described in the DB2 SQL Reference. For your convenience, that description is also given here in Appendix D. The DB2 REC2XML scalar function.
For an example of its use, see Applying a model and getting results values.
Use the function DM_applData to build a data record where both of the following are true:
You must call DM_applData for each column that goes into the data record. The function returns an XML string consisting of a field name/value pair of type DM_ApplicationData. DM_applData is called in a nested way, because the return value of the function is the input to the next call of the function. The function then appends its field name/value pair to the input XML string, and returns the whole XML string. The input parameters to the function DM_applData are as follows:
If you use DM_applData on a table, the values are specified using the column name.
For example, the following call corresponds to the call described in Specifying data by means of CONCAT:
IDMMX.DM_applData( IDMMX.DM_applData( 'CHARCOL', CHARCOL ) , 'DOUBLECOL', DOUBLECOL )
Use the built-in function REC2XML for performance-critical applications. You can also use the built-in operator CONCAT, or the corresponding characters ||, in a sequence to construct the type DM_ApplicationData. For more information on the required format of the string, see DM_impApplData.
For example, the following calls correspond to the example described in Specifying data by means of DM_applData.
IDMMX.DM_impApplData('<row><column name="CHARCOL">'
||CHARCOL||'</column> '||'column name="DOUBLECOL">'
||CHAR(DOUBLECOL)||'</column></row>')
If the columns CHARCOL and DOUBLECOL have NULL values, you must call CONCAT as follows:
IDMMX.DM_impApplData('<row><column name="CHARCOL"'
||coalesce('>'||CHARCOL,' null="true">'
)||'</column>'||'<column name="DOUBLECOL"'
||coalesce('>'||CHAR(DOUBLECOL),' null="true">'
)||'</column></row>')
The results data from each of the scoring functions is identified by a data type that is specific to IM Scoring. Table 10 lists the application functions together with their data types and results data.
| Application function | Data type | Results data |
|---|---|---|
| DM_applyClusModel | DM_ClusResult | Cluster ID, score, quality, confidence |
| DM_applyClasModel | DM_ClasResult | Predicted class, confidence |
| DM_applyRegModel | DM_RegResult |
|
Figure 8 illustrates the process by which data is selected and a model is applied. Values for the fields age and salary are read from a database table to form an instance of the data type DM_ApplicationData. This data and the model, ClusterModel, form the input to the function DM_applyClusModel. The results of applying the model consist of a cluster ID and a cluster score. The results are returned as data type DM_ClusResult.
IM Scoring enables you to customize the results data. In addition to or in replacement of the default results data listed in Results data, new results data can be calculated during the scoring run and made accessible in the application result. Table 11 lists the application functions together with their data types and specifiable results data.
| Application function | Results data type | Specifiable results data |
|---|---|---|
| DM_applyClusModel | DM_ClusResult | Score and quality for a specified cluster |
| DM_applyClasModel | DM_ClasResult | Confidence for a specified class, node ID used for the prediction (if a Tree Classification model was used) |
| DM_applyRegModel | DM_RegResult |
The specifiable results data is created in the result only if the user requests it. To do this, the user indicates in the call to the application function which results data has to be inserted in the result object. IM Scoring defines overloaded application functions that take the following parameters:
IDMMX.DM_ClusResultSpec()
Then invoke some methods on this object indicating which results data has to be calculated during the scoring run and set in the result, for example:
IDMMX.DM_ClusResultSpec()..DM_setBestCluster()..DM_setCluster(3)If the result specification object is empty, an error is returned. Having the default results data in the scoring result can be set at once, and having the specifiable results data indicated in Table 11 in the scoring result can be individually specified. The result specification object is of type DM_ClusResultSpec for clustering or DM_ClasResultSpec for classification.
The application functions return results data that the mining logic calculates according to the result specification object.
The methods used to generate a result specification object are described in Table 12 for the type DM_ClasResultSpec and in Table 13 for the type DM_ClusResultSpec.
| DM_ClasResultSpec function | Purpose |
|---|---|
| DM_setPredClass | Specifies that the default results data (predicted class and confidence in this prediction) has to be calculated and written into the scoring result. |
| DM_setClass(class) | Specifies that a confidence value for the specified class has to be calculated and written into the scoring
result.
This function can be called several times with different classes. |
| DM_setAllClasses | Specifies that a confidence value for all classes of the predicted field has to be calculated and written into the scoring result. |
| DM_setTreeNodeID | Specifies that the node ID used for predicting the class
and confidence has to be written into the scoring result.
The node ID is a string that gives the following binary path from the root to the node used for the prediction:
Notes:
|
| DM_ClusResultSpec function | Purpose |
|---|---|
| DM_setBestCluster | Specifies that the default results data (cluster ID, score, quality, and confidence of the best cluster) has to be calculated and written into the scoring result. |
| DM_setCluster(clusterid) | Specifies that a score and a quality for the specified
cluster (indicated by its cluster ID) has to be calculated and written into
the scoring result.
This function can be called several times with different cluster IDs. |
IM Scoring includes results functions that obtain the different results values calculated within the application functions. This section lists and describes these functions. It also includes information about situations where input records contain NULL values; this is in Handling missing values.
Table 14 lists the results functions and describes the value that each function returns when a Clustering model is applied.
| Results function | Purpose |
|---|---|
| DM_getClusterID | Obtains the cluster ID from results data calculated when a Clustering model is applied. This identifies the position of the cluster in the Clustering model that was the best match for this data record. The position of the cluster is a value between 1 and the number of clusters. |
| DM_getClusScore | Obtains the score of the best cluster from results data calculated when a Clustering model is applied. The score is a measure of how closely the data matches the cluster. |
| DM_getClusScore(clusterid) | Returns the Clustering quality for a specified cluster from results data calculated when a Clustering model is applied. The calculation for this cluster ID must have been specified (in a DM_ClusResultSpec object given as the 3rd parameter for the application function) as the result object was calculated. |
| DM_getQuality | Returns the quality of the best cluster from results data calculated when a Clustering model is applied. The quality is a measure of how well the data fits into the cluster. |
| DM_getQuality(clusterid) | Returns the quality for a specified cluster from results data calculated when a Clustering model is applied. The calculation for this cluster ID must have been specified (in a DM_ClusResultSpec object given as the 3rd parameter for the application function) as the result object was calculated. |
| DM_getClusConf | Returns the confidence of attributing a record to the best cluster in comparison with attributing it to another cluster of the applied model. |
Table 15 lists the results functions and describes the value that each function returns when a Classification model is applied.
| Results function | Purpose |
|---|---|
| DM_getPredClass | Obtains the predicted class from results data calculated when a Classification model is applied. This identifies the class within the model to which the data matched. |
| DM_getConfidence | Obtains the classification confidence value from results data calculated when a Classification model is applied. This is a value between 0.0 and 1.0; it measures the probability that the class is predicted correctly. |
| DM_getConfidence(class) | Obtains the classification confidence value for a specified class from results data calculated when a Classification model is applied. The calculation for this class must have been specified (in a DM_ClasResultSpec object given as 3rd parameter for the application function) as the result object was calculated. |
| DM_getTreeNodeID | Obtains the node ID used to predict the predicted class from results data calculated when a Tree Classification model is applied. The calculation for this node ID must have been specified (in a DM_ClasResultSpec given as the 3rd parameter for the application function) as the result object was calculated. |
Table 16 lists the results functions and describes the value that each function returns when a Regression model is applied.
| Results function | Purpose |
|---|---|
| DM_getPredValue | Obtains the predicted value from results data calculated when a Regression model is applied. This value is calculated according to relations established by the model. |
| DM_getPredStdDev | Obtains the standard deviation of the prediction around the predicted value from results data calculated when a Transform Regression model is applied. |
| DM_getPredDev(prob) | Obtains the deviation around the predicted value where the prediction is true with a probability of prob from results data calculated when a Transform Regression model is applied. |
| DM_getConfidence(low, up) | Obtains the confidence in predicting a value in the specified interval (low, up) from results data calculated when a Transform Regression model is applied. |
| DM_getRBFRegionID | Obtains the number of the region from results data calculated when an RBF Regression model is applied. This identifies the region within the model that the record was assigned to. |
To obtain the results of applying a model, you run the appropriate results function, giving the return value of an application function as a parameter. This can be one of the following:
WITH "CLUSTERVIEW"( "CLIENT_ID", "CLUSTERRESULT" ) AS ( SELECT "CLIENT_ID", IDMMX.DM_applyClusModel( 'DemoBanking', rec2xml( ... ) ) FROM "BANKING_SCORING" ) SELECT "CLIENT_ID", IDMMX.DM_getClusterID( "CLUSTERRESULT" ) AS "CLUSTERID", FROM "CLUSTERVIEW";
INSERT INTO "SCORINGRESULTS"("CUSTNO",
"CLFRESULT") SELECT "CUSTNO",
IDMMX.DM_applyClasModel('RiskModel',
REC2XML(...)) FROM "MYDATA" s WHERE ...;
SELECT CUSTNO, IDMMX.DM_getPredClass("CLFRESULT") FROM "SCORINGRESULTS";SELECT CUSTNO, IDMMX.DM_getPredClass( IDMMX.DM_applyClasModel('RiskModel',
REC2XML(...))) FROM "MYDATA"You use common table expressions or pass the return value of the application function directly if you use only a single statement. That is, you apply the model and obtain the results value within a single statement. You use the database column name if the results of applying the model were stored in a DB2 table.
If you specify a column name, and the column is not configured for the correct results data type, an error occurs. See Table 10 for the relationships between results functions, results data types, and results data.
A results function might return a NULL value. This means that the application function that calculated the result could not determine this value, because of one of the following reasons:
Input records might contain one or more values that are NULL; these are known as missing values. The handling of missing values in IM Scoring depends on the algorithm.
With IBM models, a sophisticated value treatment is used. If a missing value occurs, the record being scored is fed into both child nodes (binary tree) of the tree node requiring the missing value. This process continues until the record reaches a leaf node. Thus, a record is assigned to more than one leaf node. Tree Classification aggregates all these leaf nodes, and DM_getPredClass returns the value assigned to this aggregated node.
IM Scoring provides a memory cache for mining models that improves the performance of scoring runs and allows real-time scoring. Real-time scoring ensures a fast response time for a scoring run of a single input record with an execution time that takes only a few milliseconds. Model caching allows to perform a scoring run in real time if:
Model caching allows to keep models in main memory for subsequent scoring runs. If there is no model cache, the model is deleted from the main memory after the scoring run (using the SELECT statement) has been finished. If a model is permanently stored in memory, a scoring run using this model is faster, because the initial loading and parsing phase can be skipped.
Models in the cache can be:
The scoring run is performed without adding the model to the cache if the:
Unpinned models are implicitly loaded into the cache with an apply UDF. They can be removed from the cache at any time if a new model requires cache space. The variable IDM_MX_MAX_OPEN_MODELS controls the number of unpinned models in the cache only.Scoring apply UDFs are provided to identify the model by its name. In this case it is not required to pass the complete model as a large object (LOB) to the function. For more information refer to DM_openModel.
There is one model cache for each database instance. The main memory for the cache is allocated in the db2fmp process of DB2 V8, which runs stored procedures and user-defined functions (UDFs). If an error occurs during this process, DB2 creates a new db2fmp process. In this case models in the cache are lost and the new process starts with an empty cache using the default cache size.
Use the following configuration parameters and UDFs for model caching:
CALL IDMMX.DM_setEnv( 'IDM_MX_MAX_OPEN_MODELS', '3');
Caching of unpinned models is disabled if you specify:
CALL IDMMX.DM_setEnv( 'IDM_MX_MAX_OPEN_MODELS', '0');For more information refer to Setting the model cache size.
A model cache can significantly improve the scoring speed of one or a few records against a model that is already in the cache. This is especially important for large models that need a lot of time for the open phase.
The scoring run can be a bit slower than without cache:
The size of the cache must relate to the available memory of the machine and the size of the models to be scored. You can adapt the size according to your requirements or disable the model cache to save memory.
The model cache can hold pinned models and unpinned models:
If you change the environment variable IDM_MX_MAX_OPEN_MODELS to a lower value, this setting does not have an immediate effect on the cache. The variable is read again on the next cache operation that adds a model to the cache. In this case the unpinned model might be removed from the cache to satisfy the maximum cache size. The models are only deleted if they are not in use.
The environment variable can be set using the stored procedure DM_setEnv(). If the environment variable is set to a value that does not represent an integer, or to an integer value < 0, the variable is ignored and the default (1 model) is used. This variable setting is only valid for the currently running db2fmp process.
Here you find examples on how to specify real-time scoring:
SELECT IDMMX.DM_openModel(model, NULL)
FROM IDMMX.CLUSTERMODELS
WHERE MODELNAME = 'DemoBanking';The SELECT statement
returns a modelID, which can be used to remove the
model from the cache again:
VALUES ( IDMMX.DM_closeModel( modelID ) );CREATE TABLE TEMPTABLE (MODELNAME VARCHAR(240), MODELID BIGINT);
INSERT INTO TEMPTABLE
SELECT MODELNAME, IDMMX.DM_openModel(model, NULL)
FROM IDMMX.CLUSTERMODELS WHERE MODELNAME = 'DemoBanking';
Perform the scoring run and close the model later:
SELECT IDMMX.DM_getClusterID(IDMMX.DM_applyClusModel(C.MODEL,
IDMMX.DM_impApplData(
rec2xml( 1.0, 'COLATTVAL', '', B.TYPE, B.AGE, B.SIBLINGS,
B.INCOME ))))
FROM BANKING_SCORING B,IDMMX.CLUSTERMODELS C WHERE
C.MODELNAME='DemoBanking';
SELECT IDMMX.DM_closeModel(MODELID) FROM TEMPTABLE WHERE
MODELNAME = 'DemoBanking';
DROP TABLE TEMPTABLE;CALL IDMMX.DM_setEnv( 'IDM_MX_MAX_OPEN_MODELS', '2');
SELECT IDMMX.DM_getClusterID(IDMMX.DM_applyClusModel(C.MODEL,
IDMMX.DM_impApplData(
rec2xml( 1.0, 'COLATTVAL', '', B.TYPE, B.AGE, B.SIBLINGS,
B.INCOME ))))
FROM BANKING_SCORING B, IDMMX.CLUSTERMODELS C WHERE
C.MODELNAME='DemoBanking';
SELECT IDMMX.DM_openModel(model, 'NeuralModel')
FROM IDMMX.CLUSTERMODELS WHERE MODELNAME = 'NeuralBanking';
You can retrieve the cache information with the following select statement:
SELECT CT.* FROM TABLE(IDMMX.DM_getOpenModels()) CT;Here is an example of the result of such a select statement:
MODELID MODELNAME ALIAS USER TIMESTMP PINNED SIZE USECOUNT
------------- ----------------------- ------- ---------- -------------------------- ----------- ----------- --------
7 DemoBanking paul 2004-12-13-14.01.14.354001 0 12340 0
17 NeuralBanking NeuralModel claudia 2004-12-13-14.03.15.549000 1 434354 0CALL IDMMX.DM_closeAllModels(1);
CALL IDMMX.DM_setEnv( 'IDM_MX_MAX_OPEN_MODELS', '0');After the scoring run, the model is not cached:
SELECT IDMMX.DM_getClusterID(IDMMX.DM_applyClusModel(C.MODEL,
IDMMX.DM_impApplData(
rec2xml( 1.0, 'COLATTVAL', '', B.TYPE, B.AGE,
B.SIBLINGS, B.INCOME ))))
FROM BANKING_SCORING B, IDMMX.CLUSTERMODELS C
WHERE C.MODELNAME='DemoBanking';
SELECT CT.* FROM TABLE(IDMMX.DM_getOpenModels()) CT; Reset the default:
CALL IDMMX.DM_setEnv( 'IDM_MX_MAX_OPEN_MODELS', '1');
SELECT IDMMX.DM_openModel(model, 'DemoBankingAlias')
FROM IDMMX.CLUSTERMODELS WHERE MODELNAME = 'DemoBanking';
WITH
SCORER_INPUT(TYPE, AGE, SIBLINGS, INCOME) AS
(
VALUES( "red ", 27, 1, 6611 )
),
SCORER_RESULT(RESULT) AS
(
SELECT IDMMX.DM_applyClusModel('DemoBankingAlias',
rec2xml( 1.0, 'COLATTVAL', '',
TYPE, AGE, SIBLINGS, INCOME) AS RESULT)
FROM SCORER_INPUT
)
SELECT
IDMMX.DM_getClusterID(RESULT) AS CLUSTER_ID,
IDMMX.DM_getClusScore(RESULT) AS SCORE,
IDMMX.DM_getQuality(RESULT) AS QUALITY,
IDMMX.DM_getClusConf(RESULT) AS CONFIDENCE
FROM
SCORER_RESULT;
IDMMX.DM_closeAllModels(1);This section describes the interfaces of IM Scoring Java Beans.
To perform the scoring of a data record, you must specify the following input:
When you have specified the necessary input, you can apply scoring and then access the result fields that have been computed.
The functions of IM Scoring Java Beans are implemented as methods of class com.ibm.iminer.scoring.RecordScorer.
\doc\ScoringBean\index.html
After you have installed IM Scoring Java Beans, you must set environment variables before you can use it from Java applications.
For a Java application to invoke RecordScorer, you must do the following:
The xerces.jar package is the XML4J package needed for XML parsing. It is copied into the java directory during the installation of IM Scoring Java Beans. It is possible, however, to use any other implementation of the XML4J specification.
For more information on how to set an environment variable refer to the documentation of your platform. For more information on IM Scoring Java Beans refer to the samples readme.
This section describes how to specify the model.
The RecordScorer class expects the mining model to be stored in one of the following:
public RecordScorer( String modelFile )
throws ModelException, SQLException
public void openModel( String modelFile ) throws ModelException
When a new mining model is set, this model is loaded explicitly into memory. Loading the mining model means reading the PMML file, interpreting the mining model, and preparing everything for scoring. For big mining models, for example, those with a size of more than 50 MB, this operation might take some time. After the mining model has been loaded, the model is kept interpreted in memory. For consecutive scoring calls, the loaded and prepared mining model is used, so that the scoring of a single record needs a response time of less than a second.
When a mining model is set, it remains loaded until one of the following happens:
public RecordScorer(java.sql.Connection connection,
java.lang.String table,
java.lang.String keyColumn,
java.lang.String modelColumn,
java.lang.String modelKey)
throws ModelException, SQLException
The model is expected in the table table (format:
table or schema.table). The table must have at least two columns, keyColumn and modelColumn. The key column is used to select the desired row in the table, the model column contains the model itself. Parameter modelKey denotes the key which is used to select the row that contains
the model.
public synchronized void openModel(java.sql.Connection connection,
java.lang.String table,
java.lang.String keyColumn,
java.lang.String modelColumn,
java.lang.String modelKey)
throws ModelException, SQLExceptionIf openModel is called with the same parameters as in a previous call,
the model is opened again. That is, the model in the record scorer can be
refreshed when the instance in the database has changed.
The exception ModelException is thrown if one of the following happens:
The following example contains the mining model in a table that has at least two columns:
// open JDBC connection to database dbname
Class.forName("com.ibm.db2.jcc.DB2Driver");
String url="jdbc:db2://localhost:50000/"+dbname;
Connection myConnection =
java.sql.DriverManager.getConnection(url,uid,pw);
// load the model as preparation for
// following scoring runs
String modelname="DemoBanking";
if ( scorer == null ) {
scorer = new RecordScorer(myConnection,
"IDMMX.CLUSTERMODELS",
"MODELNAME",
"MODEL",
modelname);The RecordScorer class provides a set of methods that can be used to access the metadata of the mining model that is specified. These are as follows:
| Method | Method description |
|---|---|
| public String[] getFieldNames() | Returns the names of the mining fields used by the mining model to perform scoring. If no correct model is specified, a String[0] array is returned. |
| public String[] getCategoricalFields() | Returns the names of the categorical mining fields used by the mining model to perform scoring. If no correct model is specified, a String[0] array is returned. |
| public String[] getNumericalFields() | Returns the names of the numerical mining fields used by the mining model to perform scoring. If no correct model is specified, a String[0] array is returned. |
| public boolean
isCategoricalField(String fieldName) |
Returns true if the field specified by fieldName is a categorical mining field. Otherwise, false is returned. |
| public boolean
isNumericalField(String fieldName) |
Returns true if the field specified by fieldName is a numerical mining field. Otherwise, false is returned. |
| public boolean isField(fieldname) | Returns true if the field specified by fieldName is one of the active mining fields. Otherwise, false is returned. |
| public int getModelType() | Returns an integer value that identifies the type of the model that was used. For this, the constant CLUSTERING_TYPE, CLASSIFICATION_TYPE, REGRESSION_TYPE, and UNDEFINED_TYPE are defined in the Scorer class. |
| public int[] getResultIdentifiers() | Returns the identifiers of the result fields that are
relevant for the model type that is set. For this, there are additional constants
defined in the class Scorer:
|
You can represent a data record by a mapping. Here, the names of the fields used in the records are mapped to their actual values. This is exactly the way in which a record is represented in the RecordScorer class. A java.util.Map object is instantiated, and a mapping between field names and values is defined. For example:
HashMap record = new HashMap();
record.put("Horsepower", new Integer(200) );
record.put("Air Bags standard", new Integer(2) );
record.put("City MPG", new Integer(17) );
Note that the values of categorical fields are interpreted as java.util.String, and the values of numerical fields are expected to inherit from java.lang.Number.
IM Scoring Java Beans can be used to score single or multiple data records using a specified mining model. IM Scoring Java Beans is designed to be used for applications where the online scoring of data records is the main task.
A possible application area of IM Scoring Java Beans might be the realization of an Internet-based call center scenario. In this scenario, the required business logic - in this case the scoring functions - runs on a Web or application server. Clients can connect to the server and send to it a data record that was specified by a call-center operator by means of a user interface on the client. The data record is scored on the server, and the result is passed back to the client in real time.
Figure 9 shows a simplified design, illustrating how such a scenario could be realized using IM Scoring Java Beans. Here, IM Scoring Java Beans is integrated into a J2EE implementation using, for example, servlets or Enterprise Java Beans.
For more information refer to Specifying the mining model to be used.
After the mining model and a data record are specified, the score of the data record can be computed. For this purpose, the RecordScorer class provides the following method:
public void score( Map record ) throws RecordException, ModelException
After you have successfully called the score(Map) method, you can access the computed result fields by using one of the following methods:
| Method | Required model type | Default value |
|---|---|---|
| double getClusterID() | Clustering | java.lang.Double.NaN |
| double getClusterScore() | Clustering | java.lang.Double.NaN |
| double getClusterQuality() | Clustering | java.lang.Double.NaN |
| String getPredictedClass() | Classification | NULL |
| double getConfidence() | Classification | java.lang.Double.NaN |
| double getPredictedValue() | Regression | java.lang.Double.NaN |
Depending on the type of mining model that is used, different sets of fields are computed. After you specify a mining model with one of the openModel(...) methods, you can query the type of mining model by using the method public int getModelType(). This method returns an integer value that represents one of the following constants:
With getModelType(), it is possible to determine which of the methods listed in Table 18 can be used to access the computed result fields. If the model type is, for example, Scorer.CLASSIFICATION_TYPE, the scoring result can be accessed with the methods getPredictedClass() and getConfidence(). The use of the method getPredictedValue() in this context, for example, would throw a ResultException. Each of the result methods throws a ResultException whenever the result field and the actual model type do not fit together.
It might be the case that a mining model is specified, but the model is not loaded yet or the score method is not called yet. In this case, the result methods that fit the specified model type return their default values as listed in Table 18.
0 try {
1 RecordScorer scorer = new RecordScorer( "93er_cars.pmml" );
2 int modelType = scorer.getModelType();
3 double predictedValue = getPredictedValue();
4 try {
5 int predictedClass = scorer.getPredictedClass();
6 } catch ( ResultException e ) {
7 // this is an expected exception for illustration purposes
8 }
9 HashMap record = new HashMap();
10 record.put("Horsepower", new Integer(200));
11 record.put("Air Bags standard", new Integer(2) );
12 record.put("City MPG", new Integer(17) );
13 scorer.score( record );
14 predictedValue = scorer. getPredictedValue();
15
16 } catch ( Exception e ) {
17 // should not occur if everything is correct
18 }
First, a new RecordScorer instance is initialized with a Stepwise Polynomial Regression mining model (line 1). The value of modelType in line 2 thus is equal to the value specified by the constant Scorer.REGRESSION_TYPE. For this type of model, a predicted value is expected for each scored record. When the method getPredictedValue() is called in line 3, the actual predicted value is returned. Since the score(Map) method is not called yet, the default value NaN is returned by the method in line 3. When getPredictedClass() is called in line 5, a ResultException is thrown, because the predicted class for the result field does not fit the model type Scorer.REGRESSION_TYPE. In line 9 to 12, the actual data record is defined. There, the field names are mapped to their actual values. In line 13, score(Map) is called and the scoring result is computed. The result of the call to getPredictedValue() in line 14 is a value not equal to NaN, the default value.
The following exception classes are used by the RecordScorer and its base class Scorer:
In addition, the RecordScorer constructor and the openModel method, which read the model from a database table, can throw a:
java.sql.SQLException
This exception provides information on a database access error or other errors.
The sizes of the input and output parameters of the methods, functions, and procedures are as follows:
IM Scoring provides a number of user-defined data types. These data types are used to store models and results, and to define the data to which a model is applied.
The data types are installed in the schema IDMMX.
| Data type (UDT) | Source data type | Purpose | Methods or functions (UDF) |
|---|---|---|---|
| DM_ApplicationData | CLOB | Distinct type: It contains the definition of data to which a model is applied. |
Functions: |
| DM_ClasModel | BLOB | Distinct type: It identifies data within DB2 as a Tree or Neural Classification model. The data type is associated with the model when the model is imported using the DM_impClasFile function. If the model is stored in a database table, the column must be configured for this data type. |
Functions: |
| DM_ClasResult | VARCHAR | Distinct type: It contains the predicted class and classification confidence values for a row of data obtained when a Classification model is applied by means of the DM_applyClasModel function. |
Functions: |
| DM_ClasResultSpec | VARCHAR | Structured type: It contains the user-defined specification of the scoring result to be obtained when a Classification model is applied to a row of data by means of the DM_applyClasModel function. |
Methods: |
| DM_ClusResult | VARCHAR | Distinct type: It contains computed cluster ID, score, confidence, and quality for a row of data obtained when a Clustering model is applied by means of the DM_applyClusModel function. |
Functions: |
| DM_ClusResultSpec | VARCHAR | Structured type: It contains the user-defined specification of the scoring result to be obtained when a Clustering model is applied to a row of data by means of the DM_applyClusModel function. |
Methods: |
| DM_ClusteringModel | BLOB | Distinct type: It identifies data within DB2 as a Demographic or Center-based Clustering model. The data type is associated with the model when the model is imported by means of the DM_impClusFile function. If the model is stored in a database table, the column must be configured for this data type. |
Functions: |
| DM_LogicalDataSpec | CLOB | Structured type: It identifies the field names and types that are contained in a model and that are needed to apply a model. |
Functions: Methods: |
| DM_RegressionModel | BLOB | Distinct type: It identifies data within DB2 as:
|
Functions: |
| DM_RegResult | VARCHAR | Distinct type: It contains the predicted value for a row of data obtained when a Regression model is applied by means of the DM_applyRegModel function. For RBF models it also contains the region ID. |
Functions: |
| DM_RuleModel | BLOB | Distinct type: It represents an Associations model. |
Functions: |
This chapter contains full descriptions of all the IM Scoring methods. They are presented in alphabetical order of the method names.
The methods provided by IM Scoring enable you to work with the structured types DM_LogicalDataSpec, DM_ClasResultSpec, and DM_ClusResultSpec:
For more information refer to Data types reference.
For instructions on how to use the database objects presented here, see Using IM Scoring.
For instructions on how to read the syntax diagrams, see How to read the syntax diagrams.
This method converts a value of type DM_LogicalDataSpec to a CLOB value, and returns it. Export functions are helpful when you want to store values in an external media, for example, as a backup.
Method syntax
>>-fields..DM_expDataSpec--(--)--------------------------------><
Function syntax
>>-DM_expDataSpec--(--fields--)--------------------------------><
The return value is a CLOB value converted from fields.
This method returns the name of a field at a specified position in a value of type DM_LogicalDataSpec.
Method syntax
>>-fields..DM_getFldName--(--position--)-----------------------><
Function syntax
>>-DM_getFldName--(--fields--,--position--)--------------------><
The return value is a VARCHAR value.
This method returns the mining field type of a specified field that is contained in a value of type DM_LogicalDataSpec.
Method syntax
>>-fields..DM_getFldType--(--fieldName--)----------------------><
Function syntax
>>-DM_getFldType--(--fields--,--fieldName--)-------------------><
The DM_LogicalDataSpec type defines the list of fields needed for a model application run and their mining field types. The mining field type describes which field type the field has in the model. Possible types are DM_Categorical or DM_Numerical, and these types map by default to the DB2 source data types listed here.
| Mining data field type name | Mining field type value | Source data type |
|---|---|---|
| DM_Categorical | 0 | CHAR, VARCHAR, LONG VARCHAR, TIME, DATE, TIMESTAMP |
| DM_Numerical | 1 | SMALLINT, INTEGER, DOUBLE, FLOAT, DECIMAL, BIGINT, REAL, DATE, TIME, TIMESTAMP |
This method returns the number of fields that are contained in a value of type DM_LogicalDataSpec.
Method syntax
>>-fields..DM_getNumFields--(--)-------------------------------><
Function syntax
>>-DM_getNumFields--(--fields--)-------------------------------><
The return value is the number of fields that are contained in fields. The return value is of type INTEGER.
Examples are provided in:
This method converts a CLOB value to a value of type DM_LogicalDataSpec. The CLOB value must be a value that was previously exported using the DM_expDataSpec method.
Method syntax
>>-fields..DM_impDataSpec--(--logDataSpec--)-------------------><
Function syntax
>>-DM_impDataSpec--(--fields--,--logDataSpec--)----------------><
The return value is fields containing the content of logDataSpec. Any existing definitions in fields are overwritten by the content of logDataSpec.
This method determines whether a DM_LogicalDataSpec value is compatible with another DM_LogicalDataSpec value. It compares two logical data specifications, and returns TRUE if they are compatible. It can be used to check whether a certain table with test data provides valid input for a certain model.
Method syntax
>>-existLogDataSpec..DM_isCompatible--(--logDataSpec--)--------><
Function syntax
>>-DM_isCompatible--(--existLogDataSpec--,--logDataSpec--)-----><
Note that calls to DM_isCompatible are not symmetric. A call DM_isCompatible(A,B) can return a result different from that returned by DM_isCompatible(B,A).
This method specifies that a confidence value for all classes of the predicted field has to be calculated and written into the scoring result when you apply a Classification model. This applies to an object of type DM_ClasResultSpec that can be given as the third parameter of the function DM_applyClasModel.
Method syntax
>>-resultSpec..DM_setAllClasses--(--)--------------------------><
Function syntax
>>-DM_setAllClasses--(--resultSpec--)--------------------------><
The return value is a value of data type DM_ClasResultSpec indicating that a confidence for all classes of the predicted field has to be written into the scoring result.
This method specifies that the default results values (cluster ID, score, quality, and confidence of the best cluster) have to be calculated and written into the scoring result when you apply a Clustering model. This applies to an object of type DM_ClusResultSpec that can be given as the 3rd parameter of the function DM_applyClusModel.
Method syntax
>>-resultSpec..DM_setBestCluster--(--)-------------------------><
Function syntax
>>-DM_setBestCluster--(--resultSpec--)-------------------------><
The return value is a value of data type DM_ClusResultSpec indicating that the default results values have to be calculated and written into the scoring result.
This method specifies that the confidence for the specified class has to be calculated and written into the scoring result when you apply a Classification model. This applies to an object of type DM_ClasResultSpec that can be given as 3rd parameter of the function DM_applyClasModel.
Method syntax
>>-resultSpec..DM_setClass(class)------------------------------><
Function syntax
>>-DM_setClass--(--resultSpec--,--class--)---------------------><
This method indicates that a score and quality for a specified cluster (indicated by its clusterid) has to be calculated and written into the scoring result when you apply a Clustering model. This applies to an object of type DM_ClusResultSpec that can be given as the 3rd parameter of the function DM_applyClusModel.
Method syntax
>>-resultSpec..DM_setCluster--(--clusterid--)------------------><
Function syntax
>>-DM_setCluster--(--resultSpec--,--clusterid--)---------------><
This method specifies that the default results values (predicted class and confidence in this prediction) have to be calculated and written into the scoring result when you apply a Classification model. This applies to an object of type DM_ClasResultSpec that can be given as the 3rd parameter of the function DM_applyClasModel.
Method syntax
>>-resultSpec..DM_setPredClass--(--)---------------------------><
Function syntax
>>-DM_setPredClass--(--resultSpec--)---------------------------><
The return value is a value of data type DM_ClasResultSpec indicating that the default results values have to be calculated and written into the scoring result.
This method specifies that the node ID used for calculating the predicted class has to be written into the scoring result when you apply a Tree Classification model. This applies to an object of type DM_ClasResultSpec that can be given as the third parameter of the function DM_applyClasModel.
Method syntax
>>-resultSpec..DM_setTreeNodeID--(--)--------------------------><
Function syntax
>>-DM_setTreeNodeID--(--resultSpec--)--------------------------><
The return value is a value of data type DM_ClasResultSpec indicating that the node ID used for the prediction has to be written into the scoring result.
This chapter contains full descriptions of all the IM Scoring functions and stored procedures. They are presented in alphabetical order of the function names.
IM Scoring provides a number of user-defined scoring functions that enable you to:
The scoring functions are installed in the schema IDMMX.
For more information refer to Data types reference.
For instructions on how to use the database objects presented here, see Using IM Scoring.
For instructions on how to read the syntax diagrams, see How to read the syntax diagrams.
This function obtains the data to which a model is applied by DM_applyClusModel, DM_applyClasModel, or DM_applyRegModel. It builds a value of type DM_ApplicationData, which includes the label and the value obtained from the column specified in the SQL statement.
This function is available in two different notations. One notation has two parameters; the other has three parameters. Use the two-parameter notation for the inner call in nested calls, or if the application data consists only of one field-value pair.
Two-parameter notation >>-DM_applData--(--label--,--+-character expression-+--)------->< +-numeric expression---+ +-date expression------+ +-time expression------+ '-timestamp expression-'
Three-parameter notation >>-DM_applData--(--application data--,--label--,----------------> >--+-character expression-+--)--------------------------------->< +-numeric expression---+ +-date expression------+ +-time expression------+ '-timestamp expression-'
Label can have a maximum length of 128.
If multiple data items are to be included, multiple nested calls to DM_applData must be made.
The return value is a value of data type DM_ApplicationData.
An example is provided in:
>>-DM_applyClasModel--(--+-model--,--application data-+---------> '-model name--,--data record-' >--+----------------+--)--------------------------------------->< '-,--result spec-'
REC2XML(1.0, 'COLATTVAL', '', ...)
The results produced by applying a model using DM_applyClasModel are returned as data type DM_ClasResult.
An error message is displayed, if:
>>-DM_applyClusModel--(--+-model--,--application data-+---------> '-model name--,--data record-' >--+----------------+--)--------------------------------------->< '-,--result spec-'
REC2XML(1.0, 'COLATTVAL', '', ...)
The results produced by applying a model using DM_applyClusModel are returned as data type DM_ClusResult.
An error message is displayed, if:
REC2XML(1.0, 'COLATTVAL', '', ...)
The results produced by applying a model using DM_applyRegModel are returned as data type DM_RegResult.
An error message is displayed, if:
This stored procedure removes all models from the cache.
For more information refer to Using the model cache for real-time scoring.
An error message is displayed, if the database has been enabled in unfenced mode. This is not supported for model caching.
Examples are provided in:
Another example is:
CALL IDMMX.DM_closeAllModels(1);
This user-defined function explicitly removes a model from the cache. The model is identified by the ID returned by DM_openModel. For more information refer to Using the model cache for real-time scoring.
If cachedModelID is NULL, the return value is NULL.
The function returns a value of type INTEGER that specifies if the model was found in the cache and removed:
An error message is displayed, if the database has been enabled in unfenced mode, which is not supported for model caching.
Examples are provided in:
Another example is:
VALUES (IDMMX.DM_closeModel( <model ID> ));
This function returns a character large object representing a PMML Classification model of type DM_ClasModel.
The return value is a character large object representing the PMML Classification model in question. The CLOB XML string is encoded in database encoding (the code set specified when the database was created) regardless of the encoding specification found in the XML content.
This function returns a character large object representing the PMML Clustering model extracted from a value of type DM_ClusteringModel.
The return value is a character large object representing the Clustering model. The CLOB XML string is encoded in database encoding (the code set specified when the database was created) regardless of the encoding specification found in the XML content.
This function returns a character large object representing a PMML or XML Regression model of type DM_RegressionModel.
A character large object (CLOB) represents a Regression model, if it is a valid instance of the PMML-based regression DTD according to XML.
The return value is a character large object (CLOB) representing the Regression model. The CLOB XML string is encoded in the code set, which is specified when the database is created, regardless of the encoding specification found in the XML content.
This function returns a character large object representing an Associations model of type DM_RuleModel.
The result of invoking DM_expRuleModel is a character large object representing the Associations model. The CLOB XML string is encoded in database encoding (the code set specified when the database was created) regardless of the encoding specification found in the XML content.
This function returns the classification cost rate of the Classification model computed in a validation phase during the training phase. It uses the validation data specified in the DM_ClasBldTask value (an IM Modeling structured type that defines a modeling task).
For more information refer to DM_setClasCostRate in Intelligent Miner Modeling Administration and Programming.
The return value is the name of the Classification model as a VARCHAR value.
This function returns the DM_LogicalDataSpec value representing the set of fields needed for an application of the Classification model.
The return value is the DM_LogicalDataSpec value representing the set of fields needed for an application of the Classification model.
The return value is the target field name as a VARCHAR value.
This function returns the confidence of attributing the record r to the best cluster in comparison with attributing it to another cluster of the applied model. The ID of the best cluster is returned by the function DM_getClusterID.
The confidence is a value between 0 and 1 of type DOUBLE. A value near 0 should never appear. A value near 0.5 (50%) means that the record might fit equally well into another cluster of the model. A value near 1 means that it is quite certain that the record belongs to the best cluster. It also means that the record definitely does not suit any other clusters of the model.
The return value is the name of the Clustering model as a VARCHAR value.
This function returns the DM_LogicalDataSpec value representing the set of fields needed for an application of the Clustering model.
The return value is the DM_LogicalDataSpec value representing the set of fields needed for an application of the Clustering model.
Examples are provided in:
The return value is the type of the Clustering model as a VARCHAR value. It can be center-based or distribution-based.
This function obtains the Clustering quality from results data that is produced when you apply a Clustering model. The score is an expression of how closely the data matches the model cluster. For Distribution-based Clustering , a score value close to 1.0 indicates a good match. For Center-based Clustering, a score value close to 0.0 indicates a good match.
For more information refer to DM_getQuality.
This function obtains the Clustering quality for a specified cluster from results data that is produced when you apply a Clustering model. The score is an expression of how closely the data matches the model cluster. For Distribution-based Clustering, a score value close to 1.0 indicates a good match. For Center-based Clustering, a score value close to 0.0 indicates a good match.
The result may not contain a score for all the available clusters. To optimize the memory needed to store the clustering result, IM Scoring usually computes the Clustering quality for only the two best matching clusters. You can explicitly specify clusters for which a score and a quality value have to be calculated. Specify the function DM_setCluster(clusterid) on an object of data type DM_ClusResultSpec given as the 3rd parameter to the application function DM_applyClusModel.
This function obtains the cluster ID from results data that is produced when you apply a Clustering model. The cluster ID identifies the position of the cluster in the Clustering model that is the best match for this data. For information about the difference between the cluster IDs that are returned by IM Scoring V7.1 and IM Scoring V8.2, see Using the function DM_getClusterID.
Examples are provided in:
This function returns the name of a cluster at a specified position in a value of type DM_ClusteringModel.
This function returns a table that contains the clusters of a Clustering model. For each cluster, the size and homogeneity is given.
You can use this function for example to determine the smallest clusters for deviation detection. The cluster IDs can be used in result specification methods.
The result of invoking DM_getClusters is a table. Table 21 describes the data type and purpose of each column contained in this table.
| Column | Data type | Purpose |
|---|---|---|
| ID | INTEGER | Are the index values of the cluster in the model |
| NAME | VARCHAR(128) | Contains the names of the clusters |
| SIZE | BIGINT | Contains the number of records in the clusters |
| HOMOGENEITY | REAL | Contains a measure for the homogeneity of the records in the cluster. The value is between 0 (heterogeneous) and 1 (homogeneous, all records are identical) |
| DESCRIPTION | VARCHAR(1024) | Contains for each cluster a text description of the most important fields for characterizing the cluster. |
The DESCRIPTION of a cluster is built up as follows:
The text of an individual field depends on the field type:
"<field alias> is much more/less often <value> than average"
"<field alias> is more/less often <value> than average"
"<field alias> is much larger/smaller than average"
"<field alias> is larger/smaller than average"
"<field alias> has a larger/smaller variance than input data"
Table 22 shows an example for the table returned by DM_getClusters:
| ID | NAME | SIZE | HOMOGENEITY | DESCRIPTION |
|---|---|---|---|---|
| 1 | lost customer | 765 | 0.8 | AGE is smaller than average, GENDER is more often FEMALE than average, INCOME is much larger than average |
| 2 | loyal customer | 8156 | 0.4 | This cluster is overall similar to input data |
| 3| | undecided customer | 172 | 0.7 | INCOME larger than average, GENDER is more often FEMALE than average, AGE is larger than average |
| 4 | potential customer | 455 | 0.4 | GENDER is much more often MALE than average, NUM_OF_INSURANCES is smaller than average, SICK_LEAVE is much smaller than average, CAR_INSURANCE is much less often YES, NUM_OF_CHILDREN is larger than average |
This function obtains the classification confidence value from results data that was produced when you applied a Classification model. This is a value between 0.0 and 1.0 that expresses the probability that the class is predicted correctly.
This function obtains the classification confidence value for a specified class from results data that was produced when you applied a Classification model. This is a value between 0.0 and 1.0 that expresses the probability that the class is predicted correctly.
The result may not contain a score for all the available classes. To optimize the memory needed to store the classification result, IM Scoring usually computes the Classification score for only the best matching class. You can explicitly specify classes for which a confidence value has to be calculated. Specify the function DM_getConfidence(class) or DM_setAllClasses on an object of data type DM_ClasResultSpec or DM_ClasResult given as the 3rd parameter to the application function DM_applyClasModel.
This function returns the confidence that a given regression result, which has been produced by applying a Transform Regression model lies in the interval between two given boundary values low and up. The returned confidence value is calculated based on accuracy estimations which are part of the Transform Regression model. These estimations have been established when the model was trained.
This procedure lists all the environment variables in the running agent process that have the IDM_ prefix.
The return value is a string that concatenates all variable=value entries of the environment, separated by an end-of-line character. Only those variables that have the prefix IDM_ are selected.
To display the environment variables from the command line, enter this call:
CALL IDMMX.DM_getEnv(?)
If you did not set any of the environment variables recognized by IM Scoring or IM Modeling (IDM_MX_ERRORFILE, IDM_MX_TRACEFILE, IDM_MX_TRACELEVEL, IDM_MX_MAX_OPEN_MODELS) before, the resulting list of variables will be empty.
If rowcount is NULL, all error messages are returned.
The result of invoking DM_getErrors is a table. Table 23 describes the data type and purpose of each column contained in this table.
| Column | Data type | Purpose |
|---|---|---|
| ROWCOUNT | INTEGER | Contains the row number (can be used to order) |
| ERRMSG | VARCHAR(1024) | Contains the complete error message |
| ERRDATE | VARCHAR(12) | Contains the date formatted as in error file (system locale) |
| ERRTIME | VARCHAR(12) | Contains the time formatted as in error file (system locale) |
| ERRTYPE | CHAR(1) |
|
| THREADID | INTEGER | Contains the thread ID of thread writing the error |
| EVENT | INTEGER | Contains the IM Scoring or IM Modeling reason code or event ID as documented in message reference |
An example is:
SELECT * FROM TABLE (IDMMX.DM_GETERRORS(5)) AS ERRORS
This function returns a table that contains the signature of a model. The signature of a model is the set of all input data fields which appear in the model's internal equations and whose values are therefore needed to apply the model. For each signature field, its importance for the model may also be contained in the table. It replaces and completes the following methods or functions:
>>-DM_getFields--(--+-classificationModel-+--)----------------->< +-clusteringModel-----+ +-regressionModel-----+ '-ruleModel-----------'
The result of invoking DM_getFields is a table. Table 24 describes the data type and purpose of each column contained in this table.
| Column | Data type | Purpose |
|---|---|---|
| COLNAME | VARCHAR(128) | Contains the original column names in the database table holding the training data. |
| FIELDNAME | VARCHAR(128) | Contains alias names as defined in the PMML attributes displayName. If no alias is defined, it contains the same value as the column COLNAME. |
| MININGTYPE | SMALLINT | Is 0 for categorical and 1 for numerical fields. |
| IMPORTANCE | REAL | If field importance information is contained in the input model, the IMPORTANCE column holds values between 0 and 1 describing the contribution of this input field to the model. A value of 1 means that this field contains all the model information by itself, a value of 0 indicates that the field has no influence on the model. Otherwise, all values are NULL. |
The resulting virtual table has the following layout. In Table 25 the first row shows the column name, the second row shows the column type, and the following rows show examples.
| COLNAME | FIELDNAME | MININGTYPE | IMPORTANCE |
| VARCHAR(128) | VARCHAR(128) | SMALLINT | REAL |
| REVENUE | REVENUE | 1 | 0.753 |
| ZIPCODE | zip | 0 | 0.018 |
| EDUCATION | EDUCATION | 0 | 0.331 |
| CUSTOMER_AGE | age | 1 | 0.240 |
This function returns the number of clusters contained in a value of type DM_ClusteringModel.
This function returns the number of transactions contained in the dataset used to build the model of type DM_RuleModel. The number of transactions can be used to determine absolute support of individual rules in conjunction with DM_getRules.
The result of invoking DM_getNumTransacts is an INTEGER specifying the number of transactions contained in the dataset used to build ruleModel.
Examples are provided in:
This table function returns the contents of the model cache as a table. For every model in the cache, one row is returned. This is the only function that provides information about the cache. It can be used in a SELECT statement to filter the desired data about the cache, such as the size of the cache. For more information refer to Using the model cache for real-time scoring.
The returned table has the following columns:
| Column | Data type | Purpose |
|---|---|---|
| MODELID | BIGINT | Contains the ID of the model in the cache. |
| MODELNAME | VARCHAR(240) | Contains the name of a model as it is found in the PMML representation. |
| MODELALIAS | VARCHAR(256) | Contains the alias for a model if specified in DM_openModel. Otherwise, it returns an empty string. |
| USER | VARCHAR(128) | Application Authorization ID. |
| TIMESTMP | TIMESTAMP | Last access time of the model. |
| PINNED | INTEGER |
|
| SIZE | INTEGER | Size of the model in bytes. The value is the size of the PMML representation of the model. |
| USECOUNT | INTEGER | Number of scoring runs that currently use the model. |
An error message is displayed, if the database has been enabled in unfenced mode, which is not supported for model caching.
Examples are provided in:
Another example is:
SELECT CT.* FROM TABLE(IDMMX.DM_getOpenModels()) CT
This function obtains the predicted class from results data that is produced when you apply a Classification model. This identifies the class within the model to which the data matches.
This function returns the half width of the range in which a given result value that has been produced by applying a Regression model, lies with the probability prob. The returned width value is calculated based on accuracy estimations which are part of the Regression model. These estimations have been established when the model was trained.
This function returns the estimated standard deviation of a given predicted value, which has been produced by applying a Regression model. The returned value is calculated based on accuracy estimations which are part of the Regression model. These estimations have been established when the model was trained.
This function obtains the predicted value from results data that is produced when you apply a Regression model. This value is calculated according to relations that are established by the model.
This function returns the quality of attributing the record to the best cluster whose ID is given by the function DM_getClusterID. It measures how well the applied record fits into the best cluster.
The returned value is between 0.0 and 1.0. A value close to 0.0 means that the record does not fit at all in the best cluster. A value close to 1.0 means that the record fits very well in the best cluster. The quality measurement depends on the algorithm used to score the record, so that a direct comparison between the quality of algorithm results is not possible. However, both center-based and distribution-based algorithms use a linear, possibly similar, quality measurement function.
This function returns the quality of attributing the record to a specified cluster. It measures how well the applied record fits into the specified cluster.
The result may not contain a quality measure for all the available clusters. To optimize the memory needed to store the clustering result, IM Scoring usually computes the quality measure for only the two best matching clusters. You can explicitly specify clusters for which a score and a quality value have to be calculated. Specify the function DM_setCluster(clusterid) on an object of data type DM_ClusResultSpec given as the 3rd parameter to the application function DM_applyClusModel.
The returned value is between 0.0 and 1.0. A value close to 0.0 means that the record does not fit at all in the cluster. A value close to 1.0 means that the record fits very well in the specified cluster. The quality measurement depends on the algorithm used to score the record, so that a direct comparison between the quality of algorithm results is not possible. However, both center-based and distribution-based algorithms use a linear, possibly similar, quality measurement function.
Examples are provided in:
This function returns the number of the region to which the record was assigned. The value is returned from results data that is produced when you apply an RBF Regression model.
The return value is the name of the Regression model as a VARCHAR value.
This function returns the DM_LogicalDataSpec value representing the set of fields needed for an application of the Regression model. The field names contained in the DM_LogicalDataSpec value are the field names of the DM_LogicalDataSpec value used for building the Regression model. To test the model, you must also call the function DM_getRegTarget to complete the set of fields needed for a test run.
The return value is the DM_LogicalDataSpec value representing the set of fields needed for an application of the Regression model.
This function returns the name of the target field used when training the Regression model. The name is the appropriate column alias name of the DM_MiningData value used for building the model.
If the model was produced by means of IM Modeling, the target field name is the name that was set by means of the method DM_setRegTarget in the DM_RegSettings value.
The target field name is returned as a value of type VARCHAR.
This function returns the squared Pearson correlation coefficient of the Regression model computed during the training phase using the validation data specified in the DM_RegBldTask value used to generate the model.
This coefficient measures the correlation between the prediction error on verification data and the actual target values.
This function returns a table containing the bodies of rules in a value of type DM_RuleModel.
The result of invoking DM_getRuleBodies is a table. Table 26 describes the data type and purpose of each column contained in this table.
| Column | Data type | Purpose |
|---|---|---|
| BODYID | INTEGER | Contains the ID of the body. Each value in BODYID appears in n rows, where n is the size of the item set. There is a distinct entry in BODYID for each item set appearing in a rule of ruleModel.
Note:
The table contains each BODYID that
appears in a rule. However, not every BODYIDthat is
contained in the table also appears in a rule. |
| ITEMNAME | VARCHAR(1024) | The item name after name mapping (if any) |
| ITEM | VARCHAR(1024) | The original item name before name mapping |
An item set could be, for example:
[shoes][coat][hat]
The resulting virtual table has the following layout. In Table 27 the first row shows the body ID, the item name, and the item, and the following rows show examples.
| BODYID | ITEMNAME | ITEM |
| 17 | 2576901 | shoes |
| 17 | 1288737 | coat |
| 17 | 1298130 | hat |
This example is related to the example shown in DM_getRules.
The return value is the name of the Associations model as a VARCHAR value.
This function returns a table containing the rules in a value of type DM_RuleModel.
The result of invoking DM_getRules is a table. Table 28 describes the data type and purpose of each column contained in this table.
| Column | Data type | Purpose |
|---|---|---|
| ID | INTEGER | Is a number generated to identify the rules. |
| HEADNAME | VARCHAR(1024) | Contains the head item of the rule after name mapping (if any). |
| HEAD | VARCHAR(1024) | Uses the original item before name mappings. |
| BODYID | INTEGER | Is a generated identifier to allow joining the resulting
table with a table generated by DM_getRuleBodies.
Note:
Values of BODYID may appear in several rows, if there
are rules with identical sets of items in their bodies. |
| BODYTEXT | VARCHAR(4096) | Is a concatenation of the names of all body items separated by the term 'AND'. The body items and their names can be determined using the table DM_getRuleBodies. |
| LENGTH | SMALLINT | Is a count of all items in the head and body. |
| SUPPORT | REAL | Is the rule support and contains percentage values between
0.0 and 100.0.
The support of an association rule is the percentage of groups that contain all of the items listed in that association rule. |
| CONFIDENCE | REAL | Is the rule confidence and contains percentage values
between 0.0 and 100.0.
The confidence of an association rule is a percentage value that shows how frequently the rule head occurs among all the groups containing the rule body. |
| LIFT | REAL | Indicates how much more confidence the rule has as might
be expected if the items were statistically independent; the value is given
as a positive factor.
The lift of a rule is the ratio of confidence to the expected confidence. It indicates how much more confidence the rule has as might be expected if the items were statistically independent. |
If, for example, model contains the rules:
[shoes][coat][hat] ==> [scarf]
and
[shoes][coat][hat] ==> [scarf][blouse]
There will be three rows in the result table as shown in Table 29.
| ID | HEADNAME | HEAD | BODYID | BODYTEXT | LENGTH | SUPPORT | CONFIDENCE | LIFT |
| 1 | scarf | 1271180 | 17 | shoes AND coat AND hat | 4 | 5.8 | 82.0 | 0.7 |
| 2 | scarf | 1271180 | 17 | shoes AND coat AND hat | 5 | NULL | NULL | NULL |
| 2 | blouse | 2222333 | 17 | shoes AND coat AND hat | 5 | NULL | NULL | NULL |
This example is related to the example shown in DM_getRuleBodies.
This function obtains the node ID used for the prediction from results data that is produced when you apply a Tree Classification model. This identifies the path from the root to a node of the Tree Classification model to which the data matches.
The result may not contain a score for all the available nodes. To optimize the memory needed to store the Tree Classification result, IM Scoring usually computes the Tree Classification score for only the two best matching nodes. You can explicitly specify nodes for which a score and a quality value have to be calculated. Specify the function DM_getTreeNodeID on an object of data type DM_ClasResult given as the 3rd parameter to the application function DM_applyClasModel.
This function returns a table that contains one record for each node of a Tree Classification model. Each record contains the node ID, as presented by the visualizer, and a textual description of the rule that defines the node. In addition to this, the predicted class, the confidence, and the depth of the node are provided.
| Column | Data type | Purpose |
|---|---|---|
| NODEID | VARCHAR(IDM_SQL_NODE_ID)
or VARCHAR(128) |
The values are unique strings identifying an individual node in the tree. The format is identical to the one used by IM Visualization. For example, "1.1.2.1" indicates the node at depth 4 that is reached from the root node by selecting the first successor, then the second, and then the first again. The root node itself has NODEID "1". |
| ISLEAF | SMALLINT | Contains 1 if the node is a leaf node, otherwise it contains 0. The prune level of the model determines which nodes are leaf nodes. The resulting table does not contain any nodes lower than the current prune level. |
| CLASS | VARCHAR(IDM_SQL_CLASS_LABEL=256) | Is the predicted class label (when scoring) for records
that belong to this node.
Note:
The predicted class label need not
be the majority class label in the node if a cost matrix was used. |
| CONFIDENCE | REAL | Is a value between 0 and 1, indicating the probability (based on training data) that the value in CLASS will be a correct prediction for records belonging to the node. CONFIDENCE is sometimes also called purity of a node. |
| SIZE | BIGINT | Is the number of training records that belong to the node. |
| DEPTH | SMALLINT | Holds the depth at which the node occurs in the tree as a SMALLINT, the root node has a depth of 1. |
| CONDITION | VARCHAR(4096) | Is a human-readable string that describes the condition defining the node. There may not be a single decision for each level in the order of the tree branch, as the node text is optimized to eliminate redundancies. CONDITION is truncated if the string is longer than 4096. In this case, the string ends with "..." to indicate that it is truncated. |
The layout of the virtual table is as follows. In Table 31 the first row shows the column name, the second row shows the column type, and the following rows show examples.
| NODEID | ISLEAF | CLASS | CONFIDENCE | SIZE | DEPTH | CONDITION |
| VARCHAR(128) | SMALLINT | VARCHAR(256) | REAL | BIGINT | SMALLINT | VARCHAR(32K) |
| 1 | 0 | NO | 0.51 | 512,606 | 1 | TRUE |
| 1.1 | 0 | NO | 0.62 | 248,384 | 2 | age<=34 |
| 1.1.2 | 0 | YES | 0.55 | 123,811 | 3 | age<=34 AND color IS IN (red, green) |
| 1.1.2.1 | 0 | YES | 0.67 | 75,589 | 4 | 23<=age < 34 AND color IS IN (red, green) |
| 1.1.2.1.2 | 0 | YES | 0.70 | 32,066 | 5 | 23<=age<34 AND color IS IN (red, green) AND income>23200 |
| 1.1.2.1.2.1 | 1 | NO | 0.73 | 15,754 | 6 | 23<=age<34 AND color=blue AND income>23200 |
| 1.1.2.1.2.2 | 1 | YES | 0.92 | 16,312 | 6 | 23<=age<34 AND color IS IN (red, green, blue) AND income>23200 |
The data record must be a well-formed XML element. The element must match the DTD declaration of type row below:
<!ELEMENT row (column*) >
<!ELEMENT column (PCDATA) >
<!ATTLIST column
name CDATA #REQUIRED
null (true | false ) "false"
>A value of the attribute name is interpreted as the name of the scoring field. The content of an element is interpreted as the value of the named scoring field. The order of the column elements is not relevant. The data for some fields might be NULL. In this case, it is represented by an element where the attribute null has the value true and the content is empty.
This format is used by the DB2 function REC2XML called with the parameter COLATTVAL.
Examples are provided in:
This function reads a Classification model from a file, and returns it as data of type DM_ClasModel. This data can then be inserted into a table where one of the columns is designated for this data type.
The return value is the imported model as data type DM_ClasModel.
The encoding of characters in the imported file is determined by default. For information about the default encoding rules, see DM_impClasFileE. The call
DM_impClasFile(filename)corresponds to
DM_impClasFileE(filename,cast (NULL as CHAR))
When the content of the file is read and imported into DB2, the file is no longer needed. However, you might want to keep the file in case you need to import the model again.
This function reads a Classification model from a file, and returns it as data of type DM_ClasModel. This data can then be inserted into a table where one of the columns is designated for this data type.
The encoding of characters in the imported file is specified by a parameter.
IM Scoring supports different encoding names. The MIME encoding strings are recommended, for example, iso-8859-1.
When the content of the file is read and imported into DB2, the file is no longer needed. However, you might want to keep the file in case you need to import the model again.
The return value is the imported model as data type DM_ClasModel.
This function converts the Classification model given as CLOB into a Classification model of type DM_ClasModel.
The return value is a Classification model of type DM_ClasModel. If model_as_CLOB is NULL, the return value is NULL.
This function reads a Demographic or Center-based Clustering model from a file, and returns it as data of type DM_ClusteringModel. This data can then be inserted into a table where one of the columns is designated for this data type.
The return value is the imported model as data type DM_ClusteringModel.
If the input model is a Distribution-based Clustering Model that does not contain distance units, they are calculated by default for numeric fields. The default value is half the square root of the variance of the field.
The encoding of characters in the imported file is determined by default. For information about the default encoding rules, see DM_impClusFileE. The call
DM_impClusFile(filename)corresponds to
DM_impClusFileE(filename,cast (NULL as CHAR))
When the content of the file is read and imported into DB2, the file is no longer needed. However, you might want to keep the file in case you need to import the model again.
Examples are provided in:
This function reads a Demographic or Center-based Clustering model from a file, and returns it as data of type DM_ClusteringModel. This data can then be inserted into a table where one of the columns is designated for this data type.
The encoding of characters in the imported file is specified by a parameter.
IM Scoring supports different encoding names. The MIME encoding strings are recommended, for example, iso-8859-1.
The return value is the imported model as data type DM_ClusteringModel.
If the input model is a Distribution-based Clustering model that does not contain distance units, they are calculated by default for numeric fields. The default value is half the square root of the variance of the field.
When the content of the file is read and imported into DB2, the file is no longer needed. However, you might want to keep the file in case you need to import the model again.
Examples are provided in:
This function converts a Clustering model given as a CLOB value into a Clustering model of type DM_ClusteringModel.
The return value is a Clustering model of type DM_ClusteringModel. If model_as_CLOB is NULL, the return value is NULL.
This function reads an RBF model, a Neural Regression model, a Polynomial Regression model, or a Transform Regression model from a file, and returns it as data of type DM_RegressionModel. This data can then be inserted into a table where one of the columns is designated for this data type.
The return value is the imported model as data type DM_RegressionModel.
The encoding of characters in the imported file is determined by default. For information about the default encoding rules, see DM_impRegFileE . The call
DM_impRegFile(filename)corresponds to
DM_impRegFileE(filename,cast (NULL as CHAR))
When the content of the file is read and imported into DB2, the file is no longer needed. However, you might want to keep the file in case you need to import the model again.
This function reads an RBF model, a Neural Regression model, a Polynomial Regression model, or a Transform Regression model from a file, and returns it as data of type DM_RegressionModel. This data can then be inserted into a table where one of the columns is designated for this data type.
The encoding of characters in the imported file is specified by a parameter.
IM Scoring supports different encoding names. The MIME encoding strings are recommended, for example, iso-8859-1.
The return value is the imported model as data type DM_RegressionModel.
When the content of the file is read and imported into DB2, the file is no longer needed. However, you might want to keep the file in case you need to import the model again.
This function converts a Regression model given as CLOB into a Regression model of type DM_RegressionModel.
The return value is a Regression model of type DM_RegressionModel. If model_as_CLOB is NULL, the return value is NULL.
This function reads an association rules model (PMML format) from a file and returns it as data of type DM_RuleModel. This data can then be inserted into a table where one of the columns is designated for this data type.
The return value is the imported model as data type DM_RuleModel.
The encoding of characters in the imported file is determined by default. For information about the default encoding rules, see DM_impRuleFileE . The call
DM_impRuleFile(<file name>)corresponds to
DM_impRuleFileE(<file name>,cast (NULL as CHAR))
When the content of the file is read and imported into DB2, the file is no longer needed. However, you might want to keep the file in case you need to import the model again.
This function reads an association rules model (PMML) from a file and returns it as data of type DM_RuleModel. This data can then be inserted into a table where one of the columns is designated for this data type.
The encoding of characters in the imported file is determined by a parameter.
When the content of the file is read and imported into DB2, the file is no longer needed. However, you might want to keep this file in case you need to import the model again.
IM Scoring supports different encoding names. The MIME encoding strings are recommended, for example, iso-8859-1.
The return value is the imported model as data type DM_RuleModel.
Examples are provided in:
This function converts an association rules model given as CLOB into an association model of type DM_RuleModel.
The return value is an association rules model of type DM_RuleModel. If model_as_CLOB is NULL, the return value is NULL.
This user-defined function enables you to insert a model into the cache without providing an input data record for the scoring run. It adds a new model to the cache and optionally associates a unique user-specified name with the model.
The model is pinned into the cache, which means that it cannot be implicitly removed from the cache if another model requires a cache entry and the cache is not below its maximum size.
For more information refer to Using the model cache for real-time scoring.
You can also use the model alias to decide whether to perform automatic or manual load balancing. This is done as follows. You can open a model several times using the same model alias on each invocation of DM_openModel within one database instance. Each time you call this function a copy of the model is stored in the cache. If you use:
<schema name>.<alias>where schema name is the value returned by the SQL special register CURRENT SCHEMA.
The function:
An error message is displayed, if:
Examples are provided in:
Another example is:
SELECT IDMMX.DM_openModel(MODEL, MODELNAME) FROM IDMMX.CLUSTERMODELS WHERE MODELNAME = 'DemoBanking';
The procedure checks that the variable name has the prefix IDM_. This ensures that you change only variables specific to IM Modeling or IM Scoring.
If value is NULL, the variable with the name variable is removed from the environment of the process.
The following call sets the name and directory of the error file:
CALL IDMMX.DM_setEnv('IDM_MX_ERRORFILE', '/tmp/myerrors.log')The error file is set to its default value:
CALL IDMMX.DM_setEnv('IDM_MX_ERRORFILE', NULL)
An example for IM Scoring:
Cached models can be of type pinned or unpinned. The variable IDM_MX_MAX_OPEN_MODELS controls the number of unpinned models in the cache only. Models implicitly loaded into the cache using an apply UDF are always unpinned. They can be removed from the cache at any time if a new model needs cache space. Pinned models must be explicitly inserted into and removed from the cache. For more information refer to the function DM_openModel.
The following call allows the cache to store three models:
CALL IDMMX.DM_setEnv( 'IDM_MX_MAX_OPEN_MODELS', '3');
The cache does not store any models if the following call is specified:
CALL IDMMX.DM_setEnv( 'IDM_MX_MAX_OPEN_MODELS', '0');
This chapter contains full descriptions of the commands provided with IM Scoring. Use these commands to:
See The idmxmod command.
See The idmmkSQL command.
See The idmlicm command.
See The idmlevel command.
You can find these commands in the bin directory of your IM Scoring installation.
The idmcheckdb command checks the parameters of a database. It identifies DB CFG parameters if they are not valid and tells you how to solve the problem. It also checks whether a specified database is enabled:
>>-idmcheckdb--dbname--+-------------+--+-------------------------------+->< '-show detail-' '-user--userID--using--password-'
The idmcheckdb utility returns the following messages:
| The database "mydb" is enabled for IM Modeling Version 8.2 and IM Scoring Version 8.2 in "fenced" mode. |
| The database "mydb" is enabled for IM Scoring Version 8.2 in "fenced" mode. |
| The database "mydb" is enabled for IM Modeling Version 8.2 in "fenced" mode. |
| The database "mydb" is not enabled for IM Modeling Version 8.2 or IM Scoring Version 8.2. |
If the database was enabled with the current version of the product, idmcheckdb reports:
The database "sample" is enabled for IM Modeling Version 8.2 and IM Scoring Version 8.2 in "fenced" mode.
If the database was enabled with the current version of the product using the Tablespace option, idmcheckdb sample reports:
The database "sample" is enabled for IM Modeling Version 8.2 and IM Scoring Version 8.2 in "fenced" mode. The following tables contain one or more columns with mining objects: IDMMX.CLASSETTINGS (TABLESPACE USERSPACE2), IDMMX.CLASSIFMODELS (TABLESPACE USERSPACE2), IDMMX.CLASTASKS (TABLESPACE USERSPACE2), IDMMX.CLASTESTRESULTS (TABLESPACE USERSPACE2), IDMMX.CLASTESTTASKS (TABLESPACE USERSPACE2), IDMMX.CLUSSETTINGS (TABLESPACE USERSPACE2), IDMMX.CLUSTASKS (TABLESPACE USERSPACE2), IDMMX.CLUSTERMODELS (TABLESPACE USERSPACE2), IDMMX.LOGICALDATASPECS (TABLESPACE USERSPACE2), IDMMX.MININGDATA (TABLESPACE USERSPACE2), IDMMX.REGRESSIONMODELS (TABLESPACE USERSPACE2), IDMMX.REGSETTINGS (TABLESPACE USERSPACE2), IDMMX.REGTASKS (TABLESPACE USERSPACE2), IDMMX.REGTESTRESULTS (TABLESPACE USERSPACE2), IDMMX.REGTESTTASKS (TABLESPACE USERSPACE2), IDMMX.RULEMODELS (TABLESPACE USERSPACE2), IDMMX.RULESETTINGS (TABLESPACE USERSPACE2), IDMMX.RULETASKS (TABLESPACE USERSPACE2)
If the database was enabled with a previous but compatible version of the product, idmcheckdb reports:
The database "sample" is enabled for IM Scoring Version 8.1.0.1 in "fenced" mode. The database can be used with the current version 8.2. IBM recommends to migrate the database. Use command idmenabledb to migrate your database.
If the database was enabled with a previous but incompatible version of the product, idmcheckdb reports:
The database "sample" is enabled for IM Modeling Version 8.1 and IM Scoring Version 8.1 in "fenced" mode. To use this database with the current version 8.2 you must migrate the database. Use command idmenabledb to migrate your database.
Another example using user ID and password: To check a cataloged database on a remote system, you can specify a user ID and a password, such as:
idmcheckdb sample user peter using mypassword
If a user has not installed IM Scoring or IM Modeling on the client, enter the following to get information about the status of the database enablement:
db2 "select * from IDMMX.VERSION"
The database is not enabled, if the following information is returned:
SQL0204N "IDMMX.VERSION" is an undefined name. SQLSTATE=42704
Otherwise, the following information is returned:
V_KEY V_VALUE V_TIMESTAMP -------------------- ------------------------------ -------------------------- IM Scoring 8.2 2004-05-08-10.10.33.576001 IM Modeling 8.2 2004-05-08-10.10.43.430001
To find out if a database is enabled in fenced or unfenced mode, you can use the following query:
db2 "select routinename,fenced from syscat.routines where
routineschema = 'IDMMX' and origin='E'"
More examples are provided in:
The idmdisabledb command disables a database. It deletes the following mining objects from a specified database:
Examples are provided in:
The idmenabledb command enable a database. It creates new database objects in the database and changes existing database objects if required.
This command is shared between IM Modeling and IM Scoring. It detects which:
>>-idmenabledb--dbname--+----------+--+---------+---------------> +-fenced---+ +-dbcfg---+ '-unfenced-' '-nodbcfg-' >--+------------------+--+------------------+-------------------> '-ClasModelSize--n-' '-RuleModelSize--n-' >--+------------------+--+-----------------+--------------------> '-ClusModelSize--n-' '-RegModelSize--n-' >--+---------------+--+-----------------+--+---------------+----> '-StructSize--n-' '-ApplDataSize--n-' '-ResultSize--n-' >--+-----------------------------+----------------------------->< '-Tablespace--tablespace-name-'
If dbcfg is specified, the database configuration (DB CFG) is changed as recommended without prompting the user.
If nodbcfg is specified, only a warning message is displayed. The database configuration (DB CFG) is not changed.
If you want to change the parameter sizes after you have created models in your database, follow the instructions in Exporting and importing models by means of DB2 Utilities.
The default is 2 KB, which is suitable for all default results and for most of the results created according to a result specification with 10 additional results data. If you want to use a result specification that contains more or bigger results data, increase the size accordingly. The maximum size is 32 KB.
ClusModelSize 20M ResultSize 2K
"Database successfully enabled. However, some types already exist with a different size than requested. First disable the database and run the command again."
An example is:
idmenabledb testdb fenced ClasModelSize 5 RuleModelSize 7 RegModelSize 9
where:
More examples are provided in:
The idminstfunc command enables the DB2 instance for the use of IM Modeling and IM Scoring. Enabling the DB2 instance means that shared libraries containing the implementation of the UDFs, UDMs, and stored procedures are linked into the sqllib/function directory of the DB2 instance.
The idminstfunc command is a shared command between IM Modeling and IM Scoring, and it must be called only once if both products are installed. If only one of the two products is installed, the command must be called again when the other product is added later on.
The idminstfunc command enables the instance that is specified in the DB2INSTANCE environment variable. This variable is automatically set when the respective db2profile script of the instance is executed. It automatically detects if it is a 32 or 64-bit instance. If you want to upgrade an instance from 32 to 64 bit, you must call idminstfunc again. The bin directory of the IM Scoring installation is added to the search path of the DB2 instance, so that further commands of IM Scoring can be called without specifying the full path.
Refer to DB2 Intelligent Miner Modeling, DB2 Intelligent Miner Scoring, DB2 Intelligent Miner Visualization: Installing the Intelligent Miner products.
Examples are provided in:
The idmuninstfunc command disables the DB2 instance for the use of IM Modeling and IM Scoring. Disabling the DB2 instance means that links to the shared libraries containing the implementation of the UDFs, UDMs, and stored procedures are removed from the sqllib/function directory of the DB2 instance.
This command must be called only on UNIX platforms, and it can be called only by a user with SYSADM authority.
The idmuninstfunc command is a shared command between IM Modeling and IM Scoring, and needs be called only once if both products are installed. It is not possible to disable the instance for the use of only one product if both products are installed.
After the idmuninstfunc command is called, IM Modeling and IM Scoring can no longer be used for that DB2 instance. To enable the DB2 instance again, call the idminstfunc command.
Use the command idmlevel to collect information about the software environment (operating system, DB2 version) and IM product version you are using.
idmlevel c:\imscoring.log
idmlevel
More examples are provided in:
Use the idmlicm command to check your license status. IM Scoring and IM Modeling use nodelocked license keys installed in a license file. The full product contains production license keys, which are installed during installation. The 'Try and Buy' version does not include a production license key. You can use the idmlicm command to generate a 'Try and Buy' license key.
The idmlicm command is located in the bin directory. It has no parameters. When invoked, idmlicm checks the license status.
The license for the product "DB2 Intelligent Miner Scoring"
was found in the file "nodelock_sc".
The license for the product "DB2 Intelligent Miner Modeling"
was found in the file "nodelock_mo".
If no production license is installed, idmlicm can generate a temporary license key the first time it is invoked.
W 2771: You are now using a temporary license. You need to enroll "DB2 Intelligent Miner Scoring" within "89" days in the license file "d:\IMinerX\bin\nodelock_sc".
If you invoke idmlicm when a temporary license is already installed, you get the following sample output:
W 2772: The number of days left is "89". You are still using a temporary license. You need to enroll "DB2 Intelligent Miner Scoring" in the license file "d:\IMinerX\bin\nodelock_sc".
The command idmmkSQL analyzes a PMML model, and generates from it a template SQL script that contains the SQL statements necessary to perform a scoring run using the model. It contains placeholders that you replace with the names of concrete database objects in order to finally get the executable SQL script.
The syntax can be as follows:
If PMML files in the file system are processed, default values are used for tables in which mining models are to be stored. However, you can specify another table to store your models by replacing the following strings:
If you specify the following command, the PMML model is analyzed in thePMMLFile.pmml and a DB2 SQL template is generated and stored in theScriptFile.sql. The SQL template uses the REC2XML method to build the input records and to specify that the results of the scoring run are calculated dynamically. To run this template as an executable SQL script, you must first replace the placeholders by real values.
idmmkSQL -D DB2 -M REC2XML -O VIEW thePMMLFile.pmml theScriptFile.sql
The generated template is shown in the following example. Generated comments have been removed from this sample.
INSERT INTO IDMMX.CLUSTERMODELS (MODELNAME,MODEL) VALUES (
'ClusterModel',
IDMMX.DM_impClusFile('###ABSOLUTE_PATH###thePMMLFile.pmml'));
WITH ScoringView
AS (
SELECT
data.*,
IDMMX.DM_applyClusModel(models.MODEL,
IDMMX.DM_impApplData(
REC2XML(1,'COLATTVAL','',
data."TYPE",
data."AGE",
data."INCOME",
data."SIBLINGS"))) AS Result
FROM IDMMX.CLUSTERMODELS models, ###TABLENAME### data
WHERE models.MODELNAME = 'ClusterModel'
)
SELECT
-- add any columns from input data
IDMMX.DM_getClusterID( Result ) AS ClusterID,
IDMMX.DM_getClusConf( Result ) AS ClusConf,
IDMMX.DM_getQuality( Result ) AS Quality
FROM ScoringView;
The following command generates an SQL template from the mining model demoBanking in the DB2 table IDMMX.CLUSTERMODELS. The SQL template uses the REC2XML method to build the input records and defines that the scoring results are to be stored in a table. The script is written on standard output.
idmmkSQL -dbn SAMPLE -dbt IDMMX.CLUSTERMODELS -dbk MODELNAME -dbd MODEL demoBanking
In the following example the DB2 SQL template myScoringView.db2 is generated using the PMML file MyClusterModel.pmml. The SQL template uses the CONCAT method to build the input records and to define that the result of the scoring run is to be calculated dynamically. The encoding of the generated SQL script is iso8859-1.
idmmkSQL -m CONCAT -o VIEW -d DB2 -e iso8859-1 c:\samples\models\MyClusterModel.pmml c:\samples\scripts\myScoringView.db2
The shortest command to generate SQL templates from a mining model stored in a DB2 database is:
idmmkSQL -dbn SAMPLE -dbt IDMMX.CLUSTERMODELS mymodel
More examples are provided in:
You can convert a model outside IM for Data from Intelligent Miner format to PMML 2.1 format by using the idmxmod command.
If an error occurs during a scoring run, an error message is displayed.
The table function IDMMX.DM_GETERRORS() allows to retrieve a complete list of error messages, for more information refer to DM_getErrors(rowcount).
See DB2 Intelligent Miner Modeling, DB2 Intelligent Miner Scoring: Messages for a list of error messages with explanations of their meanings, and indications about what action you should take. Note that some messages are truncated by DB2. To see the full, untruncated message, check the idmMxError.log file.
Errors are logged by default in the file idmMxError.log together with identifiers and time stamps.
If you intend to use the environment variable TMP or TEMP, it must be set in the environment of the DB2 engine. Scoring services run as part of the DB2 engine. Set the environment variable as a system variable.
When the file gets too large, you must delete it.
You can change the error file name and directory by setting the environment variable IDM_MX_ERRORFILE to the name of an alternative error file. The file name must be given as an absolute path name. If you want to prevent IM Scoring from writing to an error file, set the environment variable IDM_MX_ERRORFILE to NONE. The environment variable must be set in the environment of the DB2 engine. On UNIX platforms, add IDM_MX_ERRORFILE to the DB2 registry variable DB2ENVLIST and restart DB2 to activate the changes. See the DB2 Administration Guide to get information on the DB2ENVLIST registry variable. On Windows platforms, IDM_MX_ERRORFILE must be set as a system variable.
Before you contact IBM for support, check the information in the release.txt file that comes with the product. It can be found in the installation directory.
To find the latest information about IM Scoring access the Intelligent Miner Web site.
When you contact IBM for support, prepare to answer the questions in the problem identification worksheet. Make yourself familiar with the instructions on how to collect trace information given at Getting trace information.
The IBM Software Support Guide contains the following problem identification worksheet.
Answer the questions in the worksheet before contacting IBM support.
PROBLEM IDENTIFICATION WORKSHEET
Complete this form before calling Technical Support
This form helps you identify problems and assists IBM Technical Support in
finding solutions.
System Information
What is the failing product? _______________________________________________
What is the version and release number?_____________________________________
What machine model, operating system, and version are running?______________
Problem Description
What are the expected results?______________________________________________
What statement or command is being used? ___________________________________
What are the exact symptoms and syntax? ____________________________________
____________________________________________________________________________
What is or isn't happening, including exact error number and message text?
____________________________________________________________________________
____________________________________________________________________________
Is anyone else experiencing the problem? ___________________________________
Is this the first time this operation has been attempted? __________________
Is this the first time this problem has occurred?___________________________
Environment
When did this activity work last? __________________________________________
What has changed since the activity last worked? ___________________________
_____ Hardware type/model _____ Application
_____ Operating system/version _____ Level of usage
_____ New product version/release _____ Maintenance applied
If the problem does not occur every time, under what conditions does the
problem not occur?
____________________________________________________________________________
____________________________________________________________________________
Is there any other software running on the system which may be conflicting
with this product?
____________________________________________________________________________
____________________________________________________________________________
Problem Isolation
Identify the specific feature of the software causing the problem.__________
____________________________________________________________________________
Can the problem be reproduced? If so, please provide a reproducible test case
or instructions on how to reproduce the error condition.____________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Use the command idmlevel to collect information about the software environment (operating system, DB2 version) and IM product version you are using.
For more information on using this command on Windows or UNIX operating systems refer to The idmlevel command.
The trace facility in IM Scoring helps IBM to locate an error by writing information about an error situation to a file. This information consists of trace messages.
The trace facility is configured by means of two environment variables. These are as follows:
IDM_MX_TRACELEVEL determines the filtering of trace messages. IDM_MX_TRACELEVEL is effectively an on/off switch for tracing.
Since trace messages are controlled by means of environment variables, concurrent mining runs write to the same trace file.
The trace message that is written to the trace file consists of the following information:
The basic system information is written once per trace.
Use the DM_setEnv method to trace errors:
execute IDMMX.DM_setEnv('IDM_MX_TRACELEVEL','ALL') execute IDMMX.DM_setEnv('IDM_MX_TRACELEVEL','')If you need to contact IBM support, you might also need to provide DB2 diagnostic information like DB2CLI trace or db2diag.log. For more information, see the DB2 Troubleshooting Guide.
If you want to migrate from IM Scoring V7.1 to IM Scoring V8.2, in general you can start working with IM Scoring V8.2 after performing the following steps:
If you want to perform scoring operations with both versions, the recommended way to do this is to use different DB2 instances. The reason for this is that an instance is enabled for a specific version of IM Scoring by means of the command idminstfunc. If you want to use the same DB2 instance for both products, disable and enable the DB2 instance first before you use the second product. For this scenario, it is recommended that you use different databases.
IM Scoring and IM Modeling support DB2 V8.
If you use DB2 Version 7 with previous versions of IM Scoring or IM Modeling, you must first migrate DB2 Version 7 to Version 8 as described in the DB2 documentation. Then proceed with the migration instructions for IM Scoring or IM Modeling.
IM Scoring V8.2 stores models in a compressed format in a database, however, it can also work with the uncompressed format that was used for IM Scoring V7.1. The default size for the following model types is 50 MB when you enable a database in unfenced mode:
However, if you want to save disk space, you can simply compress the models by using the export and import UDFs that are provided. These UDFs are:
DM_expClasModel DM_impClasModel
DM_expClusModel DM_impClusModel
DM_expRegModel DM_impRegModel
DM_expRuleModel DM_impRuleModel
You can also compress the models by using a sample script, which is available in the directory samples/ScoringDB2. You can directly use the sample if your models are stored in the tables that are provided. These tables are as follows:
If you use tables that are different from these, you must adapt the sample to your needs before you execute it.
To execute the sample:
db2 -tf compressV7Models.db2
If you want to re-enable an existing database of IM Scoring V7.1 to run in IM Scoring V8, run-time problems might occur because the size of the existing model types can be 100 MB. To export and import these model types:
In the samples/ScoringDB2 directory of your installation, sample scripts are available that export and import models by means of the appropriate DB2 commands. You can directly use the samples if your models are stored in the tables that are provided; these are IDMMX.CLUSTERMODELS, IDMMX.CLASSIFMODELS, and IDMMX.REGRESSIONMODELS. If you use tables that are different from these, you must adapt the samples to your needs before you execute them. To run the samples:
db2 -tf db2ExportModels.db2 idmdisabledb dbname idmenabledb dbname [fenced|unfenced] db2 -tf db2ImportModels.db2
The situation might occur where you have enabled your database for the unfenced mode and you want to import models that were created by IM for Data. In this case, the models cannot be imported if they are still in Intelligent Miner format. Convert the models to PMML first before you import them. Use one of the following ways to do this:
Center-based Clustering models, Neural Classification models, and Neural Regression models that were imported by IM Scoring V7.1 can no longer be applied by IM Scoring V8.2.
If the models are still available as results in IM for Data, drop them from your tables, and import them again.
If you use the function DM_getClusterID on a DM_ClusResult value that was returned when a Clustering model was applied, the values will differ from those returned by IM Scoring:
To get the mapping between cluster IDs and cluster names, use the DM_getClusters function on the Clustering model.
Before you start the migration you must consider the following:
If you want to migrate from IM Scoring V8.1 to IM Scoring V8.2, in general you can start working with IM Scoring V8.2 after performing the following steps:
A DB2 instance must have access to the libraries containing the IM Modeling or IM Scoring functions to use IM from that instance. Some library names and installation paths have changed with Version 8.2. To migrate the DB2 instances to the new version of IM, use the command idminstfunc. For more information refer to The idminstfunc command.
IM Modeling and IM Scoring work with database objects, such as user-defined types (UDT), user-defined functions (UDF), user-defined methods (UDM), and stored procedures (SP). These objects must be created in each DB2 database to be used with IM. This step is called "enabling the database". New database objects have been added in Version 8.2 and some database objects need to be updated.
To migrate existing database objects:
db2 list db directory
Sample output:
System Database Directory Number of entries in the directory=2 Database 1 entry: Database alias = SAMPLE Database name = SAMPLE Database drive = D:\DB2 Database release level = a.00 Comment = Directory entry type = Indirect Catalog database partition number = 0 Database 2 entry: Database alias = IMDEMO Database name = IMDEMO Database drive = D:\DB2 Database release level = a.00 Comment = Directory entry type = Indirect Catalog database partition number = 0
idmcheckdb dbnameSample output:
E:\>idmcheckdb sample The database "sample" is enabled for IM Modeling Version 8.1 and IM Scoring Version 8.1 in "fenced" mode. To use this database with the current version 8.2 you must migrate the database. Use command idmenabledb to migrate your database. ...
idmenabledb dbnameFor
more information refer to The idmenabledb command.
E:\>idmcheckdb sample The database "sample" is enabled for IM Modeling Version 8.2 and IM Scoring Version 8.2 in "fenced" mode. ...
External libraries implementing UDF, UDM, or SP may remain loaded in DB2's processes until the DB2 instance is restarted. To avoid that DB2 uses older libraries of a previous version, the database instance should be restarted after migration. To restart the instance, use the commands:
db2stop db2start
For more information refer to the DB2 manuals.
PMML is a markup language for data mining. Based on XML, PMML provides a standard that enables data mining models to be shared between the applications of different vendors. It provides a vendor-independent method of defining models. It allows you to exchange models between applications.
You can find more information about PMML on the Web site of the Data Mining Group (DMG).
Here you find information on how IM Scoring conforms to the PMML standard. The following naming conventions of the PMML standard are used:
IM Scoring provides an SQL interface enabling the application of PMML models to data.
For this feature, IM Scoring complies with the PMML consumer conformance clause of the PMML standard for several algorithms. These algorithms are listed below with possible restrictions for their consumer conformance to PMML.
IM Scoring delivers conversion tools that enable models in IM for Data format to be converted to PMML.
IM Scoring conversion tools comply with the PMML producer conformance clause of the PMML standard for center-based clustering, decision trees, neural networks, and regression.
IM Scoring conversion tools also comply with the PMML producer conformance clause of the PMML standard for distribution-based clustering when value weighting was not used to create the model. (For information, see the documentation for IM for Data.) However, if value weighting was used, IM Scoring conversion tools produce non-conforming PMML models with a specific extension for value weighting. This extension can be read only by IM Scoring, which will use value weighting when scoring data on these models. Other PMML consumer tools, however, will ignore the extension, though they will read the model successfully. They will not consider value weighting when scoring data on these models.
IM Scoring conversion tools additionally comply with the PMML producer conformance clause of the PMML standard for association rules. However, taxonomies and name mappings that might have been used to create the models are not written into PMML 2.1.
IM Scoring supports Radial-Basis Function (RBF) prediction and Transform Regression. However, RBF prediction and Transform Regression are not yet part of PMML, and therefore cannot comply with the producer or consumer conformance clause. The RBF prediction models or the Transform Regression models written by IM Scoring conversion tools and used in the IM Scoring application have an XML proprietary format that is very similar to the other PMML formats.
Refer to Table 3 for an overview of all algorithms that are supported.
The following features are supported in addition to PMML 2.1 for interoperability reasons:
Models generated by SAS Enterprise Miner V5.1 (abbreviated to SAS EM in this book) can be used with IM Scoring. The following algorithms are supported: Tree (PROC ARBOR), Regression (PROC DMREG), center-based Clustering (PROC DMVQ), and Neural Networks (PROC NEURAL). You do not need any special options for these models.
For more information refer to the SAS Enterprise Miner V5.1 documentation.
SPSS Clementine V8.5 offers a compatibility mode for generating PMML that can be used with IM Scoring. To activate this option in SPSS Clementine, from the Tools menu select User Options... and set the options as shown in Figure 10.
If you have set the user options as shown in Figure 10, the models exported from SPSS Clementine as PMML can be imported into IM Scoring.
The following algorithms are supported:
To solve this problem rebuild the model, either by scanning the whole dataset in SPSS Clementine or by specifying the correct data type of the respective field manually. This can also happen if the training set only consists of integers, but the floating point decimals are inserted during application.
For more information refer to the SPSS Clementine V8.5 documentation.
The DB2 REC2XML function can be used for easy and fast construction of application data values in XML. This section shows the syntax and gives a few examples of how this function can be used.
For detailed information refer to the description of REC2XML in the DB2 Information Management Software Information Center.
Syntax
>>-REC2XML--(--decimal-constant--,--format-string--,------------> .----------------. V | >--row-tag-string----,--column-name-+--)-----------------------><
The schema is SYSIBM.
The REC2XML function returns a string formatted with XML tags and containing column names and column data.
The decimal-constant value is used to calculate the result length of the function. For every column with a character data type, the length attribute of the column is multiplied by this expansion factor before it is added in to the result length.
To specify no expansion, use a value of 1.0. Specifying a value less than 1.0 reduces the calculated result length. If the actual length of the result string is greater than the calculated result length of the function, then an error is raised (SQLSTATE 22001).
The format-string is case-sensitive, so the following values must be specified in uppercase to be recognized.
COLATTVAL
These formats return a string with columns as attribute values.
>>-<--row-tag-string-->-----------------------------------------> .----------------------------------------------------------------------. V | >----<--column-name--=--"column-name"--+->--column-value--</--column-->-+-+--> '-null="true"--/>----------------' >--</--row-tag-string-- >--------------------------------------><
Column names may be valid XML attribute values. For column names which are not valid XML attribute values, character replacement is performed on the column name before it is included in the result string.
Column values may be valid XML element names. If the format-string COLATTVAL is specified, then for the column names which are not valid XML element values, character replacement is performed on the column value before it is included in the result string.
If a string of one or more blank characters is specified, then no beginning row-tag-string or ending row-tag-string (including the angle bracket delimiters) will appear in the result string.
The same column name cannot be specified more than once (SQLSTATE 42734).
The result of the function is VARCHAR. The maximum length is 32 672 bytes (SQLSTATE 54006).
Consider the following invocation:
REC2XML (dc, fs, rt, c1, c2, ..., cn)
If the value of "fs" is "COLATTVAL", the result is the same as this expression:
'<' CONCAT rt CONCAT '>' CONCAT y1 CONCAT y2 CONCAT ... CONCAT yn CONCAT '</' CONCAT rt CONCAT '>'
where yn is equivalent to:
'<column name="' CONCAT xvcn CONCAT vn
and vn is equivalent to:
'">' CONCAT rn CONCAT '</column>'
if the column is not null, and
'" null="true"/>'
if the column value is null.
xvcn is equivalent to a string representation of the column name of cn, where any characters appearing in Table 34 are replaced with the corresponding representation. This ensures that the resulting string is a valid XML attribute or element value token.
The rn is equivalent to a string representation as indicated in Table 33.
| Data type of cn | rn |
|---|---|
| CHAR, VARCHAR | The value is a string. If the format-string does not end in the characters "_XML", then each character in cn is replaced with the corresponding replacement representation from Table 34, as indicated. The length attribute is: dc * the length attribute of cn. |
| SMALLINT, INTEGER, BIGINT, DECIMAL, NUMERIC, REAL, DOUBLE | The value is LTRIM(RTRIM(CHAR(cn))). The length attribute is the result length of CHAR(cn). The decimal character is always the period ('.') character. |
| DATE | The value is CHAR(cn,ISO). The length attribute is the result length of CHAR(cn,ISO). |
| TIME | The value is CHAR(cn,JIS). The length attribute is the result length of CHAR(cn,JIS) |
| TIMESTAMP | The value is CHAR(cn). The length attribute is the result length of CHAR(cn). |
Character replacement:
Depending on the value specified for the format-string, certain characters in column names and column values will be replaced to ensure that the column names form valid XML attribute values and the column values form valid XML element values.
| Character | Replaced XML value |
|---|---|
| < | < |
| > | > |
| " | " |
| & | & |
| ' | ' |
SELECT REC2XML (1.0, 'COLATTVAL', '', DEPTNO, MGRNO, ADMRDEPT) FROM DEPARTMENT WHERE DEPTNO = 'D01'This example returns the following VARCHAR(117) string:
<row> <column name="DEPTNO">D01</column> <column name="MGRNO" null="true"/> <column name="ADMRDEPT">A00</column> </row>
The length attribute for the REC2XML call with an expansion factor of 1.0 would be 128 (11 for the '<row>' and '</row>' overhead, 21 for the column names, 75 for the '<column name=', '>', '</column>' and double quotes, 7 for the CLASS_CODE data, 6 for the DAY data, and 8 for the STARTING data). Since the '&' and '<' characters will be replaced, an expansion factor of 1.0 will not be sufficient. The length attribute of the function will need to support an increase from 7 to 14 characters for the new format CLASS_CODE data.
However, since it is known that the DAY value will never be more than 1 digit long, an unused extra 5 units of length are added to the total. Therefore, the expansion only needs to handle an increase of 2. Since CLASS_CODE is the only character string column in the argument list, this is the only column data to which the expansion factor applies. To get an increase of 2 for the length, an expansion factor of 9/7 (approximately 1.2857) would be needed. An expansion factor of 1.3 will be used.
SELECT REC2XML (1.3, 'COLATTVAL', 'row', CLASS_CODE, DAY, STARTING) FROM CL_SCHED WHERE CLASS_CODE = '&43<FIE'This example returns the following VARCHAR(167) string:
<row> <column name="CLASS_CODE">&43<FIE</column> <column name="DAY">5</column> <column name="STARTING">06:45:00</column> </row>
SELECT REC2XML (1.0, 'COLATTVAL_XML', 'row', EMPNO, RESUME_XML) FROM (SELECT EMPNO, CAST(RESUME AS VARCHAR(3500)) AS RESUME_XML FROM EMP_RESUME WHERE RESUME_FORMAT = 'XML') AS EMP_RESUME_XMLThis example returns a row for each employee who has a resume in XML format. Each returned row will be a string with the following format:
<row>
<column name="EMPNO">{employee number}</column>
<column name="RESUME_XML">{resume in XML}</column>
</row>Where "{employee number}" is the actual EMPNO
value for the column and "{resume in XML}" is the actual XML
fragment string value that is the resume.Here you find an overview of the data or information that is shared between IM Modeling and IM Scoring.
The schema IDMMX is shared between IM Modeling and IM Scoring.
The following data types are shared between IM Modeling and IM Scoring:
The following functions are shared between IM Modeling and IM Scoring:
The following methods are shared between IM Modeling and IM Scoring:
The following commands are shared between IM Modeling and IM Scoring:
You can use IM Scoring with databases that are defined in any code page.
You might want to create a new database in a multilanguage environment and enable this database for the scoring functions. In this case, it is recommended that you create this database using the Unicode character encoding. In a Unicode-enabled database, DB2 uses the following encoding:
You can create a Unicode-enabled database with the following DB2 command:
DB2 CREATE DATABASE dbname USING CODESET UTF-8 TERRITORY US
If one of the following PMML models are exported by using the IM Scoring export functions, the XML declaration in the PMML model contains an encoding specification:
For some operation systems and locale combinations, for example, Japanese on AIX, the encoding name used is specific to the International components for Unicode.
For example, for Japanese models generated on AIX, the XML declaration might look like this:
<?xml version="1.0" encoding="ibm-942_P120_2000" ?> <PMML version="2.1">
When you exchange these models as a file with other products that can read the PMML format, these products might not support these encoding names.
You can solve the problem by manually editing the PMML model and changing the encoding name to a compatible name supported by your product.
For example:
<?xml version="1.0" encoding="ibm-942" ?> <PMML version="2.1">
IBM may not offer the products, services, or features discussed in this document in other countries. Consult your local IBM representative for information on the products and services currently available in your area. Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM product, program, or service may be used. Any functionally equivalent product, program, or service that does not infringe any IBM intellectual property right may be used instead. However, it is the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service.
IBM may have patents or pending patent applications covering subject matter described in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to:
IBM Director of Licensing IBM Corporation North Castle Drive Armonk, NY 10504-1785 U.S.A.
For license inquiries regarding double-byte (DBCS) information, contact the IBM Intellectual Property Department in your country or send inquiries, in writing, to:
IBM World Trade Asia Corporation Licensing 2-31 Roppongi 3-chome, Minato-ku Tokyo 106, Japan
The following paragraph does not apply to the United Kingdom or any other country where such provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or implied warranties in certain transactions, therefore, this statement may not apply to you.
This information could include technical inaccuracies or typographical errors. Changes are periodically made to the information herein; these changes will be incorporated in new editions of the publication. IBM may make improvements and/or changes in the product(s) and/or the program(s) described in this publication at any time without notice.
Any references in this information to non-IBM Web sites are provided for convenience only and do not in any manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of the materials for this IBM product and use of those Web sites is at your own risk.
IBM may use or distribute any of the information you supply in any way it believes appropriate without incurring any obligation to you.
Licensees of this program who wish to have information about it for the purpose of enabling: (i) the exchange of information between independently created programs and other programs (including this one) and (ii) the mutual use of the information which has been exchanged, should contact:
IBM Deutschland GmbH Department 0790 Pascalstrasse 100 70569 Stuttgart Germany
Such information may be available, subject to appropriate terms and conditions, including in some cases, payment of a fee.
The licensed program described in this information and all licensed material available for it are provided by IBM under terms of the IBM Customer Agreement or any equivalent agreement between us.
Any performance data contained herein was determined in a controlled environment. Therefore, the results obtained in other operating environments may vary significantly. Some measurements may have been made on development-level systems and there is no guarantee that these measurements will be the same on generally available systems. Furthermore, some measurement may have been estimated through extrapolation. Actual results may vary. Users of this document should verify the applicable data for their specific environment.
Information concerning non-IBM products was obtained from the suppliers of those products, their published announcements or other publicly available sources. IBM has not tested those products and cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBM products. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products.
All statements regarding IBM's future direction or intent are subject to change or withdrawal without notice, and represent goals and objectives only.
This information contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental.
COPYRIGHT LICENSE:
This information contains sample application programs in source language, which illustrates programming techniques on various operating platforms. You may copy, modify, and distribute these sample programs in any form without payment to IBM, for the purposes of developing, using, marketing or distributing application programs conforming to the application programming interface for the operating platform for which the sample programs are written. These examples have not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs.
You may copy, modify, and distribute these sample programs in any form without payment to IBM for the purposes of developing, using, marketing, or distributing application programs conforming to IBM's application programming interfaces.
Each copy or any portion of these sample programs or any derivative work, must include a copyright notice as follows:
(C) (your company name) (year). Portions of this code are derived from IBM Corp. Sample Programs. (C) Copyright IBM Corp. _enter the year or years_. All rights reserved.
The following terms are trademarks of the IBM Corporation in the United States, other countries, or both:
UNIX is a registered trademark of The Open Group in the United States and other countries.
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both.
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.
Other company, product, and service names may be trademarks or service marks of others.
This bibliography lists all publications in the Intelligent Miner library other than this book, related IBM publications that are relevant to the contents of this book, and non-IBM publications that might be useful for reference purposes.
Where appropriate, IBM publication numbers are given after the document title. This will assist you in finding the document online at the IBM Publications Center.
If you need to, download DB2 fixpacks.
To download patches, go to the SUN Solaris home page
\doc\ScoringBean\index.html