Python* API Reference for Intel® Data Analytics Acceleration Library 2018 Update 2

df_cls_traverse_model.py

1 # file: df_cls_traverse_model.py
2 #===============================================================================
3 # Copyright 2014-2018 Intel Corporation
4 # All Rights Reserved.
5 #
6 # If this software was obtained under the Intel Simplified Software License,
7 # the following terms apply:
8 #
9 # The source code, information and material ("Material") contained herein is
10 # owned by Intel Corporation or its suppliers or licensors, and title to such
11 # Material remains with Intel Corporation or its suppliers or licensors. The
12 # Material contains proprietary information of Intel or its suppliers and
13 # licensors. The Material is protected by worldwide copyright laws and treaty
14 # provisions. No part of the Material may be used, copied, reproduced,
15 # modified, published, uploaded, posted, transmitted, distributed or disclosed
16 # in any way without Intel's prior express written permission. No license under
17 # any patent, copyright or other intellectual property rights in the Material
18 # is granted to or conferred upon you, either expressly, by implication,
19 # inducement, estoppel or otherwise. Any license under such intellectual
20 # property rights must be express and approved by Intel in writing.
21 #
22 # Unless otherwise agreed by Intel in writing, you may not remove or alter this
23 # notice or any other notice embedded in Materials by Intel or Intel's
24 # suppliers or licensors in any way.
25 #
26 #
27 # If this software was obtained under the Apache License, Version 2.0 (the
28 # "License"), the following terms apply:
29 #
30 # You may not use this file except in compliance with the License. You may
31 # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
32 #
33 #
34 # Unless required by applicable law or agreed to in writing, software
35 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
36 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
37 #
38 # See the License for the specific language governing permissions and
39 # limitations under the License.
40 #===============================================================================
41 
42 #
43 # ! Content:
44 # ! Python example of decision forest classification model traversal.
45 # !
46 # ! The program trains the decision forest classification model on a training
47 # ! datasetFileName and prints the trained model by its depth-first traversing.
48 # !*****************************************************************************
49 
50 #
51 
54 from __future__ import print_function
55 
56 from daal.algorithms import classifier
57 from daal.algorithms import decision_forest
58 import daal.algorithms.decision_forest.classification
59 import daal.algorithms.decision_forest.classification.training
60 
61 from daal.data_management import (
62  FileDataSource, HomogenNumericTable, MergedNumericTable, NumericTableIface, DataSourceIface, data_feature_utils
63 )
64 
65 # Input data set parameters
66 trainDatasetFileName = "../data/batch/df_classification_train.csv"
67 categoricalFeaturesIndices = [2]
68 nFeatures = 3 # Number of features in training and testing data sets
69 
70 # Decision forest parameters
71 nTrees = 2
72 minObservationsInLeafNode = 8
73 maxTreeDepth = 15
74 
75 nClasses = 5 # Number of classes
76 
77 
78 def trainModel():
79 
80  # Create Numeric Tables for training data and dependent variables
81  trainData, trainDependentVariable = loadData(trainDatasetFileName)
82 
83  # Create an algorithm object to train the decision forest classification model
84  algorithm = decision_forest.classification.training.Batch(nClasses)
85 
86  # Pass a training data set and dependent values to the algorithm
87  algorithm.input.set(classifier.training.data, trainData)
88  algorithm.input.set(classifier.training.labels, trainDependentVariable)
89 
90  algorithm.parameter.nTrees = nTrees
91  algorithm.parameter.featuresPerNode = nFeatures
92  algorithm.parameter.minObservationsInLeafNode = minObservationsInLeafNode
93  algorithm.parameter.maxTreeDepth = maxTreeDepth
94 
95  # Build the decision forest classification model and return the result
96  return algorithm.compute()
97 
98 
99 def loadData(fileName):
100 
101  # Initialize FileDataSource<CSVFeatureManager> to retrieve the input data from a .csv file
102  trainDataSource = FileDataSource(
103  fileName, DataSourceIface.notAllocateNumericTable, DataSourceIface.doDictionaryFromContext
104  )
105 
106  # Create Numeric Tables for training data and dependent variables
107  data = HomogenNumericTable(nFeatures, 0, NumericTableIface.notAllocate)
108  dependentVar = HomogenNumericTable(1, 0, NumericTableIface.notAllocate)
109  mergedData = MergedNumericTable(data, dependentVar)
110 
111  # Retrieve the data from input file
112  trainDataSource.loadDataBlock(mergedData)
113 
114  dictionary = data.getDictionary()
115  for i in range(len(categoricalFeaturesIndices)):
116  dictionary[categoricalFeaturesIndices[i]].featureType = data_feature_utils.DAAL_CATEGORICAL
117 
118  return data, dependentVar
119 
120 
121 # Visitor class implementing NodeVisitor interface, prints out tree nodes of the model when it is called back by model traversal method
122 class PrintNodeVisitor(classifier.TreeNodeVisitor):
123 
124  def __init__(self):
125  super(PrintNodeVisitor, self).__init__()
126 
127  def onLeafNode(self, level, response):
128 
129  for i in range(level):
130  print(" ", end='')
131  print("Level {}, leaf node. Response value = {}".format(level, response))
132  return True
133 
134  def onSplitNode(self, level, featureIndex, featureValue):
135 
136  for i in range(level):
137  print(" ", end='')
138  print("Level {}, split node. Feature index = {}, feature value = {:.6g}".format(level, featureIndex, featureValue))
139  return True
140 
141 
142 def printModel(m):
143  visitor = PrintNodeVisitor()
144  print("Number of trees: {}".format(m.numberOfTrees()))
145  for i in range(m.numberOfTrees()):
146  print("Tree #{}".format(i))
147  m.traverseDF(i, visitor)
148 
149 
150 if __name__ == "__main__":
151 
152  trainingResult = trainModel()
153  printModel(trainingResult.get(classifier.training.model))

For more complete information about compiler optimizations, see our Optimization Notice.