IBM DB2 Intelligent Miner Scoring

Administration and
Programming for DB2

Version 8.2
SH12-6745-01
Note

Before using this information and the product it supports, be sure to read the information in Appendix H. Notices.

Second Edition, August 2004

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.

Copyright International Business Machines Corporation 2001, 2004. All rights reserved.
US Government Users Restricted Rights -- Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

Contents

Figures
Tables
About this book
Who should use this book
Conventions and terminology used in this book
How this book is structured
How to read the syntax diagrams
How to send your comments
What is new in version 8.2
Improved model interoperability
Functional enhancements
Standards conformance
Shared infrastructure with IM Modeling
Consistency notices
User's guide
Introducing the Intelligent Miner products
IBM DB2 Intelligent Miner Scoring
IBM DB2 Intelligent Miner Modeling
IBM DB2 Intelligent Miner Visualization
IBM DB2 Intelligent Miner for Data
Introducing IM Scoring
Introducing data mining functions
Associations
Classification
Clustering
Regression
PMML: A markup language for data mining
Sources of PMML models
PMML models created by IM Modeling
PMML models created by IM for Data
PMML models created by vendor tools
Deployment scenarios
Introducing the SQL/MM API
Familiarizing yourself with the SQL API
Introducing SQL statements for scoring
Quick start using the sample applications
Creating database objects
Generating SQL scripts from your own mining models
Sample files
Completing the practice exercises
Creating a table and importing data
Importing a mining model
Applying a model and getting results values
Extracting information from a model
Using IM Scoring Java Beans to score records
Using idmmkSQL to work with your own mining models
Deleting the entries from the sample tables
Using IM Scoring
Scoring data types, methods, and functions
User-defined data types
User-defined methods
User-defined functions
Creating database objects
Enabling databases
Disabling databases
Checking databases
Deploying mining models
Using models created by IM Modeling
Exporting models from IM for Data
Converting exported models
Importing mining models
Generating SQL statements from models
Extracting information from a model
Applying mining models
Using the application functions
Specifying data by means of REC2XML
Specifying data by means of DM_applData
Specifying data by means of CONCAT
Results data
Customizing the results data
Getting application results
Handling missing values
Using the model cache for real-time scoring
Performance considerations
Setting the model cache size
Examples for real-time scoring
Using IM Scoring Java Beans
Setting environment variables
Specifying the mining model to be used
Accessing model metadata
Specifying a data record
Using the Java Single Record Scorer
Applying scoring
Accessing computed results
Scoring example
ScoringException classes
Reference
Parameter sizes
Data types reference
Methods reference
DM_expDataSpec
DM_getFldName
DM_getFldType
DM_getNumFields
DM_impDataSpec
DM_isCompatible
DM_setAllClasses
DM_setBestCluster
DM_setClass(class)
DM_setCluster(clusterid)
DM_setPredClass
DM_setTreeNodeID
Functions and stored procedures reference
DM_applData
DM_applyClasModel
DM_applyClusModel
DM_applyRegModel
DM_closeAllModels
DM_closeModel
DM_expClasModel
DM_expClusModel
DM_expRegModel
DM_expRuleModel
DM_getClasCostRate
DM_getClasMdlName
DM_getClasMdlSpec
DM_getClasTarget
DM_getClusConf
DM_getClusMdlName
DM_getClusMdlSpec
DM_getClusMdlType
DM_getClusScore
DM_getClusScore(clusterid)
DM_getClusterID
DM_getClusterName
DM_getClusters
DM_getConfidence
DM_getConfidence(class)
DM_getConfidence(low, up)
DM_getEnv
DM_getErrors(rowcount)
DM_getFields
DM_getNumClusters
DM_getNumRules
DM_getNumTransacts
DM_getOpenModels
DM_getPredClass
DM_getPredDev(prob)
DM_getPredStdDev
DM_getPredValue
DM_getQuality
DM_getQuality(clusterid)
DM_getRBFRegionID
DM_getRegMdlName
DM_getRegMdlSpec
DM_getRegTarget
DM_getRegRSquared
DM_getRuleBodies
DM_getRuleMdlName
DM_getRules
DM_getTreeNodeID
DM_getTreeRules
DM_impApplData
DM_impClasFile
DM_impClasFileE
DM_impClasModel
DM_impClusFile
DM_impClusFileE
DM_impClusModel
DM_impRegFile
DM_impRegFileE
DM_impRegModel
DM_impRuleFile
DM_impRuleFileE
DM_impRuleModel
DM_openModel
DM_setEnv
Command reference
The idmcheckdb command
The idmdisabledb command
The idmenabledb command
The idminstfunc command
The idmuninstfunc command
The idmlevel command
The idmlicm command
The idmmkSQL command
The idmxmod command
Administration
Getting error information
Getting support
Problem identification worksheet
Getting product information
Getting trace information
Tracing errors
Getting DB2 diagnostic information
Migrating from IM Scoring V7.1
Working with IM Scoring V7.1 and V8.2 in parallel
Migrating from DB2 Version 7
Exporting and importing models with the use of compression
Exporting and importing models by means of DB2 Utilities
Importing models in unfenced mode
Applying Neural models
Using the function DM_getClusterID
Migrating from IM Scoring Version 8.1
Migrating a DB2 instance (UNIX only)
Migrating databases (all platforms)
Database instance restart
Appendixes
Appendix A. IM Scoring conformance to PMML
IM Scoring application
IM Scoring conversion tools
Regression models
Features supported in addition to PMML 2.1
Appendix B. SAS Enterprise Miner support
Appendix C. SPSS Clementine support
Appendix D. The DB2 REC2XML scalar function
Appendix E. Coexistence with IM Modeling
Shared schema
Shared data types
Shared functions
Shared methods
Shared commands
Appendix F. Using IM Scoring in a multilanguage environment
Appendix G. Encoding considerations when exporting models
Appendix H. Notices
Trademarks
Bibliography
IBM DB2 Intelligent Miner publications
Related information
IBM Web sites
Other Web sites
Index

Figures

  1. Using IM products in your business environment
  2. IM Scoring overview
  3. The interplay of IM Modeling and IM Scoring
  4. The IM Scoring process
  5. Scoring data types and syntax
  6. Applying a model
  7. Model import processes
  8. Applying a model to data
  9. Architecture sample to realize a call-center scenario
  10. User options

Tables

  1. Formatting conventions
  2. Abbreviations
  3. PMML model types, mining functions, and mining algorithms
  4. Sample files for the Clustering mining function of IM Scoring
  5. Sample files for IM Scoring Java Beans
  6. Import functions and related data types and tables
  7. Import functions using a specific XML encoding
  8. Import functions using CLOB values
  9. Functions for applying models
  10. Application functions and their data types and results data
  11. Application functions and their data types and specifiable results data
  12. Result specification methods for the type DM_ClasResultSpec and their purpose
  13. Result specification methods for the type DM_ClusResultSpec and their purpose
  14. Results functions and their purpose (Clustering model)
  15. Results functions and their purpose (Classification model)
  16. Results functions and their purpose (Regression model)
  17. IM Scoring Java Beans methods for accessing model metadata
  18. IM Scoring Java Beans methods for accessing computed results
  19. Data types specific to IM Scoring
  20. Mining field types
  21. Result values for DM_getClusters
  22. Sample table returned by DM_getClusters
  23. Result values for DM_getErrors
  24. Result values for DM_getFields
  25. Sample table returned by DM_getFields
  26. Result values for DM_getRuleBodies
  27. Sample table returned by DM_getRuleBodies
  28. Result values for DM_getRules
  29. Sample table returned by DM_getRules
  30. Result values for DM_getTreeRules
  31. Sample table returned by DM_getTreeRules
  32. The idmcheckdb messages
  33. Column Values String Result
  34. Character replacements for XML attribute values and element values

About this book

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:

Who should use this book

This book is intended for the following users:

Conventions and terminology used in this book

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.

Note:
Identifiers such as table or column names are translated into uppercase in DB2 SQL statements, if they are not enclosed by double quotes ("). To avoid problems, identifiers are written in uppercase and enclosed by double quotes in this book, such as:
Example of how to specify identifiers
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.

Table 1. Formatting conventions
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:
  • Files and directories
  • Database tables and columns
  • SQL methods, functions, and data types
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.

Table 2. Abbreviations
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

How this book is structured

This book is divided into the following parts:

User's guide
Contains the following:
Reference
Provides a reference resource to all the IM Scoring database objects and utilities.
Administration
Provides information on how to administer, diagnose, and migrate IM Scoring.

The appendixes provide reference information.

How to read the syntax diagrams

In the reference part of this book, the syntax for IM Scoring's functionality is described using the following structure:

How to send your comments

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:

What is new in version 8.2

This section introduces you to the new features in IM Scoring.

Improved model interoperability

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:

Functional enhancements

Extended 64-bit support
IM Scoring for DB2 is available as 32-bit and 64-bit versions.
New apply functions
The apply function now allows to reference a model to be used in the scoring statement simply by its name. For more information refer to:
idmmkSQL
This command has been enhanced to enable you to operate directly on models in the database. Scoring results can be generated without creating views and physical tables. For details see The idmmkSQL command.
idmenabledb
This command has been enhanced to enable you to specify the size of the result specification. It can also configure the database manager configuration parameters. For details see The idmenabledb command.
Improved samples
The IM Scoring samples have been enhanced and reworked.
Improved error detection
During model import errors are checked and identified.
Performance enhancement for real-time scoring
IM Scoring supports 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. For details, see Using the model cache for real-time scoring.
Support for Regression models produced by IM Modeling
IM Scoring supports Transform Regression models. Transform Regression is a new regression algorithm introduced with the new easy mining capabilities of IM Modeling. For more information refer to DB2 Intelligent Miner Modeling: Administration and Programming.
Read the mining model from a DB2 table
The Java Record Scorer API has been extended to read the mining model not just from a file, but also from a DB2 table. For details, see Specifying the mining model to be used.
Customization of the results data
You can now define which part of the result you want to obtain when scoring. For details, see Customizing the results data.
New data types
New data types are listed in Data types reference:
New methods
New methods are provided:
New or updated functions
The user-defined functions are provided:
Stored procedures
The user-defined functions are provided:

Standards conformance

PMML 2.1 support
IM Scoring can read, store, and use PMML models up to Version 2.1. Its conversion utilities can also generate PMML 2.1 models. For more information refer to Appendix A. IM Scoring conformance to PMML.
SQL/MM
IM Scoring adheres to the SQL Multimedia (SQL/MM) standard, which is an International Standard for data mining. The standard is developed by ISO (the International Organization for Standardization) and IEC (the International Electrotechnical Commission), who together form a specialized system for worldwide standardization.

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.

Shared infrastructure with IM Modeling

IM Scoring shares common infrastructure like XML parsing, error handling, tracing, licensing, and diagnostics with IM Modeling.

Consistency notices

You should consider the following consistency notices when using IM Scoring V8.2:

User's guide

Introducing the Intelligent Miner products
IBM DB2 Intelligent Miner Scoring
IBM DB2 Intelligent Miner Modeling
IBM DB2 Intelligent Miner Visualization
IBM DB2 Intelligent Miner for Data
Introducing IM Scoring
Introducing data mining functions
Associations
Classification
Clustering
Regression
PMML: A markup language for data mining
Sources of PMML models
PMML models created by IM Modeling
PMML models created by IM for Data
PMML models created by vendor tools
Deployment scenarios
Introducing the SQL/MM API
Familiarizing yourself with the SQL API
Introducing SQL statements for scoring
Quick start using the sample applications
Creating database objects
Generating SQL scripts from your own mining models
Sample files
Completing the practice exercises
Creating a table and importing data
Importing a mining model
Applying a model and getting results values
Determining the customer segment for each customer in a table
Storing scoring results permanently
Obtaining specific results for customers
Optimizing performance and scoring a single record
Recomputing scores in real time
Extracting information from a model
Using IM Scoring Java Beans to score records
Using idmmkSQL to work with your own mining models
Deleting the entries from the sample tables
Using IM Scoring
Scoring data types, methods, and functions
User-defined data types
User-defined methods
User-defined functions
Creating database objects
Enabling databases
Disabling databases
Checking databases
Deploying mining models
Using models created by IM Modeling
Exporting models from IM for Data
Converting exported models
Importing mining models
Importing mining models from a file
Importing mining models from a file using a specific XML encoding
Importing mining models from a CLOB value in a database table
Generating SQL statements from models
Extracting information from a model
Applying mining models
Using the application functions
Specifying data by means of REC2XML
Specifying data by means of DM_applData
Specifying data by means of CONCAT
Results data
Customizing the results data
Getting application results
Handling missing values
Using the model cache for real-time scoring
Performance considerations
Setting the model cache size
Examples for real-time scoring
Using IM Scoring Java Beans
Setting environment variables
Specifying the mining model to be used
Accessing model metadata
Specifying a data record
Using the Java Single Record Scorer
Applying scoring
Accessing computed results
Scoring example
ScoringException classes

Introducing the Intelligent Miner products

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. Using IM products in your business environment
Using IM  products in your business environment

Figure 1 shows a typical scenario of how you can use the IM products in your business environment:

For more information refer to:

IBM DB2 Intelligent Miner Scoring

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.

Table 3. PMML model types, mining functions, and 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
Notes:
  1. IM Scoring supports models that are built by the RBF Prediction algorithm of the Intelligent Miner for Data. These models are not yet part of PMML. You can export these models in XML format from the Intelligent Miner for Data and use them with IM Scoring.
  2. Mining models that are applied by the SQL API of IM Scoring must be contained in database tables.
  3. Transform Regression models created by IM Modeling are not fully PMML 2.1 compliant models. They use existing PMML 2.1 element names with several minor additions. These additions have been submitted to be part of the next PMML 3.0 standard.

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.

IBM DB2 Intelligent Miner Modeling

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.

IBM DB2 Intelligent Miner Visualization

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.

IBM DB2 Intelligent Miner for Data

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:

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.

Introducing IM Scoring

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:

IM Modeling
This provides mining models in PMML format that are directly stored in DB2.
IM for Data
This produces models that can be exported as PMML models.
Other tools
Any other tool that provides mining models in PMML format, such as SAS Enterprise Miner (SAS EM) or SPSS Clementine.
Note:
For more information on PMML support refer to Appendix A. IM Scoring conformance to PMML.

You use IM Scoring as follows:

  1. Import or load a mining model into a DB2 table.
  2. Apply the model to data within DB2 and optionally store scoring results in a database table.
  3. Access the results. These scoring results can have different contents. IM Scoring provides functions to retrieve the values of scoring results.

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.

Figure 2. IM Scoring overview
IM Scoring overview

Introducing data mining functions

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:

Notes:
  1. IM Scoring supports only the application of these models.
  2. An overview of the data mining functions, PMML model types, and mining algorithms is provided in Table 3.

Associations

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?

Notes:
  1. IM Scoring does not support the application of Associations models.
  2. IM Scoring provides support for managing PMML models that contain Association rules, such as importing a Rule model or accessing the model content. However, IM Scoring does not have a scoring mode for association rules.

Classification

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.

Clustering

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

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: A markup language for data mining

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.

Sources of PMML models

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.

PMML models created by IM Modeling

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:

Figure 3. The interplay of IM Modeling and IM Scoring
The interplay of IM Modeling and IM Scoring

PMML models created by IM for 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:

Figure 4. The IM Scoring process
The IM Scoring process

PMML models created by vendor tools

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:

Deployment scenarios

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.

Batch scoring with persistent results
The most efficient way to compute scores is to apply the scoring function to all records of a table in batch mode. In this case the scoring result object (or individual values from a scoring result) is stored persistently in a table using the INSERT statement. Use this approach if you want to:

See Storing scoring results permanently for an example of batch scoring with persistent results.

Batch scoring from a view
In this case you create a scoring result VIEW. The view definition contains the scoring apply function. In this case the scoring results are recomputed whenever you SELECT from the view. Using a VIEW saves you from computing a score for all records because the scores are only computed for the records actually retrieved. Use this approach if: See Creating a table and importing data and Determining the customer segment for each customer in a table for an example of scoring from a view.
Triggered scoring
You can include the scoring apply function in the definition of an INSERT or UPDATE trigger that recomputes a persistent scoring result, whenever a record is inserted or changed. Using a trigger allows to move the business rules from the applications into the database. Use this approach if: You can combine this approach with BATCH scoring. When loading the table in a batch window, compute all scores in batch mode. For data changes that trickle in between batch updates use triggered scoring.

See Recomputing scores in real time for an example of setting triggers.

Real-time scoring of individual records
In this scenario the record to be scored is created by an application and a score must be computed at once. A typical example is a call-center or retail point-of-sale application where new data about a customer becomes available and a cross-selling recommendation must be computed in real time.

In this case you have the following options:

Model caching
To optimize performance in scenarios where you repeatedly use the same PMML model for different SQL statements, consider to exploit the model cache as described in Using the model cache for real-time scoring. This is very important for the real-time scoring scenarios described before where you issue many SQL statements, each of them scoring only a few records.

See Optimizing performance and scoring a single record for examples of using the model cache.

Introducing the SQL/MM API

Here you find a general introduction to the SQL/MM API terminology and statements.

Familiarizing yourself with the SQL API

The SQL/MM API is a standardized open SQL API, that:

The following list familiarizes you with the SQL API terminology:

LogicalDataSpec
Describes the logical schema of input table
Model
Describes the rules and patterns found in the modeling phase
ApplicationData
Describes the row data record provided for scoring
Result
Describes the scores computed in scoring

Introducing SQL statements for scoring

Figure 5 maps the conceptual objects to the DB2 user-defined types (UDTs) used in IM Scoring. This figure shows an example for clustering.

Figure 5. Scoring data types and syntax
Scoring data types and syntax

In Figure 5 the Scoring function DM_applyClusModel receives the following parameters:

As the scores are computed in a scalar user-defined function, the scoring step can be embedded in arbitrary SQL statements.

Example 1:
Apply a Clustering model to determine the customer segment for each customer in table BANKING_SCORING. This example joins the BANKING_SCORING table containing the data rows and the model table IDMMX.CLUSTERMODELS. The model BLOB with MODELNAME 'DemoBanking' 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";
Example 2:
This example uses a simpler syntax where the model is referenced by MODELNAME 'DemoBanking' and is implicitly read from table IDMMX.CLUSTERMODELS into the model cache:
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";

Quick start using the sample applications

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.

Creating database objects

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:

fenced
To run the sample applications provided with IM Scoring in fenced mode. In fenced mode the IM Scoring functions run in processes that are separate from the database agents.
dbcfg
To change the database configuration (DB CFG) as recommended to use IM Scoring without prompting the user.

For more information see:

Generating SQL scripts from your own mining models

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.

Sample files

The IM Scoring package includes sample files consisting of a series of practice exercises in using IM Scoring. This tutorial material enables you to:

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.

Table 4. Sample files for the Clustering mining function of IM Scoring
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:
  • Name of the model
  • Number of clusters
  • Number and names of fields
  • Model quality from a Clustering model
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:

  1. Creates a results table
  2. Implicitly reads the Clustering model from table IDMMX.CLUSTERMODELS into the model cache.
  3. Applies the Distribution-based Clustering model to the banking data to determine the customer segment for each customer in table BANKING_SCORING.
  4. Stores the calculated results in the table.
  5. Obtains results values from the table.
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:
  1. Deletes the entries from the sample tables that you have created during the exercises
  2. Avoids error messages if only parts of the examples have been completed
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.
Table 5. Sample files for IM Scoring Java Beans
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

Completing the practice exercises

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:

Notes:
  1. Before starting the tasks, you must be connected to a database that is enabled for the use of IM Scoring. Enter the following command to connect to the database:
    db2 connect to dbname
  2. To run the scripts, you must have SELECT and INSERT privileges on the IDMMX."CLUSTERMODELS" table.
  3. Go to the directory where the samples are installed. See DB2 Intelligent Miner Modeling, DB2 Intelligent Miner Scoring, DB2 Intelligent Miner Visualization: Installing the Intelligent Miner products and Sample files for information on the directories where the sample files are stored.

Creating a table and importing data

In 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";

Importing a mining model

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'));
Note:
The absolute path of the PMML model is different on each platform. On Windows, the absolute path is automatically modified at installation time to be consistent with the chosen installation path.

Applying a model and getting results values

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.

Figure 6. Applying a model
Applying a model

Determining the customer segment for each customer in a table

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";
Notes:
  1. Use this syntax if your models are not stored in Intelligent Miner default tables.
  2. impApplData is required in this sample, because the version of the Apply function expects a value of type DM_ApplicationData instead of VARCHAR.

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"
  ),
Note:
This definition is required if the names used in the model do not match the names provided by the data.

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.

Note:
The column names specified in the call to REC2XML must exactly match the names of fields that are used in the mining model. For information on how to retrieve the names of the fields in a mining model, see Applying mining models.

Finally, the script obtains the cluster ID and the Clustering quality from CLUSTERRESULT using the functions DM_getClusterID and DM_getQuality.

Storing scoring results permanently

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:

  1. CREATE...NOT LOGGED INITIALLY
  2. Execute the scoring run in the same transaction run (specify C OFF) or deactivate logging until the run is finished using:
    alter table activate not logged initially
    For more information refer to the DB2 SQL Reference.
  3. UPDATE COMMAND OPTIONS USING C off;

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';

Obtaining specific results for customers

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" ;
Note:
The column names specified in the call to REC2XML must exactly match the names of fields that are used in the mining model. For information on how to retrieve the names of the fields in a mining model, see Applying mining models.

Optimizing performance and scoring a single record

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_%';

Recomputing scores in real time

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)
@

Extracting information from a model

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;

Using IM Scoring Java Beans to score records

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:

  1. Set the PATH and CLASSPATH variables as described in Setting environment variables.
  2. Change to the sample directory.
  3. Type javac 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

Using idmmkSQL to work with your own mining models

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:

  1. Execute the following command:
    idmmkSQL -d db2 clusDemoBanking.pmml clusDemoBanking.db2
    This generates the file clusDemoBanking.db2.
  2. Open the file clusDemoBanking.db2 with an editor of your choice and perform the following modifications:
    Note:
    idmmkSQL uses default tables to store mining models. If different tables are used, the following modifications are required in addition to this:
    • Replace IDMMX.CLUSTERMODELS with the name of the table which is determined to store mining models. This appears twice in the file.
    • Replace MODEL with the column name containing the mining model name.
    • Replace MODELNAME with the column name containing the mining model.
  3. Save the modified file.

To run the script clusDemoBanking.db2, use the following command:

db2 -stf clusDemoBanking.db2

The script:

  1. Imports the PMML model clusDemoBanking.pmml into the table IDMMX.CLUSTERMODELS
  2. Performs a scoring run with the input data from the table BANKING_SCORING
  3. Writes the results into the table RESULTTABLE

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.

Note:
idmmkSQL can also generate a template SQL script out of a model that is located in the database.

Deleting the entries from the sample tables

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:

  1. Deletes the entries from the sample tables that you have created
  2. Avoids error messages if only parts of the examples have been completed
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";

Using IM Scoring

This chapter guides you through the use of IM Scoring to perform data mining tasks within a DB2 database. Use IM Scoring to:

Scoring data types, methods, and functions

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.

User-defined data types

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.

Distinct types
The following user-defined types are distinct types in IM Scoring:
Structured type
The following user-defined type is a structured type in IM Scoring:

User-defined methods

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.

Method syntax
To call, or invoke, a method using the method syntax:

Example:


select IDMMX.DM_getClusMdlSpec(modelcolumn)..DM_getNumFields()...
Function syntax
To call, or invoke, a method using the function syntax:

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.

User-defined functions

IM Scoring provides scoring functions, also referred to as user-defined functions (UDFs), which enable you to:

Note:
The function syntax is described in User-defined methods.

Creating database objects

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.

Enabling databases

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.

Disabling databases

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.

Checking databases

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.

Example:
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.

Deploying mining models

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.

Using models created by IM Modeling

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.

Exporting models from IM for Data

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:

  1. Click the results object on the IM for Data GUI.
  2. From the Selected menu, click Export.
  3. Select one of the following formats:

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.

Converting exported models

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.

Importing mining models

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:

Importing mining models from a file

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.

Table 6. Import functions and related data types and tables
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.

Figure 7. Model import processes
Model import processes overview

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'))
Note:
The absolute path to the model file must be given.

Importing mining models from a file using a specific XML encoding

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.

Table 7. Import functions using a specific XML encoding
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' )

Importing mining models from a CLOB value in a database table

You can use import functions that import a PMML model that already resides in a database table column as a CLOB value.

Note:
Use these functions to get a value of one of the model data types from a CLOB value. Do not use the casting functions that are provided by DB2.

Table 8 shows the relationship between the import function, the returned data type, and the sample table.

Table 8. Import functions using CLOB values
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.

  1. A model name and a model in PMML format as a CLOB value are selected from a table, PMMLCLUSTERMODELS.
  2. They are then inserted into the CLUSTERMODELS table.
  3. The PMML model is converted from the CLOB data type to the DM_ClusteringModel data type.
 db2 insert into IDMMX.CLUSTERMODELS (MODELNAME, MODEL) select modelname,
                IDMMX.DM_impClusModel( model) from PMMLCLUSTERMODELS
 

Generating SQL statements from models

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:

  1. Reads a PMML model from a database or from a file and analyzes the model
  2. Writes a template SQL script that can be used to do these tasks:

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.

Extracting information from a model

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.

Applying mining models

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:

Using the application functions

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.

Table 9. Functions for applying models
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:

An imported mining model of the appropriate type
This input parameter can be:
The data to which the model is applied
The data to which the model is applied must be provided as an XML string containing the column names and values of a row. For example:
<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( ... ) )
Result specification
The parameter resultspec is optional. It is only valid for DM_applyClusModel and DM_applyClasModel. For more information refer to Customizing the results data.

The following list shows how to invoke the various types of the DM_applyXXXModel functions:

Specifying a model with the model name and a data record as a character string
DM_applyXXXModel( model name, data record )

Where XXX can be CLAS, CLUS, or REG. An example is:

IDMMX.DM_applyClusModel( 'DemoBanking', rec2xml( 1.0, 'COLATTVAL', '', 
"AGE","GENDER","MARITAL_STATUS" ) ) 
Specifying a model as a LOB and an application data object
DM_applyXXXModel( model, application data )

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:

DM_applyXXXModel( model name, data record, resultspec )
Where XXX can be CLAS or CLUS. An example is:
IDMMX.DM_applyClusModel( 'DemoBanking', rec2xml( 1.0, 'COLATTVAL', '', 
"AGE","GENDER","MARITAL_STATUS" ),
IDMMX.DM_ClusResultSpec()..DM_setCluster(3) ) 
DM_applyXXXModel ( model, application data, resultspec )
Where XXX can be CLAS or CLUS. An example is:
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:

  1. A field name is compared with the values of the column FIELDNAME returned by the table function DM_getFields called on the model.
  2. If there is no match, a field name is compared with the values of the column COLNAME returned by the table function DM_getFields called on the model.

Specifying data by means of REC2XML

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)) ...
Notes:
  1. The field names of the active fields in the model must match the columns of the table that is used for REC2XML.
  2. If this is not the case, you can do the following:
    1. Create a view on the table to have the same column names as field names in the model.
    2. Use the CONCAT function instead of REC2XML to build the XML string. This technique allows you to map the column names to the field names in the model. By using CONCAT, you achieve performance similar to that achieved when you use REC2XML.
    3. Use the function DM_applData instead of REC2XML. DM_applData is slower, but it is easier to use than CONCAT. DM_applData also allows you to map the field names in the model to the column names in the table.

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.

Specifying data by means of DM_applData

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 )

Specifying data by means of CONCAT

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>')
Note:
IM for Data handles date values and time values in a character ISO format. You might want to specify a date value or a time value as CONCAT operator, and you might want to apply a model created by IM for Data. In this case, the date value and the time value must be converted to character ISO format. To do this, use CHAR(<value>, ISO) for a date value and CHAR(<value>, JIS) for a time value.

Results data

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.

Table 10. Application functions and 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
  • Predicted value
  • Data region ID for an RBF Regression model
  • Confidence, deviation, standard deviation are only available with Transform Regression models
Note:
If you create your own DB2 tables to store results, ensure that you include a column that is configured for the appropriate data type.

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.

Figure 8. Applying a model to data
Applying a model to data

Customizing the results data

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.

Table 11. Application functions and 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
Note:
For more information on overloaded functions refer to Using the application functions.

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:

An imported mining model of the appropriate type
Refer to Using the application functions
The data to which the model is applied
Refer to Using the application functions
A specification of the result data (for clustering and classification only)
First create an empty result specification object, for example:
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.

Notes:
  1. Calling the overloaded application functions with a NULL result specification object is equivalent to calling the corresponding application function with only 2 parameters.
  2. Only the Results data that has been explicitly set in the result specification object will be available in the scoring result.
  3. If the result is too small to write all the information required by the user, only a partial results data is written in the result and a warning is returned the first time this happens. Some of the get functions applying on the result will then return NULL even if the corresponding results data has been requested by the user.

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.

Table 12. Result specification methods for the type DM_ClasResultSpec and their purpose
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:

"1."
for the left child node
"2."
for the right child node
Notes:
  1. This node ID can be seen in IM Visualization when displaying the tree model.
  2. This option is ignored if the model is not a tree model.
Table 13. Result specification methods for the type DM_ClusResultSpec and their purpose
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.

Getting application results

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.

Table 14. Results functions and their purpose (Clustering model)
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.

Table 15. Results functions and their purpose (Classification model)
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.

Table 16. Results functions and their purpose (Regression model)
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:

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:

Handling missing values

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.

Notes:
  1. Fields defined in the PMML model can explicitly define a validity range. All values outside this range are considered as missing values.
  2. Fields defined in the PMML model can define a missing value replacement (PMML 2.0 and higher). In this case, all missing values are replaced by a valid value indicated in the model.
Classification
Clustering
Regression

Using the model cache for real-time scoring

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:

Unpinned
A model that is used in a scoring run is automatically added to the cache (unpinned models). If the cache is full, an unpinned model automatically replaces an older unpinned model in the cache.

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.
Pinned
Pinned models must be explicitly inserted into and removed from the cache. The function DM_openModel allows to store a model in the cache regardless of the maximum size of the cache (pinned models).

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.

Notes:
  1. A pinned model cannot be removed from the cache when a free cache entry for another model (which is not to be pinned) is searched and an old model is be to removed from the cache because the cache is full.
  2. Only pinned models can appear more than once in the cache. The user cannot affect which of the models is used for a concrete scoring run. Adding a model more than once to the cache can improve performance in an environment with many concurrent scoring users and multiple processors.

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.

Notes:
  1. You can set the maximum number of unpinned models that can be held in the cache. The default size of the model cache is set to 1 unpinned model.
  2. You must enable your database in fenced mode. The unfenced mode does not support model caching.
  3. A table function allows to see the cache as a DB2 table.
  4. You can use SQL functions to inspect and control the model cache.
  5. The scope of cached models is the database instance. A model that is inserted into the cache can be used by each database that belongs to the instance. A model can be removed from the cache from each database that belongs to the instance.

Use the following configuration parameters and UDFs for model caching:

Setting the model cache size
The following call allows the cache store a maximum of three unpinned models:
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.
Loading the pinned models into the cache
For more information refer to DM_openModel.
Explicitly removing a model from the cache
For more information refer to DM_closeModel.
Removing all models from the cache
For more information refer to DM_closeAllModels.
Using scoring apply UDFs
The UDFs apply a model specified by a model name to a data record. Parameters are passed as VARCHAR (not as LOBs) to improve performance. For more information refer to:
Inspecting the model cache
For more information refer to DM_getOpenModels.

Performance considerations

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.

Note:
The more records are scored in one scoring run, the less is the relative performance improvement by using a cache.

The scoring run can be a bit slower than without cache:

Setting the model cache size

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.

Note:
If you want to define this setting once and make it available for all future sessions, use a system environment variable (Windows) or the DB2 registry variable DB2ENVLIST (UNIX(R)) to set IDM_MX_MAX_OPEN_MODELS.

Examples for real-time scoring

Here you find examples on how to specify real-time scoring:

Using IM Scoring Java Beans

This section describes the interfaces of IM Scoring Java Beans.

To perform the scoring of a data record, you must specify the following input:

  1. The mining model to be used
  2. One or more data records for which you want to compute a score value

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.

Note:
You can access the online documentation (Javadoc) of the Java API using the following HTML start page in the IM Scoring installation directory:
\doc\ScoringBean\index.html

Setting environment variables

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:

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.

Specifying the mining model to be used

This section describes how to specify the model.

The RecordScorer class expects the mining model to be stored in one of the following:

Accessing model metadata

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:

Table 17. IM Scoring Java Beans methods for accessing model metadata
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:
  • For CLUSTERING_TYPE, the result fields CLUSTER_ID, CLUSTER_SCORE, and CLUSTER_QUALITY are relevant.
  • For CLASSIFICATION_TYPE, the result fields PREDICTED_CLASS and CONFIDENCE are relevant.
  • For REGRESSION_TYPE, the result fields PREDICTED_VALUE and RBF_REGION_ID are relevant.

Specifying a data record

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.

Using the Java Single Record Scorer

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.

Figure 9. Architecture sample to realize a call-center scenario
Architecture sample to realize a call-center scenario
Note:
To get optimum performance throughput, you might decide to run each mining model in a separate process. In this case, you would pass only the new records to the appropriate scoring process. This results in a considerable performance improvement. The reason for the improvement is that the model-loading step, which is very time consuming, is done only once.

For more information refer to Specifying the mining model to be used.

Applying scoring

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
 

Accessing computed results

After you have successfully called the score(Map) method, you can access the computed result fields by using one of the following methods:

Table 18. IM Scoring Java Beans methods for accessing computed results
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.

Scoring example

 
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.

ScoringException classes

The following exception classes are used by the RecordScorer and its base class Scorer:

ModelException
Used if an error occurred that was relevant to the mining model that was specified.
RecordException
Used if an error occurred that was relevant to the data record that was used.
ResultException
Used if an error occurred that was relevant to the result fields that were computed.

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.

Reference

Parameter sizes
Data types reference
Methods reference
DM_expDataSpec
DM_getFldName
DM_getFldType
DM_getNumFields
DM_impDataSpec
DM_isCompatible
DM_setAllClasses
DM_setBestCluster
DM_setClass(class)
DM_setCluster(clusterid)
DM_setPredClass
DM_setTreeNodeID
Functions and stored procedures reference
DM_applData
DM_applyClasModel
DM_applyClusModel
DM_applyRegModel
DM_closeAllModels
DM_closeModel
DM_expClasModel
DM_expClusModel
DM_expRegModel
DM_expRuleModel
DM_getClasCostRate
DM_getClasMdlName
DM_getClasMdlSpec
DM_getClasTarget
DM_getClusConf
DM_getClusMdlName
DM_getClusMdlSpec
DM_getClusMdlType
DM_getClusScore
DM_getClusScore(clusterid)
DM_getClusterID
DM_getClusterName
DM_getClusters
DM_getConfidence
DM_getConfidence(class)
DM_getConfidence(low, up)
DM_getEnv
DM_getErrors(rowcount)
DM_getFields
DM_getNumClusters
DM_getNumRules
DM_getNumTransacts
DM_getOpenModels
DM_getPredClass
DM_getPredDev(prob)
DM_getPredStdDev
DM_getPredValue
DM_getQuality
DM_getQuality(clusterid)
DM_getRBFRegionID
DM_getRegMdlName
DM_getRegMdlSpec
DM_getRegTarget
DM_getRegRSquared
DM_getRuleBodies
DM_getRuleMdlName
DM_getRules
DM_getTreeNodeID
DM_getTreeRules
DM_impApplData
DM_impClasFile
DM_impClasFileE
DM_impClasModel
DM_impClusFile
DM_impClusFileE
DM_impClusModel
DM_impRegFile
DM_impRegFileE
DM_impRegModel
DM_impRuleFile
DM_impRuleFileE
DM_impRuleModel
DM_openModel
DM_setEnv
Command reference
The idmcheckdb command
The idmdisabledb command
The idmenabledb command
The idminstfunc command
The idmuninstfunc command
The idmlevel command
The idmlicm command
The idmmkSQL command
The idmxmod command

Parameter sizes

The sizes of the input and output parameters of the methods, functions, and procedures are as follows:

Data types reference

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.

Table 19. Data types specific to IM Scoring
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_applData

DM_applyClasModel

DM_applyClusModel

DM_applyRegModel

DM_impApplData

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_applyClasModel

DM_expClasModel

DM_getClasMdlName

DM_getClasCostRate

DM_getClasMdlSpec

DM_getClasTarget

DM_getFields

DM_getTreeRules

DM_impClasFile

DM_impClasFileE

DM_impClasModel

DM_openModel

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_applyClasModel

DM_getConfidence

DM_getConfidence(class)

DM_getPredClass

DM_getTreeNodeID

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_setAllClasses

DM_setClass(class)

DM_setPredClass

DM_setTreeNodeID

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_applyClusModel

DM_getClusConf

DM_getClusScore

DM_getClusScore(clusterid)

DM_getClusterID

DM_getQuality

DM_getQuality(clusterid)

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_setBestCluster

DM_setCluster(clusterid)

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_applyClusModel

DM_expClusModel

DM_getClusMdlName

DM_getClusMdlSpec

DM_getClusMdlType

DM_getNumClusters

DM_getClusterName

DM_getFields

DM_impClusFile

DM_impClusFileE

DM_impClusModel

DM_getClusMdlType

DM_openModel

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:

DM_getClasMdlSpec

DM_getClusMdlSpec

DM_getRegMdlSpec

Methods:

DM_getFldName

DM_getFldType

DM_getNumFields

DM_expDataSpec

DM_impDataSpec

DM_isCompatible

DM_RegressionModel BLOB Distinct type: It identifies data within DB2 as:
  • An RBF or Neural Regression model
  • Transform Regression model
The data type is associated with the model when the model is imported by means of the DM_impRegFile function. If the model is stored in a database table, the column must be configured for this data type.

Functions:

DM_applyRegModel

DM_expRegModel

DM_getFields

DM_getRegMdlName

DM_getRegMdlSpec

DM_getRegRSquared

DM_getRegTarget

DM_impRegFile

DM_impRegFileE

DM_impRegModel

DM_openModel

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_applyRegModel

DM_getConfidence(low, up)

DM_getPredDev(prob)

DM_getPredStdDev

DM_getPredValue

DM_getRBFRegionID

DM_RuleModel BLOB Distinct type: It represents an Associations model.

Functions:

DM_getFields

DM_getRules

DM_getRuleBodies

DM_getNumRules

DM_getNumTransacts

DM_impRuleFile

DM_impRuleFileE

DM_impRuleModel

Methods reference

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.

DM_expDataSpec

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.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-fields..DM_expDataSpec--(--)--------------------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_expDataSpec--(--fields--)--------------------------------><

Parameters

fields
A value of type DM_LogicalDataSpec

Return value

The return value is a CLOB value converted from fields.

DM_getFldName

This method returns the name of a field at a specified position in a value of type DM_LogicalDataSpec.

Note:
Instead of using this method, it is recommended that you use the DM_getFields function on the model from which this DM_LogicalDataSpec value is extracted.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-fields..DM_getFldName--(--position--)-----------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getFldName--(--fields--,--position--)--------------------><

Parameters

fields
A value of type DM_LogicalDataSpec consisting of a set of fields
position
An INTEGER value, ranging from 1 to the number of fields, that specifies the position

Return value

Related concepts

Extracting information from a model

DM_getFldType

This method returns the mining field type of a specified field that is contained in a value of type DM_LogicalDataSpec.

Note:
Instead of using this method, it is recommended that you use the DM_getFields function on the model from which this DM_LogicalDataSpec value is extracted.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-fields..DM_getFldType--(--fieldName--)----------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getFldType--(--fields--,--fieldName--)-------------------><

Parameters

fields
A value of type DM_LogicalDataSpec
fieldName
A field name, of type VARCHAR, that is already contained in fields

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.

Table 20. Mining field types
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

Return value

Related concepts

Extracting information from a model

DM_getNumFields

This method returns the number of fields that are contained in a value of type DM_LogicalDataSpec.

Note:
Instead of using this method, it is recommended that you use the DM_getFields function on the model from which this DM_LogicalDataSpec value is extracted.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-fields..DM_getNumFields--(--)-------------------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getNumFields--(--fields--)-------------------------------><

Parameters

fields
A value of type DM_LogicalDataSpec consisting of a set of fields

Return value

The return value is the number of fields that are contained in fields. The return value is of type INTEGER.

Related concepts

Extracting information from a model

Examples

Examples are provided in:

DM_impDataSpec

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.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-fields..DM_impDataSpec--(--logDataSpec--)-------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impDataSpec--(--fields--,--logDataSpec--)----------------><

Parameters

fields
A value of type DM_LogicalDataSpec
logDataSpec
A CLOB value containing logical data specifications

Return value

The return value is fields containing the content of logDataSpec. Any existing definitions in fields are overwritten by the content of logDataSpec.

DM_isCompatible

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.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-existLogDataSpec..DM_isCompatible--(--logDataSpec--)--------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_isCompatible--(--existLogDataSpec--,--logDataSpec--)-----><

Parameters

existLogDataSpec
A value of type DM_LogicalDataSpec consisting of a set of fields
logDataSpec
A value of type DM_LogicalDataSpec to be checked for compatibility

Return value

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).

DM_setAllClasses

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.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-resultSpec..DM_setAllClasses--(--)--------------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_setAllClasses--(--resultSpec--)--------------------------><

Parameters

resultSpec
An object of data type DM_ClasResultSpec used to specify the results value to be calculated by the function DM_applyClasModel

Return value

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.

Related concepts

DM_setBestCluster

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.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-resultSpec..DM_setBestCluster--(--)-------------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_setBestCluster--(--resultSpec--)-------------------------><

Parameters

resultSpec
An object of data type DM_ClusResultSpec used to specify the results value to be calculated by the function DM_applyClusModel

Return value

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.

Related concepts

DM_setClass(class)

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.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-resultSpec..DM_setClass(class)------------------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_setClass--(--resultSpec--,--class--)---------------------><

Parameters

resultSpec
An object of data type DM_ClasResultSpec used to specify the results value to be calculated by the function DM_applyClasModel
class
A value of data type VARCHAR that is a valid value of the predicted field in the Classification model

Return value

Related concepts

DM_setCluster(clusterid)

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.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-resultSpec..DM_setCluster--(--clusterid--)------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_setCluster--(--resultSpec--,--clusterid--)---------------><

Parameters

resultSpec
An object of data type DM_ClusResultSpec used to specify the results value to be calculated by the function DM_applyClusModel
clusterid
A value of data type INTEGER between 1 and the result of function DM_getNumClusters called on the Clustering model

Return value

Related concepts

DM_setPredClass

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.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-resultSpec..DM_setPredClass--(--)---------------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_setPredClass--(--resultSpec--)---------------------------><

Parameters

resultSpec
An object of data type DM_ClasResultSpec used to specify the results value to be calculated by the function DM_applyClasModel

Return value

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.

Related concepts

DM_setTreeNodeID

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.

Note:
This method is only valid for a Tree Classification model. Otherwise it is ignored.

Syntax

Method syntax

Read syntax diagramSkip visual syntax diagram>>-resultSpec..DM_setTreeNodeID--(--)--------------------------><

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_setTreeNodeID--(--resultSpec--)--------------------------><

Parameters

resultSpec
An object of data type DM_ClasResultSpec used to specify the results value to be calculated by the function DM_applyClasModel

Return value

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.

Note:
If the model is not a Tree Classification model, this method has no effect. The node ID is not written into the scoring result.

Related concepts

Functions and stored procedures reference

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:

  1. Import and export mining models, and access the properties of the models.
  2. Apply these models to data held in DB2 tables.
  3. Retrieve the results.

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.

DM_applData

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.

Syntax

Read syntax diagramSkip visual syntax diagramTwo-parameter notation

>>-DM_applData--(--label--,--+-character expression-+--)-------><
                             +-numeric expression---+
                             +-date expression------+
                             +-time expression------+
                             '-timestamp expression-'

Read syntax diagramSkip visual syntax diagramThree-parameter notation

>>-DM_applData--(--application data--,--label--,---------------->

>--+-character expression-+--)---------------------------------><
   +-numeric expression---+
   +-date expression------+
   +-time expression------+
   '-timestamp expression-'

Parameters

application data
Identifies application data of type DM_ApplicationData to which the label and value of the expression are appended before being returned. In nested calls, this parameter is the return value of a DM_applData call.
label
The label is a literal and must be defined within single quotation marks. The string enclosed within the quotation marks must be a precise match, including case, for the name of a field defined in the model you apply. Together with the character or numeric expression that follows, this forms the data to which a model is applied. It will be appended to the DM_ApplicationData value.

Label can have a maximum length of 128.

character expression
An expression that returns a value of type CHAR, VARCHAR, or LONG VARCHAR.
Note:
IM for Data handles date values and time values in character ISO format. If you want to specify a date value or a time value as input to DM_applData and you want to apply a model created by IM for Data, the date value and time value must be cast to character ISO format by using TO_CHAR(<value>,ISO) for a date value and TO_CHAR(<value>,JIS) for a time value.
numeric expression
An expression that returns a value that is a numeric data type, either INTEGER, DOUBLE, DECIMAL, FLOAT, BIGINT, or SMALLINT. For example, you can include an expression such as age + 10.
date expression
An expression that returns a value of type DATE
time expression
An expression that returns a value of type TIME
timestamp expression
An expression that returns a value of type TIMESTAMP

If multiple data items are to be included, multiple nested calls to DM_applData must be made.

Return value

The return value is a value of data type DM_ApplicationData.

Related concepts

Examples

An example is provided in:

DM_applyClasModel

This function applies a Classification model to selected data and produces results.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_applyClasModel--(--+-model--,--application data-+--------->
                         '-model name--,--data record-'

>--+----------------+--)---------------------------------------><
   '-,--result spec-'

Parameters

model
A model of type DM_ClasModel that is to be applied to data
application data
Specifies the data of type DM_ApplicationData to which the model is applied. A DM_ApplicationData value is returned by DM_applData or DM_impApplData. See DM_applData and DM_impApplData.
model name
A value of type VARCHAR(256):
  • In fenced mode, the model name is used as model alias to find the model in the cache. If no model was found in the cache, the function tries to locate the model in the corresponding default model table IDMMX_CLASSIFMODELS. If successful, the function reads the model as an unpinned model into the cache, using model name as model alias for the new cached model.
    Note:
    To store the model into the cache refer to DM_openModel.
  • In unfenced mode, the model is directly selected from the corresponding default model table and, if successful, applied to the data record.
data record
Specifies the application input data record of data type VARCHAR(32672) in the format returned by:
REC2XML(1.0, 'COLATTVAL', '', ...)
result spec
A value of type DM_ClasResultSpec()

Return value

The results produced by applying a model using DM_applyClasModel are returned as data type DM_ClasResult.

Usage notes

An error message is displayed, if:

Note:
If the model to be loaded from the default model table is already in the cache with no or a different alias, the apply is performed without caching the model.

Related concepts

DM_applyClusModel

This function applies a Clustering model to selected data and produces results.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_applyClusModel--(--+-model--,--application data-+--------->
                         '-model name--,--data record-'

>--+----------------+--)---------------------------------------><
   '-,--result spec-'

Parameters

model
A model of type DM_ClusteringModel that is to be applied to data
application data
Specifies the data of type DM_ApplicationData to which the model is applied. A DM_ApplicationData value is returned by DM_applData or DM_impApplData. See DM_applData and DM_impApplData.
model name
A value of type VARCHAR(256):
  • In fenced mode, the model name is used as model alias to find the model in the cache. If no model was found in the cache, the function tries to locate the model in the corresponding default model table IDMMX.CLUSTERMODELS. If successful, the function reads the model as an unpinned model into the cache, using model name as model alias for the new cached model.
    Note:
    To store the model into the cache refer to DM_openModel.
  • In unfenced mode, the model is directly selected from the corresponding default model table and, if successful, applied to the data record.
data record
Specifies the application input data record of data type VARCHAR(32672) in the format returned by:
REC2XML(1.0, 'COLATTVAL', '', ...)
result spec
A value of type DM_ClusResultSpec()

Return value

The results produced by applying a model using DM_applyClusModel are returned as data type DM_ClusResult.

Usage notes

An error message is displayed, if:

Note:
If the model to be loaded from the default model table is already in the cache with no or a different alias, the apply is performed without caching the model.

Related concepts

DM_applyRegModel

This function applies a Regression model to selected data and produces results.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_applyRegModel--(--+-model--,--application data-+--)------><
                        '-model name--,--data record-'

Parameters

model
A model of type DM_RegressionModel that is to be applied to data
application data
Specifies the data of type DM_ApplicationData to which the model is applied. A DM_ApplicationData value is returned by DM_applData or DM_impApplData. See DM_applData and DM_impApplData.
model name
A value of type VARCHAR(256):
  • In fenced mode, the model name is used as model alias to find the model in the cache. If no model was found in the cache, the function tries to locate the model in the corresponding default model table IDMMX.REGRESSIONMODELS. If successful, the function reads the model as an unpinned model into the cache, using model name as model alias for the new cached model.
    Note:
    To store the model into the cache refer to DM_openModel.
  • In unfenced mode, the model is directly selected from the corresponding default model table and, if successful, applied to the data record.
data record
Specifies the application input data record of data type VARCHAR(32672) in the format returned by:
REC2XML(1.0, 'COLATTVAL', '', ...)

Return value

The results produced by applying a model using DM_applyRegModel are returned as data type DM_RegResult.

Usage notes

An error message is displayed, if:

Note:
If the model to be loaded from the default model table is already in the cache with no or a different alias, the apply is performed without caching the model.

Related concepts

DM_closeAllModels

This stored procedure removes all models from the cache.

For more information refer to Using the model cache for real-time scoring.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_closeAllModels--(--removePinned--)-----------------------><

Parameters

removePinned
Has a value of type INTEGER:
0
Removes only the unpinned models
1
Removes all pinned and unpinned models

Usage notes

An error message is displayed, if the database has been enabled in unfenced mode. This is not supported for model caching.

Related concepts

Using the model cache for real-time scoring

Examples

Examples are provided in:

Another example is:

CALL IDMMX.DM_closeAllModels(1);

DM_closeModel

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.

Note:
When a model is removed from the cache, it is removed from the memory only if there are no more scoring runs using that model.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_closeModel--(--cachedModelID--)--------------------------><

Parameters

cachedModelID
A unique ID for the model to be removed, as returned by the function DM_openModel

Return value

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:

1
Indicates that a model with the passed ID was found in the cache.
0
Indicates that there is no model with the passed ID.

Usage notes

An error message is displayed, if the database has been enabled in unfenced mode, which is not supported for model caching.

Related concepts

Using the model cache for real-time scoring

Examples

Examples are provided in:

Another example is:

VALUES (IDMMX.DM_closeModel( <model ID> ));

DM_expClasModel

This function returns a character large object representing a PMML Classification model of type DM_ClasModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_expClasModel--(--classificationModel--)------------------><

Parameters

classificationModel
A value of type DM_ClasModel

Return value

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.

DM_expClusModel

This function returns a character large object representing the PMML Clustering model extracted from a value of type DM_ClusteringModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_expClusModel--(--clusteringModel--)----------------------><

Parameters

clusteringModel
A value of type DM_ClusteringModel

Return value

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.

DM_expRegModel

This function returns a character large object representing a PMML or XML Regression model of type DM_RegressionModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_expRegModel--(--regressionModel--)-----------------------><

Parameters

regressionModel
A value of type DM_RegressionModel

Return value

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.

Note:
XML Regression models created by IM Modeling are not fully PMML 2.1 compliant models. They use existing PMML 2.1 element names with several minor additions. These additions have been submitted to be part of the next PMML 3.0 standard.

DM_expRuleModel

This function returns a character large object representing an Associations model of type DM_RuleModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_expRuleModel--(--ruleModel--)----------------------------><

Parameters

ruleModel
A value of type DM_RuleModel

Return value

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.

DM_getClasCostRate

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClasCostRate--(--classificationModel--)---------------><

Parameters

classificationModel
A value of type DM_ClasModel

Return value

Related concepts

Extracting information from a model

DM_getClasMdlName

This function returns the name of a Classification model of type DM_ClasModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClasMdlName--(--classificationModel--)----------------><

Parameters

classificationModel
A Classification model of the type DM_ClasModel

Return value

The return value is the name of the Classification model as a VARCHAR value.

Related concepts

Extracting information from a model

DM_getClasMdlSpec

This function returns the DM_LogicalDataSpec value representing the set of fields needed for an application of the Classification model.

Note:
It is recommended that you use the DM_getFields function instead of this function as described in DM_getFields.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClasMdlSpec--(--classificationModel--)----------------><

Parameters

classificationModel
A value of type DM_ClasModel

Return value

The return value is the DM_LogicalDataSpec value representing the set of fields needed for an application of the Classification model.

Related concepts

Extracting information from a model

DM_getClasTarget

This function returns the name of the target field of a Classification model.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClasTarget--(--classificationModel--)-----------------><

Parameters

classificationModel
A value of type DM_ClasModel

Return value

The return value is the target field name as a VARCHAR value.

Related concepts

Extracting information from a model

Related references

DM_getFields

DM_getClusConf

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusConf--(--results value--)-------------------------><

Parameters

results value
The result of applying a Clustering model, returned by function DM_applyClusModel as data type DM_ClusResult

Return value

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.

Related concepts

Getting application results

DM_getClusMdlName

This function returns the name of a Clustering model of type DM_ClusteringModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusMdlName--(--clusteringModel--)--------------------><

Parameters

clusteringModel
A Clustering model of the type DM_ClusteringModel

Return value

The return value is the name of the Clustering model as a VARCHAR value.

Related concepts

Extracting information from a model

Examples

Extracting information from a model

DM_getClusMdlSpec

This function returns the DM_LogicalDataSpec value representing the set of fields needed for an application of the Clustering model.

Note:
It is recommended that you use the DM_getFields function instead of this function as described in DM_getFields.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusMdlSpec--(--clusteringModel--)--------------------><

Parameters

clusteringModel
A value of type DM_ClusteringModel

Return value

The return value is the DM_LogicalDataSpec value representing the set of fields needed for an application of the Clustering model.

Examples

Examples are provided in:

DM_getClusMdlType

This function obtains the type of a Clustering model of type DM_ClusteringModel as defined in PMML.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusMdlType--(--clusteringModel--)--------------------><

Parameters

clusteringModel
A value of type DM_ClusteringModel

Return value

The return value is the type of the Clustering model as a VARCHAR value. It can be center-based or distribution-based.

DM_getClusScore

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusScore--(--results value--)------------------------><

Parameters

results value
The result of applying a Clustering model, returned by function DM_applyClusModel as data type DM_ClusResult

Return value

Related concepts

Getting application results

Examples

Examples for real-time scoring

DM_getClusScore(clusterid)

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.

Note:
See also DM_getQuality(clusterid).

Syntax

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusScore--(--results value--,--clusterid--)----------><

Parameters

results value
The result of applying a Clustering model, returned by function DM_applyClusModel as data type DM_ClusResult
clusterid
A value of data type INTEGER between 1 and the result of function DM_getNumClusters called on the Clustering model

Return value

Related concepts

Getting application results

Examples

Examples for real-time scoring

DM_getClusterID

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusterID--(--results value--)------------------------><

Parameters

results value
The result of applying a Clustering model, returned by function DM_applyClusModel as data type DM_ClusResult

Return value

Related concepts

Getting application results

Examples

Examples are provided in:

DM_getClusterName

This function returns the name of a cluster at a specified position in a value of type DM_ClusteringModel.

Note:
It is recommended that you use the DM_getClusters function instead of a combination of this function together with DM_getClusterID and DM_getNumClusters.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusterName--(--clusteringModel--,--position--)-------><

Parameters

clusteringModel
A value of type DM_ClusteringModel
position
A value, of type INTEGER, between 1 and the result of DM_getNumClusters. Here you can specify the value obtained by a call to DM_getClusterID.

Return value

Related concepts

Extracting information from a model

DM_getClusters

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.

Note:
It is recommended that you use the DM_getClusters function instead of:

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getClusters--(--clusteringModel--)-----------------------><

Parameters

clusteringModel
A value of type DM_ClusteringModel

Return value

The result of invoking DM_getClusters is a table. Table 21 describes the data type and purpose of each column contained in this table.

Table 21. Result values for DM_getClusters
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:

For categorical fields
The field value whose relative frequency in the cluster mostly differs from the relative frequency in the background is used:
  • If the difference is above 0.25, the text is:

    "<field alias> is much more/less often <value> than average"

  • If the difference is above 0.1, the text is:

    "<field alias> is more/less often <value> than average"

  • The relative frequencies in the cluster are preferred to the relative frequencies in the background.
  • Otherwise, no text is displayed for this field.
For numerical fields
The difference of the mean value between the cluster and the background is considered:
  • If the difference is above 1 time the standard deviation of the background, the text is:

    "<field alias> is much larger/smaller than average"

  • If the difference is above 0.5 time the standard deviation of the background, the text is:

    "<field alias> is larger/smaller than average"

  • If the difference is under 0.5 time the standard deviation of the background and the standard deviation in the cluster itself is larger/smaller than 50%, the text is:

    "<field alias> has a larger/smaller variance than input data"

  • Otherwise, no text is displayed for this field.
Note:
If no text is displayed for the five most important fields, the text is: "This cluster is overall similar to input data".

Table 22 shows an example for the table returned by DM_getClusters:

Table 22. Sample 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

Related concepts

Extracting information from a model

Examples

Extracting information from a model

DM_getConfidence

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getConfidence--(--results value--)-----------------------><

Parameters

results value
The result of applying a Classification model, returned by the function DM_applyClasModel as data type DM_ClasResult

Return value

Related concepts

Getting application results

DM_getConfidence(class)

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getConfidence--(--results value--,--class--)-------------><

Parameters

results value
The result of applying a Classification model, returned by the function DM_applyClasModel as data type DM_ClasResult
class
A value of data type VARCHAR that is a valid value of the predicted field in the Classification model

Return value

Related concepts

Getting application results

DM_getConfidence(low, up)

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.

Note:
Only Transform Regression models contain this information. For all other Regression models, function DM_getConfidence(low, up) always returns NULL.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getConfidence--(--results value--,--low--,--up--)--------><

Parameters

results value
The result of applying a Regression model, returned by the function DM_applyRegModel as data type DM_RegResult
low
The lower limit of the interval as data type DOUBLE
up
The upper limit of the interval as data type DOUBLE

Return value

Related concepts

Getting application results

DM_getEnv

This procedure lists all the environment variables in the running agent process that have the IDM_ prefix.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getEnv--(--list--)---------------------------------------><

Parameters

list
The OUT parameter, of type VARCHAR

Return value

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.

Notes:
  1. DM_setEnv and DM_getEnv are intended to set environment variables in the DB2 db2fmp process. The database must have been enabled in fenced mode. For more information refer to The idmenabledb command. If the database was enabled in unfenced mode, calling these procedures may not have the intended effect.
  2. The database manager configuration variable keepfenced (DB2 V8) must be set to the default value yes.

Examples

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.

Note:
If you have installed IM for Data, you see some variables of IM for Data, however, these are not relevant for IM Scoring or IM Modeling.

DM_getErrors(rowcount)

This table function retrieves complete error messages.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getErrors--(--rowcount--)--------------------------------><

Parameters

rowcount
Returns a table containing the last rowcount error messages in the IM Scoring or IM Modeling error file.

If rowcount is NULL, all error messages are returned.

Return value

The result of invoking DM_getErrors is a table. Table 23 describes the data type and purpose of each column contained in this table.

Table 23. Result values for DM_getErrors
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)
E
for error
W
for warning
I
for information
S
for severe error
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

Related concepts

Getting error information

Examples

An example is:

SELECT * FROM TABLE (IDMMX.DM_GETERRORS(5)) AS ERRORS

DM_getFields

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:

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getFields--(--+-classificationModel-+--)-----------------><
                    +-clusteringModel-----+
                    +-regressionModel-----+
                    '-ruleModel-----------'

Parameters

classificationModel
A value of type DM_ClasModel
clusteringModel
A value of type DM_ClusteringModel
regressionModel
A value of type DM_RegressionModel
ruleModel
A value of type DM_RuleModel

Return value

The result of invoking DM_getFields is a table. Table 24 describes the data type and purpose of each column contained in this table.

Table 24. Result values for DM_getFields
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.

Table 25. Sample table returned by DM_getFields
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
Note:
For supervised models (classification or regression) the target field is not contained in the table. It can be retrieved using DM_getClasTarget or DM_getRegTarget.

Related concepts

Extracting information from a model

Examples

Extracting information from a model

DM_getNumClusters

This function returns the number of clusters contained in a value of type DM_ClusteringModel.

Note:
It is recommended that you use the DM_getClusters function instead of a combination of this function together with DM_getClusterID and DM_getClusterName.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getNumClusters--(--clusteringModel--)--------------------><

Parameters

clusteringModel
A value of type DM_ClusteringModel

Return value

Related concepts

Extracting information from a model

Examples

Extracting information from a model

DM_getNumRules

This function returns the number of rules contained in a value of type DM_RuleModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getNumRules--(--ruleModel--)-----------------------------><

Parameters

ruleModel
A value of type DM_RuleModel

Return value

Related concepts

Extracting information from a model

DM_getNumTransacts

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getNumTransacts--(--ruleModel--)-------------------------><

Parameters

ruleModel
A value of type DM_RuleModel

Return value

The result of invoking DM_getNumTransacts is an INTEGER specifying the number of transactions contained in the dataset used to build ruleModel.

Related concepts

Extracting information from a model

Examples

Examples are provided in:

DM_getOpenModels

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getOpenModels--(--)--------------------------------------><

Return value

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
1
Indicates that the model is pinned into the cache.
0
Indicates that the model is unpinned.
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.

Usage notes

An error message is displayed, if the database has been enabled in unfenced mode, which is not supported for model caching.

Related concepts

Using the model cache for real-time scoring

Examples

Examples are provided in:

Another example is:

SELECT CT.* FROM TABLE(IDMMX.DM_getOpenModels()) CT

DM_getPredClass

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getPredClass--(--results value--)------------------------><

Parameters

results value
The result of applying a Classification model, returned by the function DM_applyClasModel as data type DM_ClasResult

Return value

Related concepts

Getting application results

DM_getPredDev(prob)

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.

Notes:
  1. Only Transform Regression models contain this information. For all other Regression models, function DM_getPredDev always returns NULL.
  2. The functions DM_getPredDev and DM_getPredStdDev are related as follows: DM_getPredDev(value,0.683) equals DM_getPredStdDev(value) because the standard deviation is the half width of the interval in which the predicted value lies with a probability of 0.683.

Syntax

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getPredDev--(--results value--,--prob--)-----------------><

Parameters

results value
The result of applying a Regression model, returned by the function DM_applyRegModel as data type DM_RegResult
prob
A probability value between 0 and 1 (not inclusive) as data type DOUBLE

Return value

Related concepts

Getting application results

DM_getPredStdDev

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.

Notes:
  1. Only Transform Regression models contain this information. For all other Regression models, function DM_getPredStdDev always returns NULL.
  2. The functions DM_getPredStdDev and DM_getPredDev are related as follows: DM_getPredDev(value,0.683) equals DM_getPredStdDev(value) because the standard deviation is the half width of the interval in which the predicted value lies with a probability of 0.683.
  3. DM_getPredStdDev is similar to DM_getPredValue, but it returns the estimated standard deviation for a predicted value (as it is estimated by the Transform Regression kernel).

Syntax

Function syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getPredStdDev--(--results value--)-----------------------><

Parameters

results value
The result of applying a Regression model, returned by the function DM_applyRegModel as data type DM_RegResult

Return value

Related concepts

Getting application results

DM_getPredValue

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getPredValue--(--results value--)------------------------><

Parameters

results value
The result of applying a Regression model, returned by the function DM_applyRegModel as data type DM_RegResult

Return value

Related concepts

Getting application results

DM_getQuality

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getQuality--(--results value--)--------------------------><

Parameters

results value
The result of applying a Clustering model, returned by the function DM_applyClusModel as data type DM_ClusResult

Return value

Related concepts

Getting application results

Examples

Getting application results

DM_getQuality(clusterid)

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getQuality--(--results value--,--clusterid--)------------><

Parameters

results value
The result of applying a Clustering model, returned by the function DM_applyClusModel as data type DM_ClusResult
clusterid
A value of data type INTEGER between 1 and the result of function DM_getNumClusters called on the Clustering model

Return value

Related concepts

Getting application results

Examples

Examples are provided in:

DM_getRBFRegionID

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getRBFRegionID--(--results value--)----------------------><

Parameters

results value
The results of applying an RBF Regression model returned by the function DM_applyRegModel as data type DM_RegResult

Return value

Related concepts

Getting application results

DM_getRegMdlName

This function returns the name of a Regression model of type DM_RegressionModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getRegMdlName--(--regressionModel--)---------------------><

Parameters

regressionModel
A Regression model of the type DM_RegressionModel

Return value

The return value is the name of the Regression model as a VARCHAR value.

Related concepts

Extracting information from a model

DM_getRegMdlSpec

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.

Note:
It is recommended that you use the DM_getFields function instead of this function as described in DM_getFields.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getRegMdlSpec--(--regressionModel--)---------------------><

Parameters

regressionModel
A value of type DM_RegressionModel

Return value

The return value is the DM_LogicalDataSpec value representing the set of fields needed for an application of the Regression model.

DM_getRegTarget

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getRegTarget--(--regressionModel--)----------------------><

Parameters

regressionModel
A value of type DM_RegressionModel

Return value

The target field name is returned as a value of type VARCHAR.

Related concepts

Extracting information from a model

DM_getRegRSquared

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.

Note:
r2=0 means that the prediction error and the target field values are uncorrelated, r2=1 means that the two values are perfectly (positively or negatively) correlated.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getRegRSquared--(--regressionModel--)--------------------><

Parameters

regressionModel
A value of type DM_RegressionModel

Return value

DM_getRuleBodies

This function returns a table containing the bodies of rules in a value of type DM_RuleModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getRuleBodies--(--ruleModel--)---------------------------><

Parameters

ruleModel
A value of type DM_RuleModel

Return value

The result of invoking DM_getRuleBodies is a table. Table 26 describes the data type and purpose of each column contained in this table.

Table 26. Result values for DM_getRuleBodies
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

Related concepts

Extracting information from a model

Examples

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.

Table 27. Sample table returned by DM_getRuleBodies
BODYID ITEMNAME ITEM
17 2576901 shoes
17 1288737 coat
17 1298130 hat

This example is related to the example shown in DM_getRules.

Note:
If any of the character values for items or item names in ruleModel is longer than 1024 characters, this value is truncated to 1021, and three dot characters (...) are added at the end.

DM_getRuleMdlName

This function returns the name of an Associations model of type DM_RuleModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getRuleMdlName--(--ruleModel--)--------------------------><

Parameters

ruleModel
An Associations model of type DM_RuleModel

Return value

The return value is the name of the Associations model as a VARCHAR value.

Related concepts

Extracting information from a model

DM_getRules

This function returns a table containing the rules in a value of type DM_RuleModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getRules--(--ruleModel--)--------------------------------><

Parameters

ruleModel
A value of type DM_RuleModel

Return value

The result of invoking DM_getRules is a table. Table 28 describes the data type and purpose of each column contained in this table.

Table 28. Result values for DM_getRules
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.

Notes:
  1. There is a row in the result table for each rule in model whose head consists of exactly one item. For these rules, the length (total number of items), as well as the support, confidence, and lift values, are available in the appropriate columns.
  2. For each complex rule (that is, a rule with more than one head item), there is one table entry per head item representing a simple derived rule with the same body but only one of the head items. In this case, the length is provided, but support, confidence, and lift have NULL values. All entries derived from the same complex rule will have the same rule ID.
  3. Most association algorithms do not generate rules with more than one head item. In particular the algorithm in DB2 IM Modeling and DB2 IM for Data do not generate complex rules.

Related concepts

Extracting information from a model

Examples

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.

Table 29. Sample table returned by DM_getRules
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.

Note:
If any of the character values in ruleModel is larger than the number of characters allowed (1024 for head items and 4096 for the body text), this value will be truncated to the allowed length -3, and three dot characters (...) will be added at the end.

DM_getTreeNodeID

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getTreeNodeID--(----results value----)-------------------><

Parameters

results value
The result of applying a Tree Classification model, returned by the function DM_applyClasModel as data type DM_ClasResult

Return value

Related concepts

Getting application results

DM_getTreeRules

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_getTreeRules--(----classificationModel----)--------------><

Parameters

classificationModel
A value of type DM_ClasModel

Return value

Examples

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.

Table 31. Sample table returned by DM_getTreeRules
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

Related concepts

Extracting information from a model

DM_impApplData

This function converts a data record of type CLOB, CHAR, or VARCHAR into type DM_ApplicationData.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impApplData--(----data record as string----)-------------><

Parameters

data record as string
Is a value of CLOB, CHAR, or VARCHAR.

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.

Return value

Related concepts

Examples

Examples are provided in:

DM_impClasFile

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impClasFile--(--input file name--)-----------------------><

Parameters

input file name
The name and full path of the file to be imported. The specified file must:
  • Exist on the database server and the DB2 instance owner (unfenced) or DB2 fenced user (fenced) must have read access to the file.
  • Have a supported format, for more information refer to Importing mining models.

Return value

The return value is the imported model as data type DM_ClasModel.

Related concepts

Importing mining models

Usage

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.

DM_impClasFileE

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impClasFileE--(--input file name--,--encoding name--)----><

Parameters

input file name
The name and full path of the file to be imported. The specified file must:
  • Exist on the database server and the DB2 instance owner (unfenced) or DB2 fenced user (fenced) must have read access to the file.
  • Have a supported format, for more information refer to Importing mining models.
encoding name

IM Scoring supports different encoding names. The MIME encoding strings are recommended, for example, iso-8859-1.

  • If the encoding name is a non-empty string, the value is interpreted as an XML encoding. The content of the imported file is parsed according to this encoding. The imported file must be a PMML document.
  • If the encoding name is the string 'SYSTEM', the locale settings of the operating system are used to determine the encoding of the file.
  • If the encoding name is NULL, the encoding is determined by the imported file.

    • If the file is a PMML document, the standard rules of the XML specification apply. That is, the encoding is either given explicitly or assumed to be Unicode by default.
    • If the imported file is written in Intelligent Miner format, the locale settings of the operating system are used.

Usage

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.

Return value

The return value is the imported model as data type DM_ClasModel.

Related concepts

Importing mining models

Examples

DM_impClasFile

DM_impClasModel

This function converts the Classification model given as CLOB into a Classification model of type DM_ClasModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impClasModel--(--model_as_CLOB--)------------------------><

Parameters

model_as_CLOB
A Classification model in PMML format as a CLOB value. The model is assumed to be provided in database encoding (the code set specified when the database was created), regardless of the XML encoding specification contained in the model.

Return value

The return value is a Classification model of type DM_ClasModel. If model_as_CLOB is NULL, the return value is NULL.

Related concepts

Importing mining models

DM_impClusFile

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impClusFile--(--input file name--)-----------------------><

Parameters

input file name
The name and full path of the file to be imported. The specified file must:
  • Exist on the database server and the DB2 instance owner (unfenced) or DB2 fenced user (fenced) must have read access to the file.
  • Have a supported format, for more information refer to Importing mining models.

Return value

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.

Usage

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.

Related concepts

Importing mining models

Examples

Examples are provided in:

DM_impClusFileE

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impClusFileE--(--input file name--,--encoding name--)----><

Parameters

input file name
The name and full path of the file to be imported. The specified file must:
  • Exist on the database server and the DB2 instance owner (unfenced) or DB2 fenced user (fenced) must have read access to the file.
  • Have a supported format, for more information refer to Importing mining models.
encoding name

IM Scoring supports different encoding names. The MIME encoding strings are recommended, for example, iso-8859-1.

  • If the encoding name is a non-empty string, the value is interpreted as an XML encoding. The content of the imported file is parsed according to this encoding. The imported file must be a PMML document.
  • If the encoding name is the string 'SYSTEM', the locale settings of the operating system are used to determine the encoding of the file.
  • If the encoding name is NULL, the encoding is determined by the imported file.

    • If the file is a PMML document, the standard rules of the XML specification apply. That is, the encoding is either specified explicitly or assumed to be Unicode by default.
    • If the imported file is written in Intelligent Miner format, the locale settings of the operating system are used.

Return value

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.

Usage

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.

Related concepts

Importing mining models

Examples

Examples are provided in:

DM_impClusModel

This function converts a Clustering model given as a CLOB value into a Clustering model of type DM_ClusteringModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impClusModel--(--model_as_CLOB--)------------------------><

Parameters

model_as_CLOB
A Clustering model in PMML format as a CLOB value. The model is assumed to be provided in database encoding (the code set specified when the database was created), regardless of the XML encoding specification contained in the model.

Return value

The return value is a Clustering model of type DM_ClusteringModel. If model_as_CLOB is NULL, the return value is NULL.

Related concepts

Importing mining models

Examples

Importing mining models from a CLOB value in a database table

DM_impRegFile

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impRegFile--(--input file name--)------------------------><

Parameters

input file name
The name and full path of the file to be imported. The specified file must:
  • Exist on the database server and the DB2 instance owner (unfenced) or DB2 fenced user (fenced) must have read access to the file.
  • Have a supported format, for more information refer to Importing mining models.

Return value

The return value is the imported model as data type DM_RegressionModel.

Related concepts

Importing mining models

Usage

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.

DM_impRegFileE

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impRegFileE--(--input file name--,--encoding name--)-----><

Parameters

input file name
The name and full path of the file to be imported. The specified file must:
  • Exist on the database server and the DB2 instance owner (unfenced) or DB2 fenced user (fenced) must have read access to the file.
  • Have a supported format, for more information refer to Importing mining models.
encoding name

IM Scoring supports different encoding names. The MIME encoding strings are recommended, for example, iso-8859-1.

  • If the encoding name is a non-empty string, the value is interpreted as an XML encoding. The content of the imported file is parsed according to this encoding. The imported file must be a PMML document.
  • If the encoding name is the string 'SYSTEM', the locale settings of the operating system are used to determine the encoding of the file.
  • If the encoding name is NULL, the encoding is determined by the imported file.

    • If the file is a PMML document, the standard rules of the XML specification apply. That is, the encoding is either specified explicitly or assumed to be Unicode by default.
    • If the imported file is written in Intelligent Miner format, the locale settings of the operating system are used.

Return value

The return value is the imported model as data type DM_RegressionModel.

Usage

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.

Related concepts

Importing mining models

Examples

DM_impRegFile

DM_impRegModel

This function converts a Regression model given as CLOB into a Regression model of type DM_RegressionModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impRegModel--(--model_as_CLOB--)-------------------------><

Parameters

model_as_CLOB
A Regression model in PMML format as a CLOB value. The model is assumed to be provided in database encoding (the code set specified when the database was created), regardless of the XML encoding specification contained in the model.

Return value

The return value is a Regression model of type DM_RegressionModel. If model_as_CLOB is NULL, the return value is NULL.

Related concepts

Importing mining models

DM_impRuleFile

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impRuleFile--(--input file name--)-----------------------><

Parameters

input file name
The name and full path of the file to be imported. The specified file must exist on the database server.

Return value

The return value is the imported model as data type DM_RuleModel.

Related concepts

Importing mining models

Examples

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.

DM_impRuleFileE

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impRuleFileE--(--input file name--,--encoding name--)----><

Parameters

input file name
The name and full path of the file to be imported. The specified file must exist on the database server.
encoding name

IM Scoring supports different encoding names. The MIME encoding strings are recommended, for example, iso-8859-1.

  • If the encoding name is a non-empty string, the value is interpreted as an XML encoding. The content of the imported file is parsed with respect to this encoding. The imported file must be a PMML document.
  • If the encoding name is an empty string, the locale settings of the operating system are used to determine the encoding of the file.
  • If the encoding name is NULL, the encoding is determined by the imported file.

    • If the file is a PMML document, the standard rules of the XML specification apply. That is, the encoding is either specified explicitly or it is assumed to be Unicode by default.
    • If the imported file is written in Intelligent Miner format, the locale settings of the operating system are used.

Return value

The return value is the imported model as data type DM_RuleModel.

Related concepts

Importing mining models

Examples

Examples are provided in:

DM_impRuleModel

This function converts an association rules model given as CLOB into an association model of type DM_RuleModel.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_impRuleModel--(--model_as_CLOB--)------------------------><

Parameters

model_as_CLOB
An association rules model in PMML format as CLOB value

Return value

The return value is an association rules model of type DM_RuleModel. If model_as_CLOB is NULL, the return value is NULL.

Related concepts

Importing mining models

Examples

The idmenabledb command

DM_openModel

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_openModel--(--model--,--model alias--)-------------------><

Parameters

model
A value of type DM_ClusteringModel, DM_ClasModel, or DM_RegressionModel that contains the model.
Note:
There are overloaded DM_openModel functions for these different data types.
model alias
A unique, user-specified model name with a value of type VARCHAR(256).
Notes:
  1. If the parameter is NULL, the model does not get an alias.
  2. Each database instance has its own cache. The model name you specify in DM_openModel(model alias) must be unique within this database instance.

    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:

    • The same alias several times within a database instance, the system automatically determines which copy of the model to use for the next apply operation.
    • Different alias names the system expects the models to be different. You must then manually decide which alias to use.
  3. The model alias identifies the model in the apply UDFs if the model name is passed as VARCHAR in the first parameter: DM_applyClusModel, DM_applyClasModel, or DM_applyRegModel.
  4. The model alias provided can be different from the PMML (internal) model name of a model. PMML model names of implicitly cached models do not cause a conflict when the same name is reused for the DM_openModel(model, model alias) call.
  5. To avoid a name conflict with model aliases used in other databases of the instance, it is recommended to use a prefix in the model alias, such as:
    <schema name>.<alias>
    where schema name is the value returned by the SQL special register CURRENT SCHEMA.

Return value

The function:

Notes:
  1. The model is pinned which means that the model can only be removed from the cache explicitly using DM_closeModel or DM_closeAllModels.
  2. The model is inserted into the cache even if the cache is at or beyond its maximum size. The insertion does not depend on the cache size specified by IDM_MX_MAX_OPEN_MODELS.
  3. The maximum size will only be ignored if it is not possible to gain cache by removing one of the existing (unpinned) models.
  4. If the function DM_openModel is called several times, and the same model is used on each invocation, several instances of the same model are inserted into the cache (the model alias can be the same, but need not be the same).
  5. With DM_openModel you can add several instances of the model into the cache. Adding a model more than once to the cache can improve performance in an environment with many concurrent scoring users and multiple processors.

Usage notes

An error message is displayed, if:

Related concepts

Using the model cache for real-time scoring

Examples

Examples are provided in:

Another example is:

SELECT IDMMX.DM_openModel(MODEL, MODELNAME)
  FROM IDMMX.CLUSTERMODELS WHERE MODELNAME = 'DemoBanking';

DM_setEnv

This procedure sets environment variables that are used by IM Scoring and IM Modeling in the running agent process. For IM Scoring it sets the model cache size.

Syntax

Read syntax diagramSkip visual syntax diagram>>-DM_setEnv--(--variable--,--value--)-------------------------><

Parameters

variable
The name of the variable to be defined, of type VARCHAR. In IM Scoring use IDM_MX_MAX_OPEN_MODELS to set the model cache size.
value
The value of the variable (for example, an absolute path name), of type VARCHAR

Return value

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.

Notes:
  1. DM_setEnv and DM_getEnv are intended to set environment variables in the DB2 db2fmp process. The database must have been enabled in fenced mode. For more information refer to The idmenabledb command. If the database was enabled in unfenced mode, calling these procedures may not have the intended effect.
  2. The database manager configuration variable keepfenced (DB2 V8) must be set to the default value yes.

Examples

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');

Command reference

This chapter contains full descriptions of the commands provided with IM Scoring. Use these commands to:

You can find these commands in the bin directory of your IM Scoring installation.

The idmcheckdb command

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:

Syntax

Read syntax diagramSkip visual syntax diagram>>-idmcheckdb--dbname--+-------------+--+-------------------------------+-><
                       '-show detail-'  '-user--userID--using--password-'

Parameters

dbname
The name of the database that you want to check
show detail
If specified, a detailed report about all mining objects is shown. This list includes mining distinct and structured types, tables, indexes, user defined functions, user defined methods, and stored procedures.
user userid using password
The user ID for the database on the remote system and the appropriate password. If specified, you can check a cataloged database on a remote system. All mining specific types, tables, indexes, methods, functions, and stored procedures are listed.
Note:
You can check a remote database by specifying userid and password, however, the idmcheckdb command is only available on a database client if IM Modeling or IM Scoring is installed on the database client.

Return value

The idmcheckdb utility returns the following messages:

Table 32. The idmcheckdb 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.

Related concepts

Checking databases

Examples

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
Note:
This example only works if IM Scoring or IM Modeling is installed on the client machine.

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

The idmdisabledb command disables a database. It deletes the following mining objects from a specified database:

Syntax

Read syntax diagramSkip visual syntax diagram>>-idmdisabledb--dbname--+--------+----------------------------><
                         '-tables-'

Parameters

dbname
The name of the database that you want to disable
tables
If specified, the sample tables containing models are deleted.
Notes:
  1. Use the tables parameter with caution. Before you delete the sample tables, consider that you will also delete the models contained in these tables.
  2. If the sample tables are empty, they are deleted regardless whether the tables option is specified or not.
  3. If the sample tables are not empty, idmdisabledb asks the user whether to delete the sample tables.

Related concepts

Disabling databases

Examples

Examples are provided in:

The idmenabledb command

The idmenabledb command enable a database. It creates new database objects in the database and changes existing database objects if required.

Note:
You need not disable existing databases before using the idmenabledb command. However, the fenced or unfenced option must be the same as before, you can use idmcheckdb to check the existing database before enabling it again.

This command is shared between IM Modeling and IM Scoring. It detects which:

Syntax

Read syntax diagramSkip visual syntax diagram>>-idmenabledb--dbname--+----------+--+---------+--------------->
                        +-fenced---+  +-dbcfg---+
                        '-unfenced-'  '-nodbcfg-'

>--+------------------+--+------------------+------------------->
   '-ClasModelSize--n-'  '-RuleModelSize--n-'

>--+------------------+--+-----------------+-------------------->
   '-ClusModelSize--n-'  '-RegModelSize--n-'

>--+---------------+--+-----------------+--+---------------+---->
   '-StructSize--n-'  '-ApplDataSize--n-'  '-ResultSize--n-'

>--+-----------------------------+-----------------------------><
   '-Tablespace--tablespace-name-'

Parameters

dbname
Specifies the name of the database that you want to enable. This parameter is mandatory.
fenced
Specifies if the database is in fenced mode. Functions and methods are run in their own process. This is the default option.
unfenced
Specifies if the database is in unfenced mode. Functions and methods are run in the database process.
dbcfg or nodbcfg
If not specified, the user is prompted whether to change the database configuration.

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.

ClasModelSize, RuleModelSize, ClusModelSize, RegModelSize n
Specify the:
  • BLOB size of the distinct types DM_ClasModel, DM_RuleModel, DM_ClusteringModel, and DM_RegressionModel for mining results.
  • CLOB parameter size of the associated import and export model functions.
Notes:
  1. When you have created database objects (for example, tables) using these types, you can no longer change the size of the types without dropping these database objects. It is recommended that you work with default sizes in a test environment and that you carefully consider the parameter sizes before moving to a production environment.

    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.

  2. The default values are 10 MB in fenced mode and 50 MB in unfenced mode.
    Note:
    In IM Scoring 7.1, the default for the BLOB model was 100 MB; the default for the CLOB model to be imported was 50 MB. The BLOB model in IM Scoring 8.2 is compressed. For this reason, the default for the CLOB and BLOB models is the same (50 MB for unfenced and 10 MB for fenced).
StructSize n
Specifies the CLOB size of structured type DM_LogicalDataSpec in megabytes. The default is 512 KB.
ApplDataSize n
Specifies the CLOB size of the data records for the distinct type DM_ApplicationData in megabytes. The default is 500 KB.
ResultSize n
Specifies the VARCHAR size for scoring results of the distinct types DM_ClasResult, DM_ClusResult, and DM_RegResult, and of the structured types DM_ClasResultSpec and DM_ClusResultSpec.

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.

Tablespace tablespace-name
Specifies the table space to be used for the tables created by idmenabledb. If you do not specify this option, the mining tables are created in the default user tablespace selected by DB2.

Usage notes

Note:
Functions and methods are created as DETERMINISTIC NO EXTERNAL ACTION.

Related concepts

Enabling databases

Examples

An example is:

idmenabledb testdb fenced ClasModelSize 5 RuleModelSize 7 RegModelSize 9 

where:

Note:
DM_RuleModel is a type introduced by IM Modeling. DM_RuleModel is not used by IM Scoring, but is mentioned here because idmenabledb is a shared command between IM Scoring and IM Modeling.

More examples are provided in:

The idminstfunc command

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.

Notes:
  1. This command must be called only on UNIX platforms. It can be called only by a user with SYSADM authority.
  2. If you invoke the idminstfunc script, the DB2INSTANCE environment variable depicts to which DB2 instance the changes will be applied.
  3. Each DB2 instance can only be used with one product version. The DB2 instance is associated with a product version when performing the instance configuration (idminstfunc).

Syntax

Read syntax diagramSkip visual syntax diagram>>-idminstfunc-------------------------------------------------><

Usage notes

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.

Related concepts

Refer to DB2 Intelligent Miner Modeling, DB2 Intelligent Miner Scoring, DB2 Intelligent Miner Visualization: Installing the Intelligent Miner products.

Examples

Examples are provided in:

The idmuninstfunc command

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-idmuninstfunc-----------------------------------------------><

Usage notes

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.

The idmlevel command

Use the command idmlevel to collect information about the software environment (operating system, DB2 version) and IM product version you are using.

Syntax

Read syntax diagramSkip visual syntax diagram>>-idmlevel--+---------+---------------------------------------><
             '-logfile-'

Parameters

logfile
Specifies the path and name of the file into which the result of the idmlevel command is written. If you do not specify a log file, the result is displayed on the screen. This parameter is optional.

Related concepts

Getting product information

Examples

More examples are provided in:

The idmlicm command

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.

Syntax

Read syntax diagramSkip visual syntax diagram>>-idmlicm-----------------------------------------------------><

Related concepts

Getting product information

Examples

The idmlicm command is located in the bin directory. It has no parameters. When invoked, idmlicm checks the license status.

Sample output with production license
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.

Sample output with temporary license
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:

Sample output with temporary license already installed
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 idmmkSQL command

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.

Note:
idmmkSQL can read the PMML model from the file system or from a DB2 table.

Syntax

The syntax can be as follows:

Parameters

options
Specifies the following options.
Note:
You can start with a slash (/) or a hyphen (-).
-M
Identifies the method used to build input records. The option must be followed by one of the following values (not case-sensitive):
-O
Identifies the method used to build the SQL script.
TABLE
Permanently stores scoring results in a table. This is the default.
VIEW
Compute scoring results dynamically.
-D
Determines whether DB2 SQL or Oracle SQL is written. The option must be followed by one of the following values, which are not case-sensitive:
  • DB2 (the default value)
  • ORACLE
-E
Determines the encoding of the PMML file and SQL script. The option must be followed by a valid encoding string:
  • If this option is not given, the encoding string contained in the PMML file is used.
  • If the file does not contain encoding information, utf-8 is the default encoding.
Note:
For models in the database this option is ignored.
-H
Displays help information.
dboptions
Specifies the following:
-dbn[ame]
DB2 database name (required).
-dbu[serid]
User ID for DB2 database (optional).
-dbp[assword]
Password for DB2 database (optional).
-dbt[ablename]
Table name that contains the model (required).
-dbk[eycol]
Column that contains the model name (optional). The default value is 'MODELNAME'.
-dbd[atacol]
Column that contains the model (optional). The default value is 'MODEL'.
inputfile
Specifies the file that contains the PMML model.
modelname
Specifies the name of the PMML model.
outputfile
Specifies the file to which the SQL template is written. If no outputfile is given, the template is written to standard output.

Usage notes

Placeholders
The placeholders are marked with leading and trailing ### signs, for example, ###TABLENAME###. Replace these placeholders with appropriate (correct) values.
Note:
To generate the SQL script by using idmmkSQL, you need the model as a PMML file or in a DB2 database.
###ABSOLUTE_PATH###
The absolute path to the PMML file. The function that imports the PMML model needs the absolute path name of the file.
###RECORDID###
The table containing the input data records for the scoring run is expected to have a column to identify different records. Replace ###RECORDID### with the name of the column.
###INTEGER###
Replace ###INTEGER### with the data type of the previously specified ID column.
###TABLENAME###
The name of the table containing your input data records.

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:

IDMMX.CLUSTERMODELS, IDMMX.CLASSIFMODELS, IDMMX.REGRESSIONMODELS
Replace these strings by specifying the name of the table in which your mining models are to be stored.
MODEL
The name of the column in the model table containing the model itself. In the sample tables, this name is MODEL.
MODELNAME
The name of the column in the model table containing the model name. In the sample tables, this name is MODELNAME.

Related concepts

Generating SQL statements from models

Examples

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:

The idmxmod command

You can convert a model outside IM for Data from Intelligent Miner format to PMML 2.1 format by using the idmxmod command.

Syntax

Read syntax diagramSkip visual syntax diagram>>-idmxmod--in file name--out file name------------------------><

Parameters

in file name
The name of a file containing a model in Intelligent Miner format
out file name
The name of the file containing the converted PMML model

Related concepts

Converting exported models

Examples

Importing models in unfenced mode

Administration

Getting error information
Getting support
Problem identification worksheet
Getting product information
Getting trace information
Tracing errors
Getting DB2 diagnostic information
Migrating from IM Scoring V7.1
Working with IM Scoring V7.1 and V8.2 in parallel
Migrating from DB2 Version 7
Exporting and importing models with the use of compression
Exporting and importing models by means of DB2 Utilities
Importing models in unfenced mode
Applying Neural models
Using the function DM_getClusterID
Migrating from IM Scoring Version 8.1
Migrating a DB2 instance (UNIX only)
Migrating databases (all platforms)
Database instance restart

Getting error information

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).

Note:
This table function enables you to view the error list on another computer that uses a remote control software.

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.

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.

Getting support

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.

Problem identification worksheet

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.____________________

____________________________________________________________________________

____________________________________________________________________________

____________________________________________________________________________
 

Getting product information

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.

Note:
Attach the resulting log file to your problem description when you contact IBM support.

Getting trace information

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.

Tracing errors

Use the DM_setEnv method to trace errors:

  1. Start tracing:
    execute IDMMX.DM_setEnv('IDM_MX_TRACELEVEL','ALL') 
  2. Run the function in error.
  3. Reset tracing:
    execute IDMMX.DM_setEnv('IDM_MX_TRACELEVEL','')
  4. Send the trace file to your IBM support team.
Notes:
  1. You can set the environment variable as described in Getting error information.
  2. For more information refer to DM_setEnv and Setting environment variables.

Getting DB2 diagnostic information

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.

Migrating from IM Scoring V7.1

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:

  1. Installing IM Scoring V8.2
  2. Performing the configuration steps
  3. Re-enabling your databases or enabling new databases
    Note:
    You need not disable your databases before you re-enable them.

Working with IM Scoring V7.1 and V8.2 in parallel

Windows platform:
You cannot work with both versions on one machine on the Windows platform. If you install IM Scoring V8.2 on a Windows machine and the installation finds IM Scoring V7.1, IM Scoring V7.1 is automatically uninstalled.
UNIX platforms:
IM Scoring V8.2 installs into a directory that is different from the one used for IM Scoring V7.1. This means that you can have both versions installed on one machine. However, it is recommended that you migrate to IM Scoring V8.2, because there is a high risk of user error if you use both versions.

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.

Migrating from DB2 Version 7

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.

Exporting and importing models with the use of compression

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:

Note:
In IM Scoring V7.1 the default size is 100 MB for the 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:

  1. Connect to the database.
  2. Call the following:
    db2 -tf compressV7Models.db2

Exporting and importing models by means of DB2 Utilities

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:

  1. Export the models by means of the DB2 export command.
  2. Disable your database.
  3. Enable your database again.
  4. Import all the models by means of the DB2 import command.

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:

  1. Connect to the database.
  2. Call the following:
     
    db2 -tf db2ExportModels.db2 
    idmdisabledb dbname  
    idmenabledb dbname  [fenced|unfenced]
    db2 -tf db2ImportModels.db2

Importing models in unfenced mode

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:

Applying Neural models

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.

Using the function DM_getClusterID

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.

Note:
The cluster names and cluster IDs are also shown in the IM Visualizer.

Migrating from IM Scoring Version 8.1

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:

  1. Installing IM Scoring V8.2
  2. Performing the configuration steps
  3. Re-enabling your databases or enabling new databases
    Note:
    When you re-enable your databases, you do not need to have already disabled any databases.

Migrating a DB2 instance (UNIX only)

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.

Note:
You need not change database manager configuration parameters (DBM CFG) or DB2 registry settings.

Migrating databases (all platforms)

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.

Note:
It is not necessary to change database manager configuration parameters (DBM CFG) or DB2 registry settings.

To migrate existing database objects:

  1. List the databases for your database instance using the DB2 command:
    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
  2. You must migrate each local database that has already been enabled with a previous version of IM. Check the status of existing databases, for example, to find out whether the existing database object is in fenced or unfenced mode:
    idmcheckdb dbname
    Sample 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.
    ...
    
  3. Call the following command to enable and migrate all databases that were enabled for previous versions:
    idmenabledb dbname
    For more information refer to The idmenabledb command.
    Note:
    You do not need to disable (idmdisabledb) a database before invoking idmenabledb.
    The idmenabledb tool creates new database objects in the database and changes existing database objects if required. For example, the names of some libraries implementing external C UDF/UDM/SP have changed and the DDL must be updated to reflect the new external symbol names:
  4. For more information on how to verify the successful migration refer to DB2 Intelligent Miner Modeling, DB2 Intelligent Miner Scoring, DB2 Intelligent Miner Visualization: Installing the Intelligent Miner products. The idmcheckdb command should now report the current version of the product:
    E:\>idmcheckdb sample
    The database "sample" is enabled for
    IM Modeling Version 8.2 and IM Scoring Version 8.2 in "fenced" mode.
    ...

Database instance restart

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.

Appendixes

Appendix A. IM Scoring conformance to PMML

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.

Note:
IM Scoring supports PMML up to V2.1. The term PMML, throughout this book, refers to PMML V2.1 and any previous versions of PMML, unless otherwise specified.

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 application

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.

Center-based clustering
Decision trees
Distribution-based clustering
Neural networks
Regression
IM Scoring supports all core and non-core features of PMML for regression.

IM Scoring conversion tools

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.

Regression models

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.

Features supported in addition to PMML 2.1

The following features are supported in addition to PMML 2.1 for interoperability reasons:

Appendix B. SAS Enterprise Miner support

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.

Notes:
  1. IM Scoring supports SAS Enterprise Miner V5.1.
  2. The following SAS EM options are not supported:

For more information refer to the SAS Enterprise Miner V5.1 documentation.

Appendix C. SPSS Clementine support

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.

Note:
Models created in SPSS Clementine V8.5 can be used with IM Scoring via the PMML mechanism. However, you have to make sure that the respective options are set accordingly.
Figure 10. User options
User options

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:

Notes:
  1. In accordance with the PMML standard, IM Scoring cannot distinguish arbitrary numbers of trailing blanks in values of categorical variables. Problems might arise if a field has two or more values that only differ from each other in the number of trailing blanks. SPSS Clementine prevents the export of such models or informs you that problems may occur.
  2. SPSS Clementine only scans the first few lines of a text file to determine the data type. If a numeric field has integers in the first few lines, but floating point decimals later on, SPSS Clementine might set the type to integer, even if floating point decimal is the correct type. SPSS Clementine converts these by cutting off the decimal places, while IM Scoring uses the float "as is". They produce different results.

    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.

  3. SPSS Clementine Neural Networks and Tree C5 models trained to predict an integer column return a floating point decimal if applied in IM Scoring. If the result is inserted into a column of type integer, it must be explicitly converted to integer via the scalar SQL function ROUND. Otherwise the decimal places will be cut off, leading to different results.

For more information refer to the SPSS Clementine V8.5 documentation.

Appendix D. The DB2 REC2XML scalar function

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

Read syntax diagramSkip visual syntax diagram>>-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.

decimal-constant
The expansion factor for replacing column data characters. The decimal value must be greater than 0.0 and less than or equal to 6.0 (SQLSTATE 42820).

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).

format-string
The string constant that specifies which format the function is to use during execution.

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.

Read syntax diagramSkip visual syntax diagram>>-<--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.

row-tag-string
A string constant that specifies the tag used for each row. If an empty string is specified, then a value of 'row' is assumed.

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.

Note:
In IM Scoring you can specify only the following for row-tag-string:
  • An empty string
  • The string 'row'
  • A blank string as the 3rd parameter of the function REC2XML
column-name
A qualified or unqualified name of a table column. The column must have one of the following data types (SQLSTATE 42815):

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.

Table 33. Column Values String Result
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.

Table 34. Character replacements for XML attribute values and element values
Character Replaced XML value
< &lt;
> &gt;
" &quot;
& &amp;
' &apos;
Note:
REC2XML does not insert new line characters in the output. All example output is formatted for the sake of readability.

Appendix E. Coexistence with IM Modeling

Here you find an overview of the data or information that is shared between IM Modeling and IM Scoring.

Shared schema

The schema IDMMX is shared between IM Modeling and IM Scoring.

Shared data types

The following data types are shared between IM Modeling and IM Scoring:

Shared functions

The following functions are shared between IM Modeling and IM Scoring:

DM_RuleModel
DM_ClasModel
DM_ClusteringModel
DM_RegressionModel

Shared methods

The following methods are shared between IM Modeling and IM Scoring:

DM_LogicalDataSpec

Shared commands

The following commands are shared between IM Modeling and IM Scoring:

Appendix F. Using IM Scoring in a multilanguage environment

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

Appendix G. Encoding considerations when exporting models

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">

Appendix H. Notices

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.

Trademarks

The following terms are trademarks of the IBM Corporation in the United States, other countries, or both:

alphaWorks
AIX
DB2
DB2 Universal Database
IBM
Intelligent Miner
Redbooks
WebSphere

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.

Bibliography

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.

IBM DB2 Intelligent Miner publications

Related information

IBM Web sites

Other Web sites

Index

Special characters
A B C D E F G I J L M N O P Q R S T U W X
Special characters A B C D E F G I J L M N O P Q R S T U W X