Python* API Reference for Intel® Data Analytics Acceleration Library 2020 Update 1

mn_naive_bayes_csr_distr.py

1 # file: mn_naive_bayes_csr_distr.py
2 #===============================================================================
3 # Copyright 2014-2020 Intel Corporation
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #===============================================================================
17 
18 
19 
20 
21 import os
22 import sys
23 
24 from daal import step1Local, step2Master
25 from daal.algorithms import classifier
26 from daal.algorithms.multinomial_naive_bayes import training, prediction
27 from daal.data_management import FileDataSource, DataSourceIface
28 
29 utils_folder = os.path.realpath(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
30 if utils_folder not in sys.path:
31  sys.path.insert(0, utils_folder)
32 from utils import printNumericTables, createSparseTable
33 
34 DAAL_PREFIX = os.path.join('..', 'data')
35 
36 # Input data set parameters
37 trainDatasetFileNames = [
38  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_csr.csv'),
39  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_csr.csv'),
40  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_csr.csv'),
41  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_csr.csv')
42 ]
43 
44 trainGroundTruthFileNames = [
45  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_labels.csv'),
46  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_labels.csv'),
47  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_labels.csv'),
48  os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_train_labels.csv')
49 ]
50 
51 testDatasetFileName = os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_test_csr.csv')
52 testGroundTruthFileName = os.path.join(DAAL_PREFIX, 'batch', 'naivebayes_test_labels.csv')
53 
54 nClasses = 20
55 nBlocks = 4
56 nTrainVectorsInBlock = 8000
57 nTestObservations = 2000
58 
59 trainingResult = None
60 predictionResult = None
61 trainData = [0] * nBlocks
62 testData = None
63 
64 
65 def trainModel():
66  global trainData, trainingResult
67 
68  masterAlgorithm = training.Distributed(step2Master, nClasses, method=training.fastCSR)
69 
70  for i in range(nBlocks):
71  # Read trainDatasetFileNames and create a numeric table to store the input data
72  trainData[i] = createSparseTable(trainDatasetFileNames[i])
73 
74  # Initialize FileDataSource<CSVFeatureManager> to retrieve the input data from a .csv file
75  trainLabelsSource = FileDataSource(
76  trainGroundTruthFileNames[i], DataSourceIface.doAllocateNumericTable,
77  DataSourceIface.doDictionaryFromContext
78  )
79 
80  # Retrieve the data from an input file
81  trainLabelsSource.loadDataBlock(nTrainVectorsInBlock)
82 
83  # Create an algorithm object to train the Naive Bayes model on the local-node data
84  localAlgorithm = training.Distributed(step1Local, nClasses, method=training.fastCSR)
85 
86  # Pass a training data set and dependent values to the algorithm
87  localAlgorithm.input.set(classifier.training.data, trainData[i])
88  localAlgorithm.input.set(classifier.training.labels, trainLabelsSource.getNumericTable())
89 
90  # Build the Naive Bayes model on the local node
91  # Set the local Naive Bayes model as input for the master-node algorithm
92  masterAlgorithm.input.add(training.partialModels, localAlgorithm.compute())
93 
94  # Merge and finalize the Naive Bayes model on the master node
95  masterAlgorithm.compute()
96  trainingResult = masterAlgorithm.finalizeCompute() # Retrieve the algorithm results
97 
98 
99 def testModel():
100  global predictionResult, testData
101 
102  # Read testDatasetFileName and create a numeric table to store the input data
103  testData = createSparseTable(testDatasetFileName)
104 
105  # Create an algorithm object to predict Naive Bayes values
106  algorithm = prediction.Batch(nClasses, method=prediction.fastCSR)
107 
108  # Pass a testing data set and the trained model to the algorithm
109  algorithm.input.setTable(classifier.prediction.data, testData)
110  algorithm.input.setModel(classifier.prediction.model, trainingResult.get(classifier.training.model))
111 
112  # Predict Naive Bayes values (Result class from classifier.prediction)
113  predictionResult = algorithm.compute() # Retrieve the algorithm results
114 
115 
116 def printResults():
117 
118  testGroundTruth = FileDataSource(
119  testGroundTruthFileName, DataSourceIface.doAllocateNumericTable,
120  DataSourceIface.doDictionaryFromContext
121  )
122  testGroundTruth.loadDataBlock(nTestObservations)
123 
124  printNumericTables(
125  testGroundTruth.getNumericTable(),
126  predictionResult.get(classifier.prediction.prediction),
127  "Ground truth", "Classification results",
128  "NaiveBayes classification results (first 20 observations):", 20, 15, flt64=False
129  )
130 
131 if __name__ == "__main__":
132 
133  trainModel()
134  testModel()
135  printResults()

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