sabina 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +10 -0
  3. data/.rspec +2 -0
  4. data/.travis.yml +16 -0
  5. data/CODE_OF_CONDUCT.md +49 -0
  6. data/Gemfile +13 -0
  7. data/LICENSE.txt +21 -0
  8. data/README.md +201 -0
  9. data/Rakefile +4 -0
  10. data/examples/example_ae_01/ae_learning_process.gif +0 -0
  11. data/examples/example_ae_01/ae_original_data.png +0 -0
  12. data/examples/example_ae_01/main.rb +123 -0
  13. data/examples/example_ae_01/training_data.csv +821 -0
  14. data/examples/example_mp_01/main.rb +158 -0
  15. data/examples/example_mp_01/mp_learning_process.gif +0 -0
  16. data/examples/example_mp_01/mp_training_data.png +0 -0
  17. data/examples/example_mp_01/training_data.csv +601 -0
  18. data/examples/example_mp_02/main.rb +170 -0
  19. data/examples/example_mp_02/mp_learning_process.gif +0 -0
  20. data/examples/example_mp_02/mp_training_data.png +0 -0
  21. data/examples/example_mp_02/training_data.csv +821 -0
  22. data/lib/sabina/auto_encoder.rb +46 -0
  23. data/lib/sabina/configuration.rb +41 -0
  24. data/lib/sabina/layer/ae_hidden_layer.rb +10 -0
  25. data/lib/sabina/layer/ae_input_layer.rb +4 -0
  26. data/lib/sabina/layer/ae_output_layer.rb +10 -0
  27. data/lib/sabina/layer/base_layer.rb +33 -0
  28. data/lib/sabina/layer/mp_hidden_layer.rb +4 -0
  29. data/lib/sabina/layer/mp_input_layer.rb +4 -0
  30. data/lib/sabina/layer/mp_output_layer.rb +12 -0
  31. data/lib/sabina/layer.rb +11 -0
  32. data/lib/sabina/multilayer_perceptron.rb +135 -0
  33. data/lib/sabina/sparse_auto_encoder.rb +49 -0
  34. data/lib/sabina/util.rb +11 -0
  35. data/lib/sabina/version.rb +3 -0
  36. data/lib/sabina.rb +17 -0
  37. data/sabina.gemspec +37 -0
  38. metadata +124 -0
@@ -0,0 +1,46 @@
1
+ module Sabina
2
+ class AutoEncoder < MultilayerPerceptron
3
+
4
+ def self.load_csv(file_name)
5
+ table = CSV.table(file_name)
6
+ table.map do |data|
7
+ x = (data.size-1).times.map { |d| data["x#{d}".to_sym] }
8
+ { :x => x, :d => x }
9
+ end
10
+ end
11
+
12
+ # Check if `@layers` is valid.
13
+ def check_layers
14
+ super
15
+
16
+ if layers.size != 3
17
+ raise "The number of layers must be three."
18
+ end
19
+
20
+ if layers.first.size != layers.last.size
21
+ raise "The number of units of the input layer must be equal to that of the output layer."
22
+ end
23
+ end
24
+
25
+ # Error function (a example of squared error)
26
+ def error(test_data)
27
+ d = Matrix.columns( test_data.map { |data| data[:d] } )
28
+ y = propagate_forward(d)
29
+ (d - y).to_a.flatten.inject(0.0) { |sum, v| sum + v**2 }
30
+ end
31
+
32
+ def next_input_data(input_data)
33
+ x = Matrix.columns( input_data.map { |data| data[:x] } )
34
+ propagate_forward(x)
35
+ @Z[1].t.to_a.map do |z|
36
+ { :x => z, :d => z }
37
+ end
38
+ end
39
+
40
+ # Update the weights of this auto-encoder.
41
+ def update
42
+ super
43
+ @layers[2].W = Marshal.load(Marshal.dump(@layers[1].W.t))
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,41 @@
1
+ module Sabina
2
+ module Configuration
3
+
4
+ OPTIONS_KEYS = [
5
+ :layers,
6
+ :mini_batch_size,
7
+ :training_data,
8
+ :learning_rate,
9
+ ].freeze
10
+
11
+ DEFAULTS = {
12
+ :layers => [
13
+ Sabina::Layer::MPInputLayer.new(1),
14
+ Sabina::Layer::MPHiddenLayer.new(1),
15
+ Sabina::Layer::MPOutputLayer.new(1)
16
+ ],
17
+ :mini_batch_size => 10,
18
+ :training_data => [{:x => [0], :d => [0]}],
19
+ :learning_rate => 0.01,
20
+ }
21
+
22
+ attr_accessor *OPTIONS_KEYS
23
+
24
+ # This method is used for setting configuration options.
25
+ def configure
26
+ yield self
27
+ end
28
+
29
+ # Create a hash of options.
30
+ def options
31
+ Hash[*OPTIONS_KEYS.map{ |key| [key, send(key)] }.flatten(1)]
32
+ end
33
+
34
+ # Reset all options to their default values.
35
+ def reset
36
+ DEFAULTS.each do |option, default|
37
+ self.send("#{option}=".to_sym, default)
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,10 @@
1
+ module Sabina::Layer
2
+ class AEHiddenLayer < BaseLayer
3
+
4
+ def initialize(size)
5
+ super
6
+ @f = ->(x){ x }
7
+ @f_ = ->(_){ 1.0 }
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,4 @@
1
+ module Sabina::Layer
2
+ class AEInputLayer < BaseLayer
3
+ end
4
+ end
@@ -0,0 +1,10 @@
1
+ module Sabina::Layer
2
+ class AEOutputLayer < BaseLayer
3
+
4
+ def initialize(size)
5
+ super
6
+ @f = ->(x){ x }
7
+ @f_ = ->(_){ 1.0 }
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,33 @@
1
+ module Sabina::Layer
2
+ class BaseLayer
3
+ attr_reader :size
4
+ attr_accessor :b, :W, :I, :J
5
+
6
+ def initialize(size)
7
+ @size = size
8
+ @f = ->(x){ 1.0 / (1.0 + Math.exp(-x)) }
9
+ @f_ = ->(x){ @f[x]*(1.0 - @f[x]) }
10
+ end
11
+
12
+ # Initialize the weights of this layer.
13
+ def init_weight
14
+ # (J, 1)
15
+ @b = Matrix.columns([Array.new(@size) { 0.0 }])
16
+
17
+ # (J, I)
18
+ @W = Array.new(@J) do
19
+ Array.new(@I) { Sabina::Util.box_muller }
20
+ end.tap { |ary| break Matrix[*ary] }
21
+ end
22
+
23
+ # An activation function
24
+ def activate(u_ary)
25
+ u_ary.map { |u| @f[u] }
26
+ end
27
+
28
+ # Differentiation of activation function
29
+ def activate_(u_ary)
30
+ u_ary.map { |u| @f_[u] }
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,4 @@
1
+ module Sabina::Layer
2
+ class MPHiddenLayer < BaseLayer
3
+ end
4
+ end
@@ -0,0 +1,4 @@
1
+ module Sabina::Layer
2
+ class MPInputLayer < BaseLayer
3
+ end
4
+ end
@@ -0,0 +1,12 @@
1
+ module Sabina::Layer
2
+ class MPOutputLayer < BaseLayer
3
+
4
+ # softmax function
5
+ def activate(u_ary)
6
+ sum = u_ary.inject(0.0) { |s, u| s + Math.exp(u) }
7
+ u_ary.map do |u|
8
+ Math.exp(u) / sum
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,11 @@
1
+ module Sabina
2
+ module Layer
3
+ autoload :MPInputLayer, "sabina/layer/mp_input_layer"
4
+ autoload :MPHiddenLayer, "sabina/layer/mp_hidden_layer"
5
+ autoload :MPOutputLayer, "sabina/layer/mp_output_layer"
6
+
7
+ autoload :AEInputLayer, "sabina/layer/ae_input_layer"
8
+ autoload :AEHiddenLayer, "sabina/layer/ae_hidden_layer"
9
+ autoload :AEOutputLayer, "sabina/layer/ae_output_layer"
10
+ end
11
+ end
@@ -0,0 +1,135 @@
1
+ module Sabina
2
+ class MultilayerPerceptron
3
+ attr_accessor *Configuration::OPTIONS_KEYS
4
+ LAMBDA = 0.001
5
+ MU = 0.5
6
+
7
+ def self.load_csv(file_name)
8
+ table = CSV.table(file_name)
9
+ k = table[:label].max + 1
10
+ table.map do |data|
11
+ x = (data.size-1).times.map { |d| data["x#{d}".to_sym] }
12
+ d = Array.new(k) { |i| i == data[:label] ? 1 : 0 }
13
+ { :x => x, :d => d }
14
+ end
15
+ end
16
+
17
+ def initialize(options = {})
18
+ load_config(options)
19
+ check_layers
20
+ @L = @layers.size - 1
21
+ @K = @layers.last.size
22
+ @delta_W_prev = []
23
+ @delta_b_prev = []
24
+
25
+ @layers[0].J = @layers[0].size
26
+ (1..@L).each do |j|
27
+ @layers[j].I = @layers[j-1].size
28
+ @layers[j].J = @layers[j].size
29
+ @layers[j].init_weight
30
+ @delta_W_prev[j] = Marshal.load(Marshal.dump(@layers[j].W * 0.0))
31
+ @delta_b_prev[j] = Marshal.load(Marshal.dump(@layers[j].b * 0.0))
32
+ end
33
+
34
+ @mini_batches =
35
+ @training_data.shuffle
36
+ .each_slice(@mini_batch_size).to_a
37
+ end
38
+
39
+ # Load the configuration.
40
+ def load_config(options = {})
41
+ merged_options = Sabina.options.merge(options)
42
+ Configuration::OPTIONS_KEYS.each do |key|
43
+ send("#{key}=".to_sym, merged_options[key])
44
+ end
45
+ end
46
+
47
+ # Check if `@layers` is valid.
48
+ def check_layers
49
+ if layers.size < 3
50
+ raise "The number of layers size must be more than three."
51
+ end
52
+ end
53
+
54
+ # Error function (a example of cross entropy)
55
+ def error(test_data)
56
+ x = Matrix.columns( test_data.map { |data| data[:x] } )
57
+ y = propagate_forward(x)
58
+ test_data.each_with_index.inject(0.0) do |mn, (data, n)|
59
+ mn + data[:d].each_with_index.inject(0.0) do |mk, (d, k)|
60
+ mk - d * Math.log(y[k, n])
61
+ end
62
+ end
63
+ end
64
+
65
+ # A learning step consists of
66
+ # a forward propagation, a backward propagation
67
+ # and updating the weights of this multi-layer perceptron.
68
+ def learn
69
+ @mini_batches.each do |mini_batch|
70
+ @X = Matrix.columns( mini_batch.map { |data| data[:x] } ) # (Dim, N)
71
+ @D = Matrix.columns( mini_batch.map { |data| data[:d] } ) # (Dim, N)
72
+
73
+ propagate_forward(@X)
74
+ propagate_backward
75
+ update
76
+ end
77
+ end
78
+
79
+ # Input values are propagated forward.
80
+ def propagate_forward(x_mat)
81
+ @X = x_mat
82
+ @N = @X.column_size
83
+ @Z, @U = [], []
84
+
85
+ # l = 0
86
+ @Z[0] = @X
87
+
88
+ # l = 1..L
89
+ ones = Matrix[Array.new(@N) { 1.0 }]
90
+ (1..@L).each do |l|
91
+ @U[l] = @layers[l].W*@Z[l-1] + @layers[l].b*ones
92
+ @Z[l] = Matrix.columns( @U[l].t.to_a.map { |u| @layers[l].activate(u) } )
93
+ end
94
+
95
+ # Oputput (K, N)
96
+ @Y = @Z[@L]
97
+ end
98
+
99
+ # Training errors are propagated backwards.
100
+ def propagate_backward
101
+ @Delta = []
102
+
103
+ # l = L
104
+ @Delta[@L] = @Y - @D
105
+
106
+ # l = (L-1)..1
107
+ [*(1...@L)].reverse.each do |l|
108
+ f_u = Matrix.columns( @U[l].t.to_a.map { |u| @layers[l].activate_(u) } )
109
+ w_d = @layers[l+1].W.t * @Delta[l+1]
110
+ @Delta[l] = @layers[l].J.times.map do |j|
111
+ @N.times.map do |n|
112
+ f_u[j, n] * w_d[j, n]
113
+ end
114
+ end.tap { |ary| break Matrix[*ary] }
115
+ end
116
+ end
117
+
118
+ # Update the weights of this multi-layer perceptron.
119
+ def update
120
+ ones = Matrix.columns( [Array.new(@N) { 1.0 }] )
121
+ (1..@L).each do |l|
122
+ delta_W = ( MU*@delta_W_prev[l] ) -
123
+ @learning_rate*( (@Delta[l] * @Z[l-1].t / @N) + LAMBDA*@layers[l].W )
124
+ delta_b = ( MU*@delta_b_prev[l] ) -
125
+ @learning_rate*( @Delta[l] * ones )
126
+
127
+ @delta_W_prev[l] = Marshal.load(Marshal.dump(delta_W))
128
+ @delta_b_prev[l] = Marshal.load(Marshal.dump(delta_b))
129
+
130
+ @layers[l].W = @layers[l].W + delta_W
131
+ @layers[l].b = @layers[l].b + delta_b
132
+ end
133
+ end
134
+ end
135
+ end
@@ -0,0 +1,49 @@
1
+ module Sabina
2
+ class SparseAutoEncoder < AutoEncoder
3
+ BETA = 0.1
4
+
5
+ def initialize(options = {})
6
+ super
7
+
8
+ @RHO_const = Matrix[Array.new(@layers[1].J) { 0.05 }]
9
+ @RHO_prev = Matrix[Array.new(@layers[1].J) { 1.0 }]
10
+ end
11
+
12
+ # Errors are propagated backwards.
13
+ def propagate_backward
14
+ calc_rho
15
+ @Delta = []
16
+
17
+ # l = L
18
+ @Delta[@L] = @Y - @D
19
+
20
+ # l = 1
21
+ l = 1
22
+ f_u = Matrix.columns( @U[l].t.to_a.map { |u| @layers[l].activate_(u) } )
23
+ w_d = @layers[l+1].W.t * @Delta[l+1]
24
+ sps = @layers[l].J.times.map do |j|
25
+ ((1.0 - @RHO_const[0, j]) / (1.0 - @RHO[0, j])) -
26
+ (@RHO_const[0, j] / @RHO[0, j])
27
+ end.tap do |ary|
28
+ ary = ary.map { |v| v > 1e10 ? 1e10 : v }
29
+ break Matrix.columns(Array.new(@N) { ary })
30
+ end
31
+ w_d_s = w_d + BETA*sps
32
+
33
+ @Delta[l] = @layers[l].J.times.map do |j|
34
+ @N.times.map do |n|
35
+ f_u[j, n] * w_d_s[j, n]
36
+ end
37
+ end.tap { |ary| break Matrix[*ary] }
38
+ end
39
+
40
+ # Calculate average activities
41
+ def calc_rho
42
+ @RHO = @Z[1].to_a.map do |z_ary|
43
+ z_ary.inject(0.0, :+)
44
+ end.tap { |ary| break Matrix[ary] / @N }
45
+
46
+ @RHO = 0.9*@RHO_prev + 0.1*@RHO
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,11 @@
1
+ module Sabina
2
+ module Util
3
+ def box_muller(s = 1.0)
4
+ r_1 = rand
5
+ r_2 = rand
6
+ s * Math.sqrt(-2*Math.log(r_1)) * Math.cos(2*Math::PI*r_2)
7
+ end
8
+
9
+ module_function :box_muller
10
+ end
11
+ end
@@ -0,0 +1,3 @@
1
+ module Sabina
2
+ VERSION = "0.1.0"
3
+ end
data/lib/sabina.rb ADDED
@@ -0,0 +1,17 @@
1
+ require 'matrix'
2
+ require 'csv'
3
+
4
+ require "sabina/version"
5
+ require "sabina/util"
6
+ require "sabina/layer"
7
+ require "sabina/layer/base_layer"
8
+ require "sabina/configuration"
9
+ require "sabina/multilayer_perceptron"
10
+ require "sabina/auto_encoder"
11
+ require "sabina/sparse_auto_encoder"
12
+
13
+ module Sabina
14
+ extend Configuration
15
+ end
16
+
17
+ Sabina.reset
data/sabina.gemspec ADDED
@@ -0,0 +1,37 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'sabina/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "sabina"
8
+ spec.version = Sabina::VERSION
9
+ spec.authors = ["seinosuke"]
10
+ spec.email = ["seinosuke.3606@gmail.com"]
11
+
12
+ spec.summary = %q{This gem is a machine learning library.}
13
+ spec.homepage = "https://github.com/seinosuke/sabina"
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'] = "TODO: Set to 'http://mygemserver.com'"
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.11"
30
+ spec.add_development_dependency "rake", "~> 10.0"
31
+ spec.add_development_dependency "rspec", "~> 3.0"
32
+
33
+ spec.description = <<-END
34
+ Sabina is a machine learning library.
35
+ This gem provides tools for Multi-Layer Perceptrons and Auto-Encoders.
36
+ END
37
+ end
metadata ADDED
@@ -0,0 +1,124 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sabina
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - seinosuke
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-04-19 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.11'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.11'
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: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ description: |
56
+ Sabina is a machine learning library.
57
+ This gem provides tools for Multi-Layer Perceptrons and Auto-Encoders.
58
+ email:
59
+ - seinosuke.3606@gmail.com
60
+ executables: []
61
+ extensions: []
62
+ extra_rdoc_files: []
63
+ files:
64
+ - ".gitignore"
65
+ - ".rspec"
66
+ - ".travis.yml"
67
+ - CODE_OF_CONDUCT.md
68
+ - Gemfile
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - examples/example_ae_01/ae_learning_process.gif
73
+ - examples/example_ae_01/ae_original_data.png
74
+ - examples/example_ae_01/main.rb
75
+ - examples/example_ae_01/training_data.csv
76
+ - examples/example_mp_01/main.rb
77
+ - examples/example_mp_01/mp_learning_process.gif
78
+ - examples/example_mp_01/mp_training_data.png
79
+ - examples/example_mp_01/training_data.csv
80
+ - examples/example_mp_02/main.rb
81
+ - examples/example_mp_02/mp_learning_process.gif
82
+ - examples/example_mp_02/mp_training_data.png
83
+ - examples/example_mp_02/training_data.csv
84
+ - lib/sabina.rb
85
+ - lib/sabina/auto_encoder.rb
86
+ - lib/sabina/configuration.rb
87
+ - lib/sabina/layer.rb
88
+ - lib/sabina/layer/ae_hidden_layer.rb
89
+ - lib/sabina/layer/ae_input_layer.rb
90
+ - lib/sabina/layer/ae_output_layer.rb
91
+ - lib/sabina/layer/base_layer.rb
92
+ - lib/sabina/layer/mp_hidden_layer.rb
93
+ - lib/sabina/layer/mp_input_layer.rb
94
+ - lib/sabina/layer/mp_output_layer.rb
95
+ - lib/sabina/multilayer_perceptron.rb
96
+ - lib/sabina/sparse_auto_encoder.rb
97
+ - lib/sabina/util.rb
98
+ - lib/sabina/version.rb
99
+ - sabina.gemspec
100
+ homepage: https://github.com/seinosuke/sabina
101
+ licenses:
102
+ - MIT
103
+ metadata: {}
104
+ post_install_message:
105
+ rdoc_options: []
106
+ require_paths:
107
+ - lib
108
+ required_ruby_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ required_rubygems_version: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ requirements: []
119
+ rubyforge_project:
120
+ rubygems_version: 2.4.5
121
+ signing_key:
122
+ specification_version: 4
123
+ summary: This gem is a machine learning library.
124
+ test_files: []