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

lin_reg_metrics_dense_batch.py

1 #===============================================================================
2 # Copyright 2014-2017 Intel Corporation
3 # All Rights Reserved.
4 #
5 # If this software was obtained under the Intel Simplified Software License,
6 # the following terms apply:
7 #
8 # The source code, information and material ("Material") contained herein is
9 # owned by Intel Corporation or its suppliers or licensors, and title to such
10 # Material remains with Intel Corporation or its suppliers or licensors. The
11 # Material contains proprietary information of Intel or its suppliers and
12 # licensors. The Material is protected by worldwide copyright laws and treaty
13 # provisions. No part of the Material may be used, copied, reproduced,
14 # modified, published, uploaded, posted, transmitted, distributed or disclosed
15 # in any way without Intel's prior express written permission. No license under
16 # any patent, copyright or other intellectual property rights in the Material
17 # is granted to or conferred upon you, either expressly, by implication,
18 # inducement, estoppel or otherwise. Any license under such intellectual
19 # property rights must be express and approved by Intel in writing.
20 #
21 # Unless otherwise agreed by Intel in writing, you may not remove or alter this
22 # notice or any other notice embedded in Materials by Intel or Intel's
23 # suppliers or licensors in any way.
24 #
25 #
26 # If this software was obtained under the Apache License, Version 2.0 (the
27 # "License"), the following terms apply:
28 #
29 # You may not use this file except in compliance with the License. You may
30 # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
31 #
32 #
33 # Unless required by applicable law or agreed to in writing, software
34 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
35 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
36 #
37 # See the License for the specific language governing permissions and
38 # limitations under the License.
39 #===============================================================================
40 
41 ## <a name="DAAL-EXAMPLE-PY-LIN_REG_METRICS_DENSE_BATCH"></a>
42 ## \example lin_reg_metrics_dense_batch.py
43 
44 import os
45 import sys
46 
47 import daal.algorithms.linear_regression as linear_regression
48 import daal.algorithms.linear_regression.quality_metric_set as quality_metric_set
49 from daal.algorithms.linear_regression import training, prediction
50 from daal.algorithms.linear_regression.quality_metric import single_beta, group_of_betas
51 from daal.data_management import (
52  DataSourceIface, FileDataSource, HomogenNumericTable, MergedNumericTable,
53  NumericTableIface, BlockDescriptor, readWrite
54 )
55 
56 utils_folder = os.path.realpath(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
57 if utils_folder not in sys.path:
58  sys.path.insert(0, utils_folder)
59 from utils import printNumericTable
60 
61 trainDatasetFileName = os.path.join('..', 'data', 'batch', 'linear_regression_train.csv')
62 
63 nFeatures = 10
64 nDependentVariables = 2
65 
66 trainingResult = None
67 # predictionResult = None
68 qmsResult = None
69 trainData = None
70 trainDependentVariables = None
71 
72 def trainModel(algorithm):
73  global trainingResult, trainData, trainDependentVariables
74 
75  # Pass a training data set and dependent values to the algorithm
76  algorithm.input.set(training.data, trainData)
77  algorithm.input.set(training.dependentVariables, trainDependentVariables)
78 
79  # Build the multiple linear regression model and retrieve the algorithm results
80  trainingResult = algorithm.compute()
81  printNumericTable(trainingResult.get(training.model).getBeta(), "Linear Regression coefficients:")
82 
83 def predictResults(trainData):
84  # Create an algorithm object to predict values of multiple linear regression
85  algorithm = prediction.Batch()
86 
87  # Pass a testing data set and the trained model to the algorithm
88  algorithm.input.setTable(prediction.data, trainData)
89  algorithm.input.setModel(prediction.model, trainingResult.get(training.model))
90 
91  # Predict values of multiple linear regression and retrieve the algorithm results
92  predictionResult = algorithm.compute()
93  return predictionResult.get(prediction.prediction)
94 
95 def predictReducedModelResults(trainData):
96  model = trainingResult.get(training.model)
97 
98  betas = model.getBeta()
99  nBetas = model.getNumberOfBetas()
100 
101  j1 = 2
102  j2 = 10
103  savedBeta = [None] * (nBetas * nDependentVariables)
104 
105  block = BlockDescriptor()
106  betas.getBlockOfRows(0, nDependentVariables, readWrite, block)
107  pBeta = block.getArray().flatten()
108 
109  for i in range(0, nDependentVariables):
110  savedBeta[nDependentVariables * i + j1] = pBeta[nDependentVariables * i + j1]
111  savedBeta[nDependentVariables * i + j2] = pBeta[nDependentVariables * i + j2]
112  pBeta[nDependentVariables * i + j1] = 0
113  pBeta[nDependentVariables * i + j2] = 0
114  betas.releaseBlockOfRows(block)
115 
116  predictedResults = predictResults(trainData)
117 
118  block = BlockDescriptor()
119  betas.getBlockOfRows(0, nDependentVariables, readWrite, block)
120  pBeta = block.getArray().flatten()
121 
122  savedBeta = [None] * nBetas * nDependentVariables
123  for i in range(0, nDependentVariables):
124  pBeta[nDependentVariables * i + j1] = savedBeta[nDependentVariables * i + j1]
125  pBeta[nDependentVariables * i + j2] = savedBeta[nDependentVariables * i + j2]
126  betas.releaseBlockOfRows(block)
127  return predictedResults
128 
129 def testModelQuality():
130  global trainingResult, qmsResult
131 
132  predictedResults = predictResults(trainData)
133  printNumericTable(trainDependentVariables, "Expected responses (first 20 rows):", 20)
134  printNumericTable(predictedResults, "Predicted responses (first 20 rows):", 20)
135 
136  model = trainingResult.get(linear_regression.training.model)
137  predictedReducedModelResults = predictReducedModelResults(trainData)
138  printNumericTable(predictedReducedModelResults, "Responses predicted with reduced model (first 20 rows):", 20)
139 
140  # Create a quality metric set object to compute quality metrics of the linear regression algorithm
141  nBetaReducedModel = model.getNumberOfBetas() - 2
142  qualityMetricSet = quality_metric_set.Batch(model.getNumberOfBetas(), nBetaReducedModel)
143  singleBeta = single_beta.Input.downCast(qualityMetricSet.getInputDataCollection().getInput(quality_metric_set.singleBeta))
144  singleBeta.setDataInput(single_beta.expectedResponses, trainDependentVariables)
145  singleBeta.setDataInput(single_beta.predictedResponses, predictedResults)
146  singleBeta.setModelInput(single_beta.model, model)
147 
148  # Set input for a group of betas metrics algorithm
149  groupOfBetas = group_of_betas.Input.downCast(qualityMetricSet.getInputDataCollection().getInput(quality_metric_set.groupOfBetas))
150  groupOfBetas.set(group_of_betas.expectedResponses, trainDependentVariables)
151  groupOfBetas.set(group_of_betas.predictedResponses, predictedResults)
152  groupOfBetas.set(group_of_betas.predictedReducedModelResponses, predictedReducedModelResults)
153 
154  # Compute quality metrics
155  qualityMetricSet.compute()
156 
157  # Retrieve the quality metrics
158  qmsResult = qualityMetricSet.getResultCollection()
159 
160 def printResults():
161  # Print the quality metrics for a single beta
162  print ("Quality metrics for a single beta")
163  result = single_beta.Result.downCast(qmsResult.getResult(quality_metric_set.singleBeta))
164  printNumericTable(result.getResult(single_beta.rms), "Root means square errors for each response (dependent variable):")
165  printNumericTable(result.getResult(single_beta.variance), "Variance for each response (dependent variable):")
166  printNumericTable(result.getResult(single_beta.zScore), "Z-score statistics:")
167  printNumericTable(result.getResult(single_beta.confidenceIntervals), "Confidence intervals for each beta coefficient:")
168  printNumericTable(result.getResult(single_beta.inverseOfXtX), "Inverse(Xt * X) matrix:")
169 
170  coll = result.getResultDataCollection(single_beta.betaCovariances)
171  for i in range(0, coll.size()):
172  message = "Variance-covariance matrix for betas of " + str(i) + "-th response"
173  betaCov = result.get(single_beta.betaCovariances, i)
174  printNumericTable(betaCov, message)
175 
176  # Print quality metrics for a group of betas
177  print ("Quality metrics for a group of betas")
178  result = group_of_betas.Result.downCast(qmsResult.getResult(quality_metric_set.groupOfBetas))
179 
180  printNumericTable(result.get(group_of_betas.expectedMeans), "Means of expected responses for each dependent variable:", 0, 0, 20)
181  printNumericTable(result.get(group_of_betas.expectedVariance), "Variance of expected responses for each dependent variable:", 0, 0, 20)
182  printNumericTable(result.get(group_of_betas.regSS), "Regression sum of squares of expected responses:", 0, 0, 20)
183  printNumericTable(result.get(group_of_betas.resSS), "Sum of squares of residuals for each dependent variable:", 0, 0, 20)
184  printNumericTable(result.get(group_of_betas.tSS), "Total sum of squares for each dependent variable:", 0, 0, 20)
185  printNumericTable(result.get(group_of_betas.determinationCoeff), "Determination coefficient for each dependent variable:", 0, 0, 20)
186  printNumericTable(result.get(group_of_betas.fStatistics), "F-statistics for each dependent variable:", 0, 0, 20)
187 
188 if __name__ == "__main__":
189 
190  # Initialize FileDataSource<CSVFeatureManager> to retrieve the input data from a .csv file
191  dataSource = FileDataSource(trainDatasetFileName,
192  DataSourceIface.notAllocateNumericTable,
193  DataSourceIface.doDictionaryFromContext)
194 
195  # Create Numeric Tables for data and values for dependent variable
196  trainData = HomogenNumericTable(nFeatures, 0, NumericTableIface.doNotAllocate)
197  trainDependentVariables = HomogenNumericTable(nDependentVariables, 0, NumericTableIface.doNotAllocate)
198  mergedData = MergedNumericTable(trainData, trainDependentVariables)
199 
200  # Retrieve the data from the input file
201  dataSource.loadDataBlock(mergedData)
202 
203  for i in range(0, 2):
204  if i == 0:
205  print ("Train model with normal equation algorithm.")
206  algorithm = training.Batch()
207  trainModel(algorithm)
208  else:
209  print ("Train model with QR algorithm.")
210  algorithm = training.Batch(method=training.qrDense)
211  trainModel(algorithm)
212  testModelQuality()
213  printResults()

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