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

svm_multi_class_metrics_dense_batch.py

1 # file: svm_multi_class_metrics_dense_batch.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 multi-class support vector machine (SVM) quality metrics
45 # !
46 # !*****************************************************************************
47 
48 #
49 
52 
53 import os
54 import sys
55 import numpy as np
56 
57 from daal.algorithms.classifier.quality_metric import multiclass_confusion_matrix
58 from daal.algorithms import svm
59 from daal.algorithms import kernel_function
60 from daal.algorithms import multi_class_classifier
61 from daal.algorithms import classifier
62 from daal.data_management import (
63  DataSourceIface, FileDataSource, readOnly, BlockDescriptor, HomogenNumericTable,
64  NumericTableIface, MergedNumericTable
65 )
66 
67 utils_folder = os.path.realpath(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
68 if utils_folder not in sys.path:
69  sys.path.insert(0, utils_folder)
70 from utils import printNumericTables, printNumericTable
71 
72 # Input data set parameters
73 DATA_PREFIX = os.path.join('..', 'data', 'batch')
74 trainDatasetFileName = os.path.join(DATA_PREFIX, 'svm_multi_class_train_dense.csv')
75 testDatasetFileName = os.path.join(DATA_PREFIX, 'svm_multi_class_test_dense.csv')
76 
77 nFeatures = 20
78 nClasses = 5
79 
80 training = svm.training.Batch(fptype=np.float64)
81 prediction = svm.prediction.Batch(fptype=np.float64)
82 
83 # Model object for the multi-class classifier algorithm
84 trainingResult = None
85 predictionResult = None
86 
87 # Parameters for the multi-class classifier kernel function
88 kernel = kernel_function.linear.Batch(fptype=np.float64)
89 
90 qualityMetricSetResult = None
91 predictedLabels = None
92 groundTruthLabels = None
93 
94 
95 def trainModel():
96  global trainingResult
97 
98  # Initialize FileDataSource to retrieve the input data from a .csv file
99  trainDataSource = FileDataSource(
100  trainDatasetFileName, DataSourceIface.notAllocateNumericTable,
101  DataSourceIface.doDictionaryFromContext
102  )
103 
104  # Create Numeric Tables for training data and labels
105  trainData = HomogenNumericTable(nFeatures, 0, NumericTableIface.doNotAllocate)
106  trainGroundTruth = HomogenNumericTable(1, 0, NumericTableIface.doNotAllocate)
107  mergedData = MergedNumericTable(trainData, trainGroundTruth)
108 
109  # Retrieve the data from the input file
110  trainDataSource.loadDataBlock(mergedData)
111 
112  # Create an algorithm object to train the multi-class SVM model
113  algorithm = multi_class_classifier.training.Batch(nClasses,fptype=np.float64)
114 
115  algorithm.parameter.training = training
116  algorithm.parameter.prediction = prediction
117 
118  # Pass a training data set and dependent values to the algorithm
119  algorithm.input.set(classifier.training.data, trainData)
120  algorithm.input.set(classifier.training.labels, trainGroundTruth)
121 
122  # Build the multi-class SVM model and get the algorithm results
123  trainingResult = algorithm.compute()
124 
125 
126 def testModel():
127  global predictionResult, groundTruthLabels
128 
129  # Initialize FileDataSource<CSVFeatureManager> to retrieve the test data from a .csv file
130  testDataSource = FileDataSource(
131  testDatasetFileName, DataSourceIface.doAllocateNumericTable,
132  DataSourceIface.doDictionaryFromContext
133  )
134 
135  # Create Numeric Tables for testing data and labels
136  testData = HomogenNumericTable(nFeatures, 0, NumericTableIface.doNotAllocate)
137  groundTruthLabels = HomogenNumericTable(1, 0, NumericTableIface.doNotAllocate)
138  mergedData = MergedNumericTable(testData, groundTruthLabels)
139 
140  # Retrieve the data from input file
141  testDataSource.loadDataBlock(mergedData)
142 
143  # Create an algorithm object to predict multi-class SVM values
144  algorithm = multi_class_classifier.prediction.Batch(nClasses,fptype=np.float64)
145 
146  algorithm.parameter.training = training
147  algorithm.parameter.prediction = prediction
148 
149  # Pass a testing data set and the trained model to the algorithm
150  algorithm.input.setTable(classifier.prediction.data, testData)
151  algorithm.input.setModel(classifier.prediction.model, trainingResult.get(classifier.training.model))
152 
153  # Predict multi-class SVM values and get the Result class from daal.algorithms.classifier.prediction
154  predictionResult = algorithm.compute()
155 
156 
157 def testModelQuality():
158  global predictedLabels, qualityMetricSetResult
159 
160  # Retrieve predicted labels
161  predictedLabels = predictionResult.get(classifier.prediction.prediction)
162 
163  # Create a quality metric set object to compute quality metrics of the multi-class classifier algorithm
164  qualityMetricSet = multi_class_classifier.quality_metric_set.Batch(nClasses)
165  input = qualityMetricSet.getInputDataCollection().getInput(multi_class_classifier.quality_metric_set.confusionMatrix)
166 
167  input.set(multiclass_confusion_matrix.predictedLabels, predictedLabels)
168  input.set(multiclass_confusion_matrix.groundTruthLabels, groundTruthLabels)
169 
170  # Compute quality metrics and get the quality metrics
171  # returns ResultCollection class from daal.algorithms.multi_class_classifier.quality_metric_set
172  qualityMetricSetResult = qualityMetricSet.compute()
173 
174 def printResults():
175 
176  # Print the classification results
177  printNumericTables(
178  groundTruthLabels, predictedLabels,
179  "Ground truth", "Classification results",
180  "SVM classification results (first 20 observations):", 20, interval=15, flt64=False
181  )
182  # Print the quality metrics
183  qualityMetricResult = qualityMetricSetResult.getResult(multi_class_classifier.quality_metric_set.confusionMatrix)
184  printNumericTable(qualityMetricResult.get(multiclass_confusion_matrix.confusionMatrix), "Confusion matrix:")
185 
186  block = BlockDescriptor()
187  qualityMetricsTable = qualityMetricResult.get(multiclass_confusion_matrix.multiClassMetrics)
188  qualityMetricsTable.getBlockOfRows(0, 1, readOnly, block)
189  qualityMetricsData = block.getArray().flatten()
190  print("Average accuracy: {0:.3f}".format(qualityMetricsData[multiclass_confusion_matrix.averageAccuracy]))
191  print("Error rate: {0:.3f}".format(qualityMetricsData[multiclass_confusion_matrix.errorRate]))
192  print("Micro precision: {0:.3f}".format(qualityMetricsData[multiclass_confusion_matrix.microPrecision]))
193  print("Micro recall: {0:.3f}".format(qualityMetricsData[multiclass_confusion_matrix.microRecall]))
194  print("Micro F-score: {0:.3f}".format(qualityMetricsData[multiclass_confusion_matrix.microFscore]))
195  print("Macro precision: {0:.3f}".format(qualityMetricsData[multiclass_confusion_matrix.macroPrecision]))
196  print("Macro recall: {0:.3f}".format(qualityMetricsData[multiclass_confusion_matrix.macroRecall]))
197  print("Macro F-score: {0:.3f}".format(qualityMetricsData[multiclass_confusion_matrix.macroFscore]))
198  qualityMetricsTable.releaseBlockOfRows(block)
199 
200 if __name__ == "__main__":
201  training.parameter.cacheSize = 100000000
202  training.parameter.kernel = kernel
203  prediction.parameter.kernel = kernel
204 
205  trainModel()
206  testModel()
207  testModelQuality()
208  printResults()

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