torch-som 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
+ SHA256:
3
+ metadata.gz: d44e4671b5a2e86749ec1e11ff05cb811259d9804896f786b18b8768e7d8ef28
4
+ data.tar.gz: 0ac72b332777eeb98e62b1e2193daac3d91499a0c90dd2148a05a261db7f402a
5
+ SHA512:
6
+ metadata.gz: 604fafabcb0312e4cdba6159d2c7fdec9cf4a9d139c1f27daca2d1e58ae61b6ad15ae3b521328ee215696f77f60779e5317f61133d3423ce3c1869c6cbb31ba8
7
+ data.tar.gz: d978191e62445d227aad144350da56414baad9b87ffebe1b1d365f58403b78773ff22f866af7622b1bf6c4fd8a6377ac4973c6713e92b394ffb114969f2772a7
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
data/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-10-26
4
+
5
+ - Initial release
6
+ - SOM class
7
+ - Monotonic descent for ratios
8
+ - Basic example inspired by https://codesachin.wordpress.com/2015/11/28/self-organizing-maps-with-googles-tensorflow/
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in torch-som.gemspec
6
+ gemspec
7
+
8
+ gem 'matplotlib'
9
+ gem 'numpy'
10
+ gem 'tqdm'
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Ivan Razuvaev
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,39 @@
1
+ # Torch::Som
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/torch/som`. 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 'torch-som'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install torch-som
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. 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 the created tag, 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]/torch-som.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/example.rb ADDED
@@ -0,0 +1,51 @@
1
+ require 'optparse'
2
+ require 'torch/som'
3
+ require 'csv'
4
+ require 'matplotlib/pyplot'
5
+ require 'numpy'
6
+ require 'tqdm'
7
+
8
+ options = {
9
+ x: 20,
10
+ y: 10,
11
+ iterations: 100,
12
+ output: 'output.png'
13
+ }
14
+
15
+ optparser = OptionParser.new do |opts|
16
+ opts.banner = "bundle exec ruby #{__FILE__} [OPTIONS]"
17
+ opts.on('-x X', Integer, "X resolution of map (default: #{options[:x]})")
18
+ opts.on('-y Y', Integer, "Y resolution of map (default: #{options[:x]})")
19
+ opts.on('-o', '--output FILE', "Output map picture filename (default: #{options[:output]})")
20
+ opts.on('-n', '--iterations NUM', Integer, "Number of iterations (default: #{options[:iterations]})")
21
+ end.parse!(into: options)
22
+
23
+ input = [
24
+ [0.0, 0.0, 0.0],
25
+ [0.0, 0.0, 1.0],
26
+ [0.0, 0.0, 0.5],
27
+ [0.125, 0.529, 1.0],
28
+ [0.33, 0.4, 0.67],
29
+ [0.6, 0.5, 1.0],
30
+ [0.0, 1.0, 0.0],
31
+ [1.0, 0.0, 0.0],
32
+ [0.0, 1.0, 1.0],
33
+ [1.0, 0.0, 1.0],
34
+ [1.0, 1.0, 0.0],
35
+ [1.0, 1.0, 1.0],
36
+ [0.33, 0.33, 0.33],
37
+ [0.5, 0.5, 0.5],
38
+ [0.66, 0.66, 0.66]
39
+ ]
40
+
41
+ som = Torch::NN::SOM.new(
42
+ options[:x],
43
+ options[:y],
44
+ dim: input.first.size, iterations: options[:iterations]
45
+ )
46
+ som.fit input
47
+ #som.fit input, progress: [:with_progress, {desc: "Fitting"}]
48
+
49
+ plt = Matplotlib::Pyplot
50
+ plt.imshow Numpy.asarray(som.weights_2d.to_a)
51
+ plt.savefig options[:output]
@@ -0,0 +1,17 @@
1
+ require 'torch-rb'
2
+
3
+ module Torch
4
+ module NN
5
+ class SelfOrganizedMap < Torch::NN::Module
6
+ module Descent
7
+ class Base
8
+ attr_reader :iterations
9
+
10
+ def call(step_number = nil)
11
+ raise NotImplementedError
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,31 @@
1
+ require_relative 'base'
2
+
3
+ module Torch
4
+ module NN
5
+ class SelfOrganizedMap < Torch::NN::Module
6
+ module Descent
7
+ class Monotonic < Base
8
+ def initialize(initial:, iterations:)
9
+ raise ArgumentError, "Iterations number must be a positive integer" unless iterations.is_a?(Integer) && iterations > 0
10
+ @iterations = iterations
11
+
12
+ raise ArgumentError, "Initial value must be a positive integer" unless initial.is_a?(Numeric) && initial > 0
13
+ @initial = initial
14
+ @step_number = 0
15
+ end
16
+
17
+ def call(step_number = nil)
18
+ if step_number
19
+ raise ArgumentError, "Step number must be an integer >= 0" unless step_number.is_a?(Integer) && step_number >= 0
20
+ @step_number = step_number
21
+ end
22
+ res = @initial * (1.0 - @step_number.to_f / @iterations)
23
+ @step_number += 1 if @step_number < @iterations
24
+
25
+ res
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'torch-rb'
4
+
5
+ module Torch
6
+ module NN
7
+ class SelfOrganizedMap < Torch::NN::Module
8
+ VERSION = "0.1.0"
9
+ end
10
+ end
11
+ end
data/lib/torch/som.rb ADDED
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "som/version"
4
+ require_relative "som/descent/monotonic"
5
+
6
+ module Torch
7
+ module NN
8
+ class SelfOrganizedMap < Torch::NN::Module
9
+ attr_reader :weights, :node_coordinates
10
+
11
+ def initialize(
12
+ x, y,
13
+ dim:,
14
+ alpha: nil, sigma: nil,
15
+ iterations: nil
16
+ )
17
+ super()
18
+
19
+ raise ArgumentError, "X must be a positive integer" unless x.is_a?(Integer) && x > 0
20
+ @x = x
21
+
22
+ raise ArgumentError, "Y must be a positive integer" unless y.is_a?(Integer) && y > 0
23
+ @y = y
24
+
25
+ raise ArgumentError, "Dimension must be a positive integer" unless dim.is_a?(Integer) && dim > 0
26
+ @dim = dim
27
+
28
+ unless alpha.nil? or alpha.is_a?(Descent::Base)
29
+ raise ArgumentError, "alpha(t) must be a Descent::Base subclass"
30
+ end
31
+
32
+ unless sigma.nil? or sigma.is_a?(Descent::Base)
33
+ raise ArgumentError, "sigma(t) must be a Descent::Base subclass"
34
+ end
35
+
36
+ if iterations.nil? && (alpha.nil? or sigma.nil?)
37
+ raise ArgumentError, "Iterations number must be provided if no alpha(t) or sigma(t) given"
38
+ end
39
+
40
+ if iterations && (alpha or sigma)
41
+ raise ArgumentError, "Steps must not be provided if alpha(t) or sigma(t) given"
42
+ end
43
+
44
+ if alpha&.iterations && sigma&.iterations && alpha.iterations != sigma.iterations
45
+ raise ArgumentError, "alpha(t) and sigma(t) are designed for different iterations count"
46
+ end
47
+
48
+ @steps = alpha&.iterations || sigma&.iterations || iterations
49
+
50
+ @alpha_t = alpha || Descent::Monotonic.new(initial: 0.25, iterations: @steps)
51
+ @sigma_t = sigma || Descent::Monotonic.new(initial: [@x, @y].max / 2.0, iterations: @steps)
52
+
53
+ @weights = Torch.rand(@x * @y, @dim)
54
+ @meter = Torch::NN::PairwiseDistance.new
55
+
56
+ @node_coordinates = Torch.tensor(@x.times.to_a.product(@y.times.to_a), dtype: :long)
57
+ end
58
+
59
+ def forward(x, step_number = nil)
60
+ x = tensor!(x)
61
+ input = Torch.stack(Array.new(@x * @y) { x })
62
+
63
+ bmu_1d_index = @meter.(input, @weights).argmin(dim: 0).item
64
+ bmu_2d_index = Torch.tensor([bmu_1d_index.div(@y), bmu_1d_index % @y])
65
+
66
+ alpha = @alpha_t.(step_number)
67
+ sigma = @sigma_t.(step_number)
68
+
69
+ dists = Torch.stack(Array.new(@x * @y) { bmu_2d_index }) - @node_coordinates
70
+ sq_dists = (dists * dists).sum(dim: 1)
71
+
72
+ h = (sq_dists / 2.0 / sigma / sigma).neg.exp * alpha
73
+
74
+ delta = Torch.einsum 'ij,i->ij', [input - @weights, h]
75
+ @weights += delta
76
+ end
77
+
78
+ def locations_for(vectors)
79
+ vectors.map do |x|
80
+ bmu_1d_index = @meter.(tensor!(x), @weights).argmin(dim: 0).item
81
+ [bmu_1d_index.div(@y), bmu_1d_index % @y]
82
+ end
83
+ end
84
+
85
+ def fit(vectors, progress: [:itself])
86
+ @steps.times.public_send(*progress).each do |i|
87
+ vectors.each do |x|
88
+ forward x, i
89
+ end
90
+ end
91
+
92
+ locations_for vectors
93
+ end
94
+
95
+ def weights_2d
96
+ @weights.view(@x, @y, @dim)
97
+ end
98
+
99
+ private
100
+ def tensor!(x)
101
+ x.is_a?(Tensor) ? x : Torch.tensor(x)
102
+ end
103
+ end
104
+
105
+ SOM = SelfOrganizedMap
106
+ end
107
+ end
data/torch-som.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/torch/som/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "torch-som"
7
+ spec.version = Torch::NN::SelfOrganizedMap::VERSION
8
+ spec.authors = ["Ivan Razuvaev"]
9
+ spec.email = ["team@orlando-labs.com"]
10
+
11
+ spec.summary = "Self-Organized Map implementation using torch-rb"
12
+ spec.description = "Self-Organized Map implementation using torch-rb"
13
+ spec.homepage = "https://github.com/orlando-labs/torch-som"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.6.0")
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
20
+
21
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
23
+ end
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.add_dependency "torch-rb", "~> 0.8.0"
27
+ end
metadata ADDED
@@ -0,0 +1,70 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: torch-som
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ivan Razuvaev
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-10-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: torch-rb
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.8.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.8.0
27
+ description: Self-Organized Map implementation using torch-rb
28
+ email:
29
+ - team@orlando-labs.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".gitignore"
35
+ - CHANGELOG.md
36
+ - Gemfile
37
+ - LICENSE.txt
38
+ - README.md
39
+ - example.rb
40
+ - lib/torch/som.rb
41
+ - lib/torch/som/descent/base.rb
42
+ - lib/torch/som/descent/monotonic.rb
43
+ - lib/torch/som/version.rb
44
+ - torch-som.gemspec
45
+ homepage: https://github.com/orlando-labs/torch-som
46
+ licenses:
47
+ - MIT
48
+ metadata:
49
+ homepage_uri: https://github.com/orlando-labs/torch-som
50
+ source_code_uri: https://github.com/orlando-labs/torch-som
51
+ post_install_message:
52
+ rdoc_options: []
53
+ require_paths:
54
+ - lib
55
+ required_ruby_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: 2.6.0
60
+ required_rubygems_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: '0'
65
+ requirements: []
66
+ rubygems_version: 3.2.15
67
+ signing_key:
68
+ specification_version: 4
69
+ summary: Self-Organized Map implementation using torch-rb
70
+ test_files: []