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

svm_two_class_metrics_dense_batch.py

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

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