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

lin_reg_metrics_dense_batch.py

1 # file: lin_reg_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 
44 
45 import os
46 import sys
47 
48 import daal.algorithms.linear_regression as linear_regression
49 import daal.algorithms.linear_regression.quality_metric_set as quality_metric_set
50 from daal.algorithms.linear_regression import training, prediction
51 from daal.algorithms.linear_regression.quality_metric import single_beta, group_of_betas
52 from daal.data_management import (
53  DataSourceIface, FileDataSource, HomogenNumericTable, MergedNumericTable,
54  NumericTableIface, BlockDescriptor, readWrite
55 )
56 
57 utils_folder = os.path.realpath(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
58 if utils_folder not in sys.path:
59  sys.path.insert(0, utils_folder)
60 from utils import printNumericTable
61 
62 trainDatasetFileName = os.path.join('..', 'data', 'batch', 'linear_regression_train.csv')
63 
64 nFeatures = 10
65 nDependentVariables = 2
66 
67 trainingResult = None
68 # predictionResult = None
69 qmsResult = None
70 trainData = None
71 trainDependentVariables = None
72 
73 def trainModel(algorithm):
74  global trainingResult, trainData, trainDependentVariables
75 
76  # Pass a training data set and dependent values to the algorithm
77  algorithm.input.set(training.data, trainData)
78  algorithm.input.set(training.dependentVariables, trainDependentVariables)
79 
80  # Build the multiple linear regression model and retrieve the algorithm results
81  trainingResult = algorithm.compute()
82  printNumericTable(trainingResult.get(training.model).getBeta(), "Linear Regression coefficients:")
83 
84 def predictResults(trainData):
85  # Create an algorithm object to predict values of multiple linear regression
86  algorithm = prediction.Batch()
87 
88  # Pass a testing data set and the trained model to the algorithm
89  algorithm.input.setTable(prediction.data, trainData)
90  algorithm.input.setModel(prediction.model, trainingResult.get(training.model))
91 
92  # Predict values of multiple linear regression and retrieve the algorithm results
93  predictionResult = algorithm.compute()
94  return predictionResult.get(prediction.prediction)
95 
96 def predictReducedModelResults(trainData):
97  model = trainingResult.get(training.model)
98 
99  betas = model.getBeta()
100  nBetas = model.getNumberOfBetas()
101 
102  j1 = 2
103  j2 = 10
104  savedBeta = [None] * (nBetas * nDependentVariables)
105 
106  block = BlockDescriptor()
107  betas.getBlockOfRows(0, nDependentVariables, readWrite, block)
108  pBeta = block.getArray().flatten()
109 
110  for i in range(0, nDependentVariables):
111  savedBeta[nDependentVariables * i + j1] = pBeta[nDependentVariables * i + j1]
112  savedBeta[nDependentVariables * i + j2] = pBeta[nDependentVariables * i + j2]
113  pBeta[nDependentVariables * i + j1] = 0
114  pBeta[nDependentVariables * i + j2] = 0
115  betas.releaseBlockOfRows(block)
116 
117  predictedResults = predictResults(trainData)
118 
119  block = BlockDescriptor()
120  betas.getBlockOfRows(0, nDependentVariables, readWrite, block)
121  pBeta = block.getArray().flatten()
122 
123  savedBeta = [None] * nBetas * nDependentVariables
124  for i in range(0, nDependentVariables):
125  pBeta[nDependentVariables * i + j1] = savedBeta[nDependentVariables * i + j1]
126  pBeta[nDependentVariables * i + j2] = savedBeta[nDependentVariables * i + j2]
127  betas.releaseBlockOfRows(block)
128  return predictedResults
129 
130 def testModelQuality():
131  global trainingResult, qmsResult
132 
133  predictedResults = predictResults(trainData)
134  printNumericTable(trainDependentVariables, "Expected responses (first 20 rows):", 20)
135  printNumericTable(predictedResults, "Predicted responses (first 20 rows):", 20)
136 
137  model = trainingResult.get(linear_regression.training.model)
138  predictedReducedModelResults = predictReducedModelResults(trainData)
139  printNumericTable(predictedReducedModelResults, "Responses predicted with reduced model (first 20 rows):", 20)
140 
141  # Create a quality metric set object to compute quality metrics of the linear regression algorithm
142  nBetaReducedModel = model.getNumberOfBetas() - 2
143  qualityMetricSet = quality_metric_set.Batch(model.getNumberOfBetas(), nBetaReducedModel)
144  singleBeta = single_beta.Input.downCast(qualityMetricSet.getInputDataCollection().getInput(quality_metric_set.singleBeta))
145  singleBeta.setDataInput(single_beta.expectedResponses, trainDependentVariables)
146  singleBeta.setDataInput(single_beta.predictedResponses, predictedResults)
147  singleBeta.setModelInput(single_beta.model, model)
148 
149  # Set input for a group of betas metrics algorithm
150  groupOfBetas = group_of_betas.Input.downCast(qualityMetricSet.getInputDataCollection().getInput(quality_metric_set.groupOfBetas))
151  groupOfBetas.set(group_of_betas.expectedResponses, trainDependentVariables)
152  groupOfBetas.set(group_of_betas.predictedResponses, predictedResults)
153  groupOfBetas.set(group_of_betas.predictedReducedModelResponses, predictedReducedModelResults)
154 
155  # Compute quality metrics
156  qualityMetricSet.compute()
157 
158  # Retrieve the quality metrics
159  qmsResult = qualityMetricSet.getResultCollection()
160 
161 def printResults():
162  # Print the quality metrics for a single beta
163  print ("Quality metrics for a single beta")
164  result = single_beta.Result.downCast(qmsResult.getResult(quality_metric_set.singleBeta))
165  printNumericTable(result.getResult(single_beta.rms), "Root means square errors for each response (dependent variable):")
166  printNumericTable(result.getResult(single_beta.variance), "Variance for each response (dependent variable):")
167  printNumericTable(result.getResult(single_beta.zScore), "Z-score statistics:")
168  printNumericTable(result.getResult(single_beta.confidenceIntervals), "Confidence intervals for each beta coefficient:")
169  printNumericTable(result.getResult(single_beta.inverseOfXtX), "Inverse(Xt * X) matrix:")
170 
171  coll = result.getResultDataCollection(single_beta.betaCovariances)
172  for i in range(0, coll.size()):
173  message = "Variance-covariance matrix for betas of " + str(i) + "-th response\n"
174  betaCov = result.get(single_beta.betaCovariances, i)
175  printNumericTable(betaCov, message)
176 
177  # Print quality metrics for a group of betas
178  print ("Quality metrics for a group of betas")
179  result = group_of_betas.Result.downCast(qmsResult.getResult(quality_metric_set.groupOfBetas))
180 
181  printNumericTable(result.get(group_of_betas.expectedMeans), "Means of expected responses for each dependent variable:", 0, 0, 20)
182  printNumericTable(result.get(group_of_betas.expectedVariance), "Variance of expected responses for each dependent variable:", 0, 0, 20)
183  printNumericTable(result.get(group_of_betas.regSS), "Regression sum of squares of expected responses:", 0, 0, 20)
184  printNumericTable(result.get(group_of_betas.resSS), "Sum of squares of residuals for each dependent variable:", 0, 0, 20)
185  printNumericTable(result.get(group_of_betas.tSS), "Total sum of squares for each dependent variable:", 0, 0, 20)
186  printNumericTable(result.get(group_of_betas.determinationCoeff), "Determination coefficient for each dependent variable:", 0, 0, 20)
187  printNumericTable(result.get(group_of_betas.fStatistics), "F-statistics for each dependent variable:", 0, 0, 20)
188 
189 if __name__ == "__main__":
190 
191  # Initialize FileDataSource<CSVFeatureManager> to retrieve the input data from a .csv file
192  dataSource = FileDataSource(trainDatasetFileName,
193  DataSourceIface.notAllocateNumericTable,
194  DataSourceIface.doDictionaryFromContext)
195 
196  # Create Numeric Tables for data and values for dependent variable
197  trainData = HomogenNumericTable(nFeatures, 0, NumericTableIface.doNotAllocate)
198  trainDependentVariables = HomogenNumericTable(nDependentVariables, 0, NumericTableIface.doNotAllocate)
199  mergedData = MergedNumericTable(trainData, trainDependentVariables)
200 
201  # Retrieve the data from the input file
202  dataSource.loadDataBlock(mergedData)
203 
204  for i in range(0, 2):
205  if i == 0:
206  print ("Train model with normal equation algorithm.")
207  algorithm = training.Batch()
208  trainModel(algorithm)
209  else:
210  print ("Train model with QR algorithm.")
211  algorithm = training.Batch(method=training.qrDense)
212  trainModel(algorithm)
213  testModelQuality()
214  printResults()

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