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

neural_net_dense_batch.py

1 # file: neural_net_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 neural network training and scoring
45 # !*****************************************************************************
46 
47 #
48 
49 
50 #
51 
52 import os
53 import sys
54 
55 import numpy as np
56 
57 from daal.algorithms.neural_networks import initializers
58 from daal.algorithms.neural_networks import layers
59 from daal.algorithms import optimization_solver
60 from daal.algorithms.neural_networks import training, prediction
61 from daal.data_management import NumericTable, HomogenNumericTable
62 
63 utils_folder = os.path.realpath(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
64 if utils_folder not in sys.path:
65  sys.path.insert(0, utils_folder)
66 from utils import printTensors, readTensorFromCSV
67 
68 # Input data set parameters
69 trainDatasetFile = os.path.join("..", "data", "batch", "neural_network_train.csv")
70 trainGroundTruthFile = os.path.join("..", "data", "batch", "neural_network_train_ground_truth.csv")
71 testDatasetFile = os.path.join("..", "data", "batch", "neural_network_test.csv")
72 testGroundTruthFile = os.path.join("..", "data", "batch", "neural_network_test_ground_truth.csv")
73 
74 fc1 = 0
75 fc2 = 1
76 sm1 = 2
77 
78 batchSize = 10
79 
80 def configureNet():
81  # Create layers of the neural network
82  # Create fully-connected layer and initialize layer parameters
83  fullyConnectedLayer1 = layers.fullyconnected.Batch(5)
84  fullyConnectedLayer1.parameter.weightsInitializer = initializers.uniform.Batch(-0.001, 0.001)
85  fullyConnectedLayer1.parameter.biasesInitializer = initializers.uniform.Batch(0, 0.5)
86 
87  # Create fully-connected layer and initialize layer parameters
88  fullyConnectedLayer2 = layers.fullyconnected.Batch(2)
89  fullyConnectedLayer2.parameter.weightsInitializer = initializers.uniform.Batch(0.5, 1)
90  fullyConnectedLayer2.parameter.biasesInitializer = initializers.uniform.Batch(0.5, 1)
91 
92  # Create softmax layer and initialize layer parameters
93  softmaxCrossEntropyLayer = layers.loss.softmax_cross.Batch()
94 
95  # Create configuration of the neural network with layers
96  topology = training.Topology()
97 
98  # Add layers to the topology of the neural network
99  topology.push_back(fullyConnectedLayer1)
100  topology.push_back(fullyConnectedLayer2)
101  topology.push_back(softmaxCrossEntropyLayer)
102  topology.get(fc1).addNext(fc2)
103  topology.get(fc2).addNext(sm1)
104  return topology
105 
106 
107 def trainModel():
108  # Read training data set from a .csv file and create a tensor to store input data
109  trainingData = readTensorFromCSV(trainDatasetFile)
110  trainingGroundTruth = readTensorFromCSV(trainGroundTruthFile, True)
111 
112  sgdAlgorithm = optimization_solver.sgd.Batch(fptype=np.float32)
113 
114  # Set learning rate for the optimization solver used in the neural network
115  learningRate = 0.001
116  sgdAlgorithm.parameter.learningRateSequence = HomogenNumericTable(1, 1, NumericTable.doAllocate, learningRate)
117  # Set the batch size for the neural network training
118  sgdAlgorithm.parameter.batchSize = batchSize
119  sgdAlgorithm.parameter.nIterations = int(trainingData.getDimensionSize(0) / sgdAlgorithm.parameter.batchSize)
120 
121  # Create an algorithm to train neural network
122  net = training.Batch(sgdAlgorithm)
123 
124  sampleSize = trainingData.getDimensions()
125  sampleSize[0] = batchSize
126 
127  # Configure the neural network
128  topology = configureNet()
129  net.initialize(sampleSize, topology)
130 
131  # Pass a training data set and dependent values to the algorithm
132  net.input.setInput(training.data, trainingData)
133  net.input.setInput(training.groundTruth, trainingGroundTruth)
134 
135  # Run the neural network training and retrieve training model
136  trainingModel = net.compute().get(training.model)
137  # return prediction model
138  return trainingModel.getPredictionModel_Float32()
139 
140 
141 def testModel(predictionModel):
142  # Read testing data set from a .csv file and create a tensor to store input data
143  predictionData = readTensorFromCSV(testDatasetFile)
144 
145  # Create an algorithm to compute the neural network predictions
146  net = prediction.Batch()
147 
148  net.parameter.batchSize = predictionData.getDimensionSize(0)
149 
150  # Set input objects for the prediction neural network
151  net.input.setModelInput(prediction.model, predictionModel)
152  net.input.setTensorInput(prediction.data, predictionData)
153 
154  # Run the neural network prediction
155  # and return results of the neural network prediction
156  return net.compute()
157 
158 
159 def printResults(predictionResult):
160  # Read testing ground truth from a .csv file and create a tensor to store the data
161  predictionGroundTruth = readTensorFromCSV(testGroundTruthFile)
162 
163  printTensors(predictionGroundTruth, predictionResult.getResult(prediction.prediction),
164  "Ground truth", "Neural network predictions: each class probability",
165  "Neural network classification results (first 20 observations):", 20)
166 
167 
168 topology = ""
169 if __name__ == "__main__":
170 
171  predictionModel = trainModel()
172 
173  predictionResult = testModel(predictionModel)
174 
175  printResults(predictionResult)

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