1 // Copyright 2016 The TensorFlow Authors. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // ============================================================================= 15 #include "tensorflow/contrib/tensor_forest/hybrid/core/ops/utils.h" 16 17 #include <math.h> 18 #include <vector> 19 20 #include "tensorflow/core/lib/random/philox_random.h" 21 #include "tensorflow/core/lib/random/simple_philox.h" 22 23 namespace tensorflow { 24 namespace tensorforest { 25 26 using tensorflow::Tensor; 27 28 float LeftProbability(const Tensor& point, const Tensor& weight, float bias, 29 int num_features) { 30 const auto p = point.unaligned_flat<float>(); 31 const auto w = weight.unaligned_flat<float>(); 32 float dot_product = 0.0; 33 for (int i = 0; i < num_features; i++) { 34 dot_product += w(i) * p(i); 35 } 36 37 // TODO(thomaswc): At some point we should consider 38 // //learning/logistic/logodds-to-prob.h 39 return 1.0 / (1.0 + exp(-dot_product + bias)); 40 } 41 42 float LeftProbabilityK(const Tensor& point, std::vector<int32> feature_set, 43 const Tensor& weight, float bias, int num_features, 44 int k) { 45 const auto p = point.unaligned_flat<float>(); 46 const auto w = weight.unaligned_flat<float>(); 47 48 float dot_product = 0.0; 49 50 for (int32 i = 0; i < k; i++) { 51 CHECK_LT(feature_set[i], num_features); 52 dot_product += p(feature_set[i]) * w(i); 53 } 54 55 // TODO(thomaswc): At some point we should consider 56 // //learning/logistic/logodds-to-prob.h 57 return 1.0 / (1.0 + exp(-dot_product + bias)); 58 } 59 60 void GetFeatureSet(int32 tree_num, int32 node_num, int32 random_seed, 61 int32 num_features, int32 num_features_to_pick, 62 std::vector<int32>* features) { 63 features->clear(); 64 uint64 seed = node_num ^ (tree_num << 16) ^ random_seed; 65 random::PhiloxRandom rng(seed); 66 for (int i = 0; i < num_features_to_pick; ++i) { 67 // PhiloxRandom returns an array of int32's 68 const random::PhiloxRandom::ResultType rand = rng(); 69 const int32 feature = (rand[0] + rand[1]) % num_features; 70 features->push_back(feature); 71 } 72 } 73 74 } // namespace tensorforest 75 } // namespace tensorflow 76