pmml_consumer 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: 71a1bb8e8baf276924decd5e2a2f1fbe0289cdca
4
+ data.tar.gz: 5bfa9c66b0c34caa5426c76ea9fd1e65d23f381b
5
+ SHA512:
6
+ metadata.gz: 6d8f878175b7df250b8bd6277005c234d009528df8e3f8c62feccfd55d20cee94cd1f467ed44c5bd916da734f856faefff82dda49cdbe2541575a210016fb1d0
7
+ data.tar.gz: dd631650ab36da646d11c6154b610df0a8a2d0f9dad8b14349cd964397f02779acdf8e643964120ad583256870499b9b90e7a6b9338ed740ab02e1d1fd144f68
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.rubocop.yml ADDED
@@ -0,0 +1,4 @@
1
+ LineLength:
2
+ Max: 160
3
+ StringLiterals:
4
+ EnforcedStyle: double_quotes
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.1
4
+ before_install: gem install bundler -v 1.10.3
@@ -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 pmml_consumer.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 romain.sagean
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,43 @@
1
+ # Ruby PMML Consumer
2
+
3
+ Generate a PMML file with your favorite machine learning library and use this gem to read the file and make prediciton in a ruby application. This gem is primarily intended to work with apache spark 1.5 PMML file, so some features from the PMML standard maybe missing.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'pmml_consumer'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install pmml_consumer
20
+
21
+ ## Usage
22
+
23
+ ```ruby
24
+ pmml_string = File.open('my_pmml_file.xml', "rb").read
25
+ predictor = PMMLConsumer.load(pmml_string)
26
+ input = { "feature1" => 1, "feature2" => "banana"}
27
+ puts predictor.predict(input)
28
+ ```
29
+
30
+ ## Development
31
+
32
+ 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.
33
+
34
+ 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).
35
+
36
+ ## Contributing
37
+
38
+ Bug reports and pull requests are welcome on GitHub at https://github.com/hupi-analytics/pmml_consumer. 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.
39
+
40
+
41
+ ## License
42
+
43
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
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 pmml_consumer -I ./lib"
10
+ end
data/bin/console ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "pmml_consumer"
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
+ require "pry"
9
+ 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,50 @@
1
+ require "pmml_consumer/version"
2
+ require "nokogiri"
3
+
4
+ require "pmml_consumer/ml_model"
5
+ require "pmml_consumer/regression_model"
6
+
7
+ begin
8
+ require "pry"
9
+ rescue LoadError
10
+ end
11
+
12
+ module PMMLConsumer
13
+ def self.load(pmml_string, model_name: nil)
14
+ xml = Nokogiri::XML(pmml_string)
15
+
16
+ ml_model = model_node(xml, model_name)
17
+
18
+ case ml_model.name
19
+ when 'RegressionModel'
20
+ RegressionModel.new(ml_model, field_type(xml))
21
+ else
22
+ MLModel.new(ml_model, field_type(xml))
23
+ end
24
+ end
25
+
26
+ def self.field_type(xml)
27
+ xml.xpath("/xmlns:PMML/xmlns:DataDictionary/xmlns:DataField").each_with_object({}) do |child, memo|
28
+ memo[child.attributes["name"].value] = case child.attributes["optype"].value
29
+ when "continuous"
30
+ child.to_h.reject! { |key| %w(name optype).include?(key) }
31
+ when "categorical"
32
+ data_field_h = child.to_h.reject! { |key| %w(name optype).include?(key) }
33
+ data_field_h["values"] = child.xpath("xmlns:Value").map do |cat|
34
+ cat.attributes["value"].value
35
+ end
36
+ data_field_h
37
+ else
38
+ raise "unknow optype: #{child.attributes['optype'].value}"
39
+ end
40
+ end
41
+ end
42
+
43
+ def self.model_node(xml, model_name)
44
+ if model_name.nil?
45
+ xml.xpath("/xmlns:PMML/*[contains(name(), 'Model') or (name() = 'NeuralNetwork') or (name() = 'Scorecard')]").first
46
+ else
47
+ xml.xpath("/xmlns:PMML/*[@modelName='#{model_name}']").first
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,56 @@
1
+ require "nokogiri"
2
+ module PMMLConsumer
3
+ class MLModel
4
+ attr_accessor :model_node, :fields_type
5
+
6
+ def initialize(model_node, field_type)
7
+ @model_node = model_node
8
+ @fields_type = filter_field(field_type)
9
+ @target_fields = target_fields
10
+ end
11
+
12
+ def predict(input)
13
+ raise "not implemented"
14
+ end
15
+
16
+ def cast_input(input)
17
+ @fields_type.each do |field_name, field_type|
18
+ input[field_name] = if input[field_name].nil? && !field_type["missingValueReplacement"].nil?
19
+ field_type["missingValueReplacement"]
20
+ elsif input[field_name].nil? && field_type["missingValueReplacement"].nil?
21
+ raise "value '#{field_name}' not found and no value replacement set"
22
+ else
23
+ case field_type["dataType"]
24
+ when "double"
25
+ input[field_name].to_f
26
+ when "integer"
27
+ input[field_name].to_i
28
+ when "string"
29
+ input[field_name].to_s
30
+ else
31
+ raise "unknow dataType: #{field_type["dataType"]}"
32
+ end
33
+ end
34
+ if field_type["values"].is_a?(Array) && !field_type["values"].include?(input[field_name])
35
+ raise "not a valid value: #{input[field_name]}"
36
+ end
37
+ end
38
+ input
39
+ end
40
+
41
+ def filter_field(field_type)
42
+ @model_node.xpath("xmlns:MiningSchema/xmlns:MiningField").each do |mining_field|
43
+ unless mining_field.attributes["usageType"].nil? || mining_field.attributes["usageType"].value == "active"
44
+ field_type.delete(mining_field.attributes["name"].value)
45
+ end
46
+ end
47
+ field_type
48
+ end
49
+
50
+ def target_fields
51
+ @model_node.xpath("xmlns:MiningSchema/xmlns:MiningField[@usageType='target']").map do |mining_field|
52
+ mining_field["name"]
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,98 @@
1
+ module PMMLConsumer
2
+ class RegressionModel < MLModel
3
+
4
+ def predict(input)
5
+ cast_input(input)
6
+ res = @model_node.xpath("xmlns:RegressionTable").each_with_object({}) do |regression_table, result|
7
+ res_name = regression_table["targetCategory"]
8
+ res_name ||= @model_node["targetFieldName"]
9
+ res_name ||= @target_fields.first
10
+ result[res_name] = regression_table["intercept"].to_f
11
+ regression_table.element_children.each do |predictor|
12
+ case predictor.name
13
+ when "NumericPredictor"
14
+ coefficient = predictor["coefficient"].to_f
15
+ exponent = (predictor["exponent"] || "1").to_i
16
+ result[res_name] += coefficient * (input[predictor["name"]]**exponent)
17
+ when "CategoricalPredictor"
18
+ if predictor["value"] == input[predictor["name"]]
19
+ result[res_name] += predictor["coefficient"].to_f
20
+ end
21
+ when "PredictorTerm"
22
+ coefficient = predictor["coefficient"].to_f
23
+ predictor.element_children.each do |field_ref|
24
+ coefficient *= input[field_ref["field"]]
25
+ end
26
+ result[res_name] += coefficient
27
+ else
28
+ raise "unknow predictor name: #{predictor.name}"
29
+ end
30
+ end
31
+ end
32
+ case @model_node["normalisationMethod"]
33
+ when "softmax"
34
+ softmax(res)
35
+ when "logit"
36
+ logit(res)
37
+ when "probit"
38
+ probit(res)
39
+ when "cloglog"
40
+ cloglog(res)
41
+ when "loglog"
42
+ loglog(res)
43
+ when "cauchit"
44
+ cauchit(res)
45
+ when "exp"
46
+ exp(res)
47
+ when nil, "none"
48
+ else
49
+ raise "unknow normalisation method: #{@model_node["normalisationMethod"]}"
50
+ end
51
+ res
52
+ end
53
+
54
+ def softmax(result)
55
+ if result.count == 1
56
+ 1 / (1 + Math.exp(-result.values.first))
57
+ else
58
+ sum1n = result.values.reduce(:+)
59
+ result.each do |k, v|
60
+ result[k] = Math.exp(v) / sum1n
61
+ end
62
+ end
63
+ end
64
+
65
+ def logit(result)
66
+ result.each do |k, v|
67
+ result[k] = 1 / (1 + Math.exp(-v))
68
+ end
69
+ end
70
+
71
+ def cloglog(result)
72
+ raise "error" if result.count == 1
73
+ result.each do |k, v|
74
+ result[k] = 1 - Math.exp(-Math.exp(v))
75
+ end
76
+ end
77
+
78
+ def loglog(result)
79
+ raise "error" if result.count == 1
80
+ result.each do |k, v|
81
+ result[k] = Math.exp(-Math.exp(-v))
82
+ end
83
+ end
84
+
85
+ def cauchit(result)
86
+ raise "error" if result.count == 1
87
+ result.each do |k, v|
88
+ result[k] = 0.5 + (1 / Math::PI) * Math.atan(v)
89
+ end
90
+ end
91
+
92
+ def exp(result)
93
+ result.each do |k, v|
94
+ result[k] = Math.exp(v)
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,3 @@
1
+ module PMMLConsumer
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,34 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'pmml_consumer/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "pmml_consumer"
8
+ spec.version = PMMLConsumer::VERSION
9
+ spec.authors = ["scauglog"]
10
+ spec.email = ["scauglog@gmail.com"]
11
+
12
+ spec.summary = %q{read a PMML file and use it to make prediction}
13
+ spec.homepage = "https://github.com/hupi-analytics/pmml_consumer"
14
+ spec.license = "MIT"
15
+
16
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
17
+ # delete this section to allow pushing this gem to any host.
18
+ if spec.respond_to?(:metadata)
19
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
20
+ else
21
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
22
+ end
23
+
24
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_development_dependency "bundler", "~> 1.10"
30
+ spec.add_development_dependency "rake", "~> 10.0"
31
+ spec.add_development_dependency "rspec"
32
+ spec.add_development_dependency "pry"
33
+ spec.add_dependency "nokogiri", "~> 1.6"
34
+ end
metadata ADDED
@@ -0,0 +1,131 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pmml_consumer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - scauglog
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2015-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
+ description:
84
+ email:
85
+ - scauglog@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - ".rspec"
92
+ - ".rubocop.yml"
93
+ - ".travis.yml"
94
+ - CODE_OF_CONDUCT.md
95
+ - Gemfile
96
+ - LICENSE.txt
97
+ - README.md
98
+ - Rakefile
99
+ - bin/console
100
+ - bin/setup
101
+ - lib/pmml_consumer.rb
102
+ - lib/pmml_consumer/ml_model.rb
103
+ - lib/pmml_consumer/regression_model.rb
104
+ - lib/pmml_consumer/version.rb
105
+ - pmml_consumer.gemspec
106
+ homepage: https://github.com/hupi-analytics/pmml_consumer
107
+ licenses:
108
+ - MIT
109
+ metadata:
110
+ allowed_push_host: https://rubygems.org
111
+ post_install_message:
112
+ rdoc_options: []
113
+ require_paths:
114
+ - lib
115
+ required_ruby_version: !ruby/object:Gem::Requirement
116
+ requirements:
117
+ - - ">="
118
+ - !ruby/object:Gem::Version
119
+ version: '0'
120
+ required_rubygems_version: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ requirements: []
126
+ rubyforge_project:
127
+ rubygems_version: 2.4.5
128
+ signing_key:
129
+ specification_version: 4
130
+ summary: read a PMML file and use it to make prediction
131
+ test_files: []