random_forester 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 4464cbf26aa7ddb944082197474c6e5fe2c8a122
4
+ data.tar.gz: 8bc005154166a42ce313fb4657fd9b9acf0e4347
5
+ SHA512:
6
+ metadata.gz: 12093b7119a156e2c49d49639a6cb8b3b77abbd2058419800416781e8c08104f65752a0102ad4575cf477af1750eb1033e906602159298cd6b45b492513beabc
7
+ data.tar.gz: d6aefbe4e09e000ce3d26847ff13ccdac1d5f15c00dd082103c563546f554172240510a0f30f3ed6ddfb2ef463599991d3918c79efe1a034bca7728f9dff25b7
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1.2
4
+ before_install: gem install bundler -v 1.10.5
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in random_forester.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 asaf schers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # RandomForester
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/random_forester`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'random_forester'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install random_forester
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/random_forester. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
7
+
8
+ task :console do
9
+ exec "pry -r random_forester -I ./lib"
10
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "random_forester"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "pry"
14
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,16 @@
1
+ class CategoricalPredicate
2
+
3
+ IS_IN = 'isIn'
4
+
5
+ attr_reader :field
6
+
7
+ def initialize(pred_xml)
8
+ @field = pred_xml.xpath('@field').to_s.to_sym
9
+ @array = pred_xml.xpath('Array/text()').to_s.tr('"', '').split(' ')
10
+ @operator = pred_xml.xpath('@booleanOperator').to_s
11
+ end
12
+
13
+ def true?(features)
14
+ @array.include? features[@field] if @operator == IS_IN
15
+ end
16
+ end
@@ -0,0 +1,48 @@
1
+ require 'predicate'
2
+ require 'rubytree'
3
+
4
+ class DecisionTree
5
+ ROOT = 'root'
6
+ LEFT = 'left'
7
+ RIGHT = 'right'
8
+
9
+ attr_reader :root
10
+
11
+ def initialize(tree_xml)
12
+ @id = tree_xml.xpath('@id')
13
+ @root = Tree::TreeNode.new(ROOT)
14
+ set_node(tree_xml.xpath('TreeModel/Node'), @root)
15
+ end
16
+
17
+ def set_node(tree_xml, root)
18
+ root.content = Predicate.new(tree_xml)
19
+
20
+ return if tree_xml.xpath('*').count == 1
21
+
22
+ root << Tree::TreeNode.new(LEFT)
23
+ root << Tree::TreeNode.new(RIGHT)
24
+
25
+ set_node(tree_xml.xpath('*')[1], root[LEFT]) if tree_xml.xpath('*')[1]
26
+ set_node(tree_xml.xpath('*')[2], root[RIGHT]) if tree_xml.xpath('*')[2]
27
+ end
28
+
29
+ def decide(features)
30
+ curr = @root
31
+ while curr.content.decision == ''
32
+ prev = curr
33
+ curr = curr[LEFT] if curr[LEFT] && curr[LEFT].content.true?(features)
34
+ curr = curr[RIGHT] if curr[RIGHT] && curr[RIGHT].content.true?(features)
35
+
36
+ return if no_true_child?(curr, prev)
37
+ end
38
+
39
+ curr.content.decision
40
+ end
41
+
42
+ def no_true_child?(curr, prev)
43
+ return false if (prev.content != curr.content)
44
+ RandomForester.logger.error "Null tree: #{@id}, bad feature: #{curr[LEFT].content.field }"
45
+ true
46
+ end
47
+
48
+ end
@@ -0,0 +1,33 @@
1
+ require 'json'
2
+
3
+ pmml_file = '' #pmml file name
4
+ json = '' #get features json from oscd
5
+
6
+ get_missing_categories(json,pmml_file)
7
+
8
+ def get_category_feature_names(pmml_file)
9
+ xml = RandomForester.get_xml pmml_file;
10
+ features = {}
11
+ xml.xpath("PMML/DataDictionary/*").each { |df| features[df.xpath('@name').to_s] = df.xpath('@dataType').to_s }; nil
12
+ features.select { |_, v| v == 'string' }.keys
13
+ end
14
+
15
+ def get_categories(json, pmml_file)
16
+ curr_features = JSON.parse(json)
17
+ category_features = get_category_feature_names(pmml_file)
18
+ curr_features.select { |k, v| category_features.include?(k)}
19
+ end
20
+
21
+ def get_missing_categories(json, pmml_file)
22
+ categories = get_categories(json, pmml_file)
23
+ categories.each { |k, v|
24
+ next if !!v == v
25
+ category_on_pmml = File.readlines(pmml_file).any?{ |l| l[v.to_s] }
26
+ puts "category: #{k}, value: #{v}" unless category_on_pmml
27
+ }; nil
28
+ end
29
+
30
+
31
+
32
+
33
+
@@ -0,0 +1,19 @@
1
+ class NumericalPredicate
2
+
3
+ GREATER_THAN = 'greaterThan'
4
+ LESS_OR_EQUAL = 'lessOrEqual'
5
+
6
+ attr_reader :field
7
+
8
+ def initialize(pred_xml)
9
+ @field = pred_xml.xpath('@field').to_s.to_sym
10
+ @value = Float(pred_xml.xpath('@value').to_s)
11
+ @operator = pred_xml.xpath('@operator').to_s
12
+ end
13
+
14
+ def true?(features)
15
+ curr_value = Float(features[@field])
16
+ return curr_value > @value if @operator == GREATER_THAN
17
+ curr_value < @value if @operator == LESS_OR_EQUAL
18
+ end
19
+ end
data/lib/predicate.rb ADDED
@@ -0,0 +1,49 @@
1
+ require 'numerical_predicate'
2
+ require 'categorical_predicate'
3
+
4
+ class Predicate
5
+
6
+ attr_reader :decision
7
+
8
+ def initialize(pred_xml)
9
+ @pred_xml = pred_xml.xpath('*')[0]
10
+
11
+ @op = @pred_xml.xpath('@operator').to_s
12
+ @bool_op = @pred_xml.xpath('@booleanOperator').to_s
13
+
14
+ if !@op.empty?
15
+ @pred = NumericalPredicate.new(@pred_xml)
16
+ elsif !@bool_op.empty?
17
+ @pred = CategoricalPredicate.new(@pred_xml)
18
+ end
19
+
20
+ @decision = pred_xml.xpath('@score').to_s
21
+ end
22
+
23
+ def to_s
24
+ @pred_xml.to_s
25
+ end
26
+
27
+ def field
28
+ @pred.field
29
+ end
30
+
31
+ def true?(features)
32
+ return true if @pred.nil?
33
+ return if missing_feature?(features)
34
+ return if nil_feature?(features)
35
+ @pred.true?(features)
36
+ end
37
+
38
+ def missing_feature?(features)
39
+ return false if features.has_key? field
40
+ RandomForester.logger.error "Missing feature #{field}"
41
+ true
42
+ end
43
+
44
+ def nil_feature?(features)
45
+ return false unless features[field].nil?
46
+ RandomForester.logger.error "Feature #{field} value is nil"
47
+ true
48
+ end
49
+ end
@@ -0,0 +1,23 @@
1
+ require 'decision_tree'
2
+
3
+ class RandomForest
4
+
5
+ def initialize(xml)
6
+ xml_trees = xml.xpath('PMML/MiningModel/Segmentation/Segment')
7
+ @decision_trees = xml_trees.collect{ |xml_tree|
8
+ DecisionTree.new(xml_tree)
9
+ }
10
+ end
11
+
12
+ def decisions_count(fearures)
13
+ decisions = @decision_trees.collect { |decision_tree|
14
+ decision_tree.decide(fearures)
15
+ }
16
+ decisions.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }
17
+ end
18
+
19
+ def predict(features)
20
+ decisions_count(features).max_by {|_, v| v }[0]
21
+ end
22
+
23
+ end
@@ -0,0 +1,3 @@
1
+ module RandomForester
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,45 @@
1
+ require 'random_forester/version'
2
+ require 'nokogiri'
3
+ require 'random_forest'
4
+ require 'logger'
5
+ require 'pry'
6
+
7
+ RANDOM_FOREST_MODEL = 'randomForest_Model'
8
+ MODEL_NOT_SUPPORTED_ERROR = 'model not supported'
9
+
10
+ module RandomForester
11
+
12
+ class << self
13
+ attr_writer :logger
14
+
15
+ def logger
16
+ @logger ||= Logger.new($stdout).tap do |log|
17
+ log.progname = self.name
18
+ end
19
+ end
20
+ end
21
+
22
+ def self.get_model(pmml_file_name)
23
+ xml = get_xml(pmml_file_name)
24
+ new_model(xml)
25
+ end
26
+
27
+ def self.new_model(xml)
28
+ case get_model_type(xml)
29
+ when RANDOM_FOREST_MODEL
30
+ RandomForest.new(xml)
31
+ else
32
+ raise MODEL_NOT_SUPPORTED_ERROR
33
+ end
34
+ end
35
+
36
+ def self.get_xml(pmml_file_name)
37
+ pmml_string = File.open(pmml_file_name, 'rb').read
38
+ xml = Nokogiri::XML(pmml_string)
39
+ xml.remove_namespaces!
40
+ end
41
+
42
+ def self.get_model_type(xml)
43
+ xml.xpath("PMML/MiningModel/@modelName").to_s
44
+ end
45
+ end
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'random_forester/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "random_forester"
8
+ spec.version = RandomForester::VERSION
9
+ spec.authors = ["asaf schers"]
10
+ spec.email = ["schers@riskified.com"]
11
+
12
+ spec.summary = %q{Creates a random forest object from a pmml file.}
13
+ spec.homepage = 'https://github.com/asafschers/random_forester'
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
17
+ spec.bindir = "exe"
18
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.10"
22
+ spec.add_development_dependency "rake", "~> 10.0"
23
+ spec.add_development_dependency "rspec"
24
+ spec.add_development_dependency "pry"
25
+ spec.add_dependency "nokogiri", "~> 1.6"
26
+ spec.add_dependency "rubytree"
27
+ end
metadata ADDED
@@ -0,0 +1,147 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: random_forester
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - asaf schers
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-12-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: nokogiri
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '1.6'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '1.6'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubytree
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description:
98
+ email:
99
+ - schers@riskified.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".rspec"
105
+ - ".travis.yml"
106
+ - CODE_OF_CONDUCT.md
107
+ - Gemfile
108
+ - LICENSE.txt
109
+ - README.md
110
+ - Rakefile
111
+ - bin/console
112
+ - bin/setup
113
+ - lib/categorical_predicate.rb
114
+ - lib/decision_tree.rb
115
+ - lib/missing_categories_script.rb
116
+ - lib/numerical_predicate.rb
117
+ - lib/predicate.rb
118
+ - lib/random_forest.rb
119
+ - lib/random_forester.rb
120
+ - lib/random_forester/version.rb
121
+ - random_forester.gemspec
122
+ homepage: https://github.com/asafschers/random_forester
123
+ licenses:
124
+ - MIT
125
+ metadata: {}
126
+ post_install_message:
127
+ rdoc_options: []
128
+ require_paths:
129
+ - lib
130
+ required_ruby_version: !ruby/object:Gem::Requirement
131
+ requirements:
132
+ - - ">="
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ required_rubygems_version: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - ">="
138
+ - !ruby/object:Gem::Version
139
+ version: '0'
140
+ requirements: []
141
+ rubyforge_project:
142
+ rubygems_version: 2.2.2
143
+ signing_key:
144
+ specification_version: 4
145
+ summary: Creates a random forest object from a pmml file.
146
+ test_files: []
147
+ has_rdoc: