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

mn_naive_bayes_dense_distr.py

1 # file: mn_naive_bayes_dense_distr.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 
44 
45 import os
46 import sys
47 
48 from daal import step1Local, step2Master
49 from daal.algorithms.multinomial_naive_bayes import prediction, training
50 from daal.algorithms import classifier
51 from daal.data_management import (
52  FileDataSource, DataSourceIface, NumericTableIface, HomogenNumericTable, MergedNumericTable
53 )
54 
55 utils_folder = os.path.realpath(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
56 if utils_folder not in sys.path:
57  sys.path.insert(0, utils_folder)
58 from utils import printNumericTables
59 
60 DAAL_PREFIX = os.path.join('..', 'data')
61 
62 # Input data set parameters
63 trainDatasetFileNames = [
64  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_dense.csv'),
65  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_dense.csv'),
66  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_dense.csv'),
67  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_dense.csv')
68 ]
69 
70 testDatasetFileName = os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_test_dense.csv')
71 
72 nFeatures = 20
73 nClasses = 20
74 nBlocks = 4
75 
76 trainingResult = None
77 predictionResult = None
78 testGroundTruth = None
79 
80 
81 def trainModel():
82  global trainingResult
83 
84  masterAlgorithm = training.Distributed(step2Master, nClasses)
85 
86  for i in range(nBlocks):
87  # Initialize FileDataSource<CSVFeatureManager> to retrieve the input data from a .csv file
88  trainDataSource = FileDataSource(
89  trainDatasetFileNames[i], DataSourceIface.notAllocateNumericTable,
90  DataSourceIface.doDictionaryFromContext
91  )
92  # Create Numeric Tables for training data and labels
93  trainData = HomogenNumericTable(nFeatures, 0, NumericTableIface.doNotAllocate)
94  trainGroundTruth = HomogenNumericTable(1, 0, NumericTableIface.doNotAllocate)
95  mergedData = MergedNumericTable(trainData, trainGroundTruth)
96 
97  # Retrieve the data from the input file
98  trainDataSource.loadDataBlock(mergedData)
99 
100  # Create an algorithm object to train the Naive Bayes model on the local-node data
101  localAlgorithm = training.Distributed(step1Local, nClasses)
102 
103  # Pass a training data set and dependent values to the algorithm
104  localAlgorithm.input.set(classifier.training.data, trainData)
105  localAlgorithm.input.set(classifier.training.labels, trainGroundTruth)
106 
107  # Build the Naive Bayes model on the local node and
108  # Set the local Naive Bayes model as input for the master-node algorithm
109  masterAlgorithm.input.add(training.partialModels, localAlgorithm.compute())
110 
111  # Merge and finalize the Naive Bayes model on the master node
112  masterAlgorithm.compute()
113  trainingResult = masterAlgorithm.finalizeCompute() # Retrieve the algorithm results
114 
115 
116 def testModel():
117  global predictionResult, testGroundTruth
118 
119  # Initialize FileDataSource<CSVFeatureManager> to retrieve the test data from a .csv file
120  testDataSource = FileDataSource(
121  testDatasetFileName, DataSourceIface.notAllocateNumericTable,
122  DataSourceIface.doDictionaryFromContext
123  )
124 
125  # Create Numeric Tables for testing data and labels
126  testData = HomogenNumericTable(nFeatures, 0, NumericTableIface.doNotAllocate)
127  testGroundTruth = HomogenNumericTable(1, 0, NumericTableIface.doNotAllocate)
128  mergedData = MergedNumericTable(testData, testGroundTruth)
129 
130  # Retrieve the data from input file
131  testDataSource.loadDataBlock(mergedData)
132 
133  # Create an algorithm object to predict Naive Bayes values
134  algorithm = prediction.Batch(nClasses)
135 
136  # Pass a testing data set and the trained model to the algorithm
137  algorithm.input.setTable(classifier.prediction.data, testData)
138  algorithm.input.setModel(classifier.prediction.model, trainingResult.get(classifier.training.model))
139 
140  # Predict Naive Bayes values (Result class from classifier.prediction)
141  predictionResult = algorithm.compute() # Retrieve the algorithm results
142 
143 
144 def printResults():
145  printNumericTables(
146  testGroundTruth, predictionResult.get(classifier.prediction.prediction),
147  "Ground truth", "Classification results",
148  "NaiveBayes classification results (first 20 observations):", 20, flt64=False
149  )
150 
151 if __name__ == "__main__":
152 
153  trainModel()
154  testModel()
155  printResults()

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