ai-neat 0.1

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: 130497fb64c8f6135d4e6ed160700e867bc13dcae5cd3214bd020b55c4bc62bb
4
+ data.tar.gz: 907d43dd6e4b55bfd2e4f3c433902b7c21cd311f6eb45ac5172ad2149a87d57a
5
+ SHA512:
6
+ metadata.gz: bf064d69c97750706cdcf4e081919099e0e857570dbca6398c20ab1fc35e60f5626278bfc952160e7875edc547b600ace3b5b7720d34ad5cf1e1b630343ecb6f
7
+ data.tar.gz: 127b336860c1ceb8dec212866e329473da88dc676b0995f33053d6f5bd1ffde55bc4ee0021b2941c3060359e990ac13c21cfbe9c8ea3b16348a06517a6018bcf
@@ -0,0 +1,18 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 2.7.2
14
+ - name: Run the default task
15
+ run: |
16
+ gem install bundler -v 2.2.4
17
+ bundle install
18
+ bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,10 @@
1
+ Style/StringLiterals:
2
+ Enabled: true
3
+ EnforcedStyle: double_quotes
4
+
5
+ Style/StringLiteralsInInterpolation:
6
+ Enabled: true
7
+ EnforcedStyle: double_quotes
8
+
9
+ Layout/LineLength:
10
+ Max: 120
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders 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, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at sunama.sukrit@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in ai-neat.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 0.80"
data/Gemfile.lock ADDED
@@ -0,0 +1,55 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ ai-neat (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ diff-lcs (1.4.4)
11
+ parallel (1.20.1)
12
+ parser (3.0.0.0)
13
+ ast (~> 2.4.1)
14
+ rainbow (3.0.0)
15
+ rake (13.0.3)
16
+ regexp_parser (2.1.0)
17
+ rexml (3.2.4)
18
+ rspec (3.10.0)
19
+ rspec-core (~> 3.10.0)
20
+ rspec-expectations (~> 3.10.0)
21
+ rspec-mocks (~> 3.10.0)
22
+ rspec-core (3.10.1)
23
+ rspec-support (~> 3.10.0)
24
+ rspec-expectations (3.10.1)
25
+ diff-lcs (>= 1.2.0, < 2.0)
26
+ rspec-support (~> 3.10.0)
27
+ rspec-mocks (3.10.2)
28
+ diff-lcs (>= 1.2.0, < 2.0)
29
+ rspec-support (~> 3.10.0)
30
+ rspec-support (3.10.2)
31
+ rubocop (0.93.1)
32
+ parallel (~> 1.10)
33
+ parser (>= 2.7.1.5)
34
+ rainbow (>= 2.2.2, < 4.0)
35
+ regexp_parser (>= 1.8)
36
+ rexml
37
+ rubocop-ast (>= 0.6.0)
38
+ ruby-progressbar (~> 1.7)
39
+ unicode-display_width (>= 1.4.0, < 2.0)
40
+ rubocop-ast (1.4.1)
41
+ parser (>= 2.7.1.5)
42
+ ruby-progressbar (1.11.0)
43
+ unicode-display_width (1.7.0)
44
+
45
+ PLATFORMS
46
+ arm64-darwin-20
47
+
48
+ DEPENDENCIES
49
+ ai-neat!
50
+ rake (~> 13.0)
51
+ rspec (~> 3.0)
52
+ rubocop (~> 0.80)
53
+
54
+ BUNDLED WITH
55
+ 2.2.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Sukrit Sunama
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,109 @@
1
+ # Ai::Neat
2
+
3
+ This gem is base on [NEAT-JS](https://github.com/ExtensionShoe/NEAT-JS). That have the main purpose to convert the code from javascript to ruby.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'ai-neat'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install ai-neat
20
+
21
+ ## Usage
22
+
23
+ ```
24
+ population_size = 100
25
+
26
+ config = {
27
+ models: [
28
+ { node_count: 5, node_type: :input },
29
+ { node_count: 3, node_type: :output, activationfunc: :softmax }
30
+ ],
31
+ mutation_rate: 0.1,
32
+ crossover_method: :random,
33
+ mutation_method: :random,
34
+ population_size: population_size
35
+ }
36
+
37
+ neat = Ai::Neat::Neat.new(config)
38
+
39
+ scores = population_size.times.map { 0 }
40
+ first_score = 0
41
+
42
+ # Generation
43
+ 100.times.each do |gen|
44
+ scores = population_size.times.map { 0 }
45
+
46
+ # play
47
+ 50.times.each do
48
+ inputs = 5.times.map { rand(-1.0..1.0) }
49
+
50
+ (0..(scores.count - 1)).each do |i|
51
+ neat.set_inputs(inputs, i)
52
+ end
53
+
54
+ neat.feed_forward
55
+ decisions = neat.decisions
56
+
57
+ (0..(scores.count - 1)).each do |i|
58
+ if inputs.last > 0
59
+ case decisions[i]
60
+ when 0
61
+ scores[i] += 1
62
+ when 1
63
+ scores[i] -= 1
64
+ end
65
+ else
66
+ case decisions[i]
67
+ when 0
68
+ scores[i] -= 1
69
+ when 1
70
+ scores[i] += 1
71
+ end
72
+ end
73
+
74
+ scores[i] = 0 if scores[i] < 0
75
+ end
76
+ end
77
+
78
+ (0..(scores.count - 1)).each do |i|
79
+ neat.set_fitness(scores[i], i)
80
+ end
81
+
82
+ first_score = scores[neat.best_creature] if gen == 0
83
+
84
+ neat.do_gen
85
+ end
86
+
87
+ exported = neat.export
88
+
89
+ neat2 = Ai::Neat::Neat.new(config)
90
+ neat2.import(exported)
91
+ ```
92
+
93
+ ## Development
94
+
95
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
96
+
97
+ 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).
98
+
99
+ ## Contributing
100
+
101
+ Bug reports and pull requests are welcome on GitHub at https://github.com/Sunama/ai-neat. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/Sunama/ai-neat/blob/master/CODE_OF_CONDUCT.md).
102
+
103
+ ## License
104
+
105
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
106
+
107
+ ## Code of Conduct
108
+
109
+ Everyone interacting in the Ai::Neat project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/Sunama/ai-neat/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/ai-neat.gemspec ADDED
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/ai/neat/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "ai-neat"
7
+ spec.version = Ai::Neat::VERSION
8
+ spec.authors = ["Sukrit Sunama"]
9
+ spec.email = ["sunama.sukrit@gmail.com"]
10
+
11
+ spec.summary = "NeuroEvolution of Augmenting Topologies (NEAT) ruby gem."
12
+ spec.description = "NeuroEvolution of Augmenting Topologies (NEAT) ruby gem."
13
+ spec.homepage = "https://github.com/Sunama/ai-neat"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = spec.homepage
19
+ spec.metadata["changelog_uri"] = spec.homepage
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
25
+ end
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ # Uncomment to register a new dependency of your gem
31
+ # spec.add_dependency "example-gem", "~> 1.0"
32
+
33
+ # For more information and examples about making a new gem, checkout our
34
+ # guide at: https://bundler.io/guides/creating_gem.html
35
+ end
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "ai/neat"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lib/ai/neat.rb ADDED
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ Dir[File.dirname(__FILE__) + "/neat/*.rb"].sort.each { |file| require file }
4
+
5
+ module Ai
6
+ module Neat
7
+ class Neat
8
+ attr_accessor :creatures, :old_creatures, :models, :population_size, :mutation_rate,
9
+ :crossover_method, :mutation_method, :generation
10
+
11
+ def initialize(config)
12
+ @creatures = []
13
+ @old_creatures = []
14
+ @models = config[:models]
15
+ @population_size = config[:population_size] || 500
16
+ @mutation_rate = config[:mutation_rate] || 0.05
17
+ @crossover_method = config[:crossover_method] || :random
18
+ @mutation_method = config[:mutation_method] || :random
19
+ @generation = 0
20
+
21
+ (1..@population_size).each do |_i|
22
+ @creatures.push(Creature.new(@models))
23
+ end
24
+ end
25
+
26
+ def best_creature
27
+ index = 0
28
+ max = -Float::INFINITY
29
+
30
+ (0..(@old_creatures.count - 1)).each do |i|
31
+ if @old_creatures[i].fitness > max
32
+ max = @old_creatures[i].fitness
33
+ index = i
34
+ end
35
+ end
36
+
37
+ index
38
+ end
39
+
40
+ def crossover
41
+ @creatures.each do |creature|
42
+ @old_creatures = @creatures.clone
43
+ parent_x = pick_creature
44
+ parent_y = pick_creature
45
+
46
+ genes = Ai::Neat.crossover(@crossover_method, parent_x.flatten_genes, parent_y.flatten_genes)
47
+ creature.flatten_genes = genes
48
+ end
49
+ end
50
+
51
+ def decisions
52
+ result = []
53
+
54
+ @creatures.each do |creature|
55
+ result.push(creature.decision)
56
+ end
57
+
58
+ result
59
+ end
60
+
61
+ def do_gen
62
+ crossover
63
+ mutate
64
+ @generation += 1
65
+ end
66
+
67
+ def export
68
+ data = {
69
+ models: @models,
70
+ creatures: []
71
+ }
72
+
73
+ @creatures.each do |creature|
74
+ data[:creatures].push(creature.flatten_genes)
75
+ end
76
+
77
+ data
78
+ end
79
+
80
+ def feed_forward
81
+ @creatures.each(&:feed_forward)
82
+ end
83
+
84
+ def import(data)
85
+ @models = data[:models]
86
+
87
+ @creatures = []
88
+ @population_size = 0
89
+
90
+ data[:creatures].each do |genes|
91
+ creature = Creature.new(@models)
92
+ creature.flatten_genes = genes
93
+
94
+ @creatures.push(creature)
95
+
96
+ @population_size += 1
97
+ end
98
+ end
99
+
100
+ def mutate
101
+ @creatures.each do |creature|
102
+ genes = creature.flatten_genes
103
+ genes = Ai::Neat.mutate(@mutation_method, genes, @mutation_rate)
104
+ creature.flatten_genes = genes
105
+ end
106
+ end
107
+
108
+ def pick_creature
109
+ sum = 0.0
110
+
111
+ @old_creatures.each do |creature|
112
+ sum += creature.score ^ 2
113
+ end
114
+
115
+ @old_creatures.each do |creature|
116
+ creature.fitness = (creature.score ^ 2) / sum
117
+ end
118
+
119
+ index = 0
120
+ r = rand
121
+
122
+ while r.positive?
123
+ r -= @old_creatures[index].fitness
124
+ index += 1
125
+ end
126
+
127
+ index -= 1
128
+
129
+ @old_creatures[index]
130
+ end
131
+
132
+ def set_fitness(fitness, index)
133
+ @creatures[index].score = fitness
134
+ end
135
+
136
+ def set_inputs(inputs, index)
137
+ @creatures[index].inputs = inputs
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ai
4
+ module Neat
5
+ class Creature
6
+ attr_accessor :network, :fitness, :score
7
+
8
+ def initialize(models)
9
+ @network = Network.new(models)
10
+ @fitness = 0
11
+ @score = 0
12
+ end
13
+
14
+ def decision
15
+ index = -1
16
+ max = -Float::INFINITY
17
+
18
+ (0..(@network.layers.last.nodes.count - 1)).each do |i|
19
+ if @network.layers.last.nodes[i].value > max
20
+ max = @network.layers.last.nodes[i].value
21
+ index = i
22
+ end
23
+ end
24
+
25
+ index
26
+ end
27
+
28
+ def feed_forward
29
+ @network.feed_forward
30
+ end
31
+
32
+ def flatten_genes
33
+ genes = []
34
+
35
+ (0..(@network.layers.count - 2)).each do |i|
36
+ @network.layers[i].nodes.each do |node|
37
+ node.weights.each do |weight|
38
+ genes.push(weight)
39
+ end
40
+ end
41
+
42
+ @network.layers[i].bias.weights.each do |weight|
43
+ genes.push(weight)
44
+ end
45
+ end
46
+
47
+ genes
48
+ end
49
+
50
+ def flatten_genes=(genes)
51
+ (0..(@network.layers.count - 2)).each do |i|
52
+ @network.layers[i].nodes.each do |node|
53
+ node.weights.each do |weight|
54
+ weight = genes.first
55
+ genes.shift
56
+ end
57
+ end
58
+
59
+ @network.layers[i].bias.weights.each do |weight|
60
+ weight = genes.first
61
+ genes.shift
62
+ end
63
+ end
64
+ end
65
+
66
+ def inputs
67
+ @network.layers.first.values
68
+ end
69
+
70
+ def inputs=(values)
71
+ @network.layers.first.values = values
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ai
4
+ module Neat
5
+ class Layer
6
+ attr_accessor :nodes, :bias, :node_type, :activationfunc
7
+
8
+ def initialize(node_count, node_type, activationfunc)
9
+ @nodes = []
10
+ @bias = nil
11
+ @node_type = node_type
12
+ @activationfunc = activationfunc
13
+
14
+ (1..node_count).each do |_i|
15
+ @nodes.push(Node.new)
16
+ end
17
+
18
+ @bias = Node.new if @node_type != :output
19
+ end
20
+
21
+ def connect(count)
22
+ @nodes.each do |node|
23
+ node.initWeights(count)
24
+ end
25
+
26
+ @bias&.initWeights(count)
27
+ end
28
+
29
+ def feed_forward(layer)
30
+ (0..(@bias.weights.count - 1)).each do |i|
31
+ layer.nodes[i].value = 0
32
+ end
33
+
34
+ @nodes.each do |node|
35
+ (0..(node.weights.count - 1)).each do |w|
36
+ layer.nodes[w].value += node.value * node.weights[w]
37
+ end
38
+ end
39
+
40
+ (0..(@bias.weights.count - 1)).each do |w|
41
+ layer.nodes[w].value += @bias.weights[w]
42
+ end
43
+
44
+ if layer.activationfunc != :softmax
45
+ layer.nodes.each do |node|
46
+ node.value = Ai::Neat.activationfunc(layer.activationfunc, node.value)
47
+ end
48
+ else
49
+ layer.values = Ai::Neat.activationfunc(layer.activationfunc, layer.values)
50
+ end
51
+ end
52
+
53
+ def values
54
+ result = []
55
+
56
+ @nodes.each do |node|
57
+ result.push(node.value)
58
+ end
59
+
60
+ result
61
+ end
62
+
63
+ def values=(values)
64
+ (0..(@nodes.count - 1)).each do |i|
65
+ @nodes[i].value = values[i]
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ai
4
+ module Neat
5
+ def self.activationfunc(method, value)
6
+ case method
7
+ when :relu
8
+ value.positive? ? value : 0
9
+ when :tanh
10
+ Math.tanh(value)
11
+ when :sigmoid
12
+ (1 / (1 + Math.exp(-value)))
13
+ when :leaky_relu
14
+ value.positive? ? value : (value * 0.01)
15
+ when :softmax
16
+ sum = 0
17
+ result = []
18
+
19
+ value.each do |v|
20
+ sum += Math.exp(v)
21
+ end
22
+
23
+ value.each do |v|
24
+ result.push(Math.exp(v) / sum)
25
+ end
26
+
27
+ result
28
+ end
29
+ end
30
+
31
+ def self.crossover(method, genes_x, genes_y)
32
+ case method
33
+ when :random
34
+ genes = []
35
+
36
+ (0..(genes_x.count - 1)).each do |i|
37
+ rand < 0.5 ? genes.push(genes_x[i]) : genes.push(genes_y[i])
38
+ end
39
+
40
+ genes
41
+ when :slice
42
+ start_index = (rand * genes_x.count).to_i
43
+ end_index = (rand * (genes_x.count - start_index + 2)).to_i + start_index + 1
44
+ cut_genes = genes_x[start_index..end_index]
45
+
46
+ genes = genes_y.clone
47
+
48
+ genes.slice!(start_index..end_index)
49
+ genes.concat(cut_genes)
50
+
51
+ genes
52
+ end
53
+ end
54
+
55
+ def self.mutate(method, genes, rate)
56
+ genes = genes.clone
57
+
58
+ case method
59
+ when :random
60
+ (0..(genes.count - 1)).each do |i|
61
+ genes[i] = rand(-1.0..1.0) if rand < rate
62
+ end
63
+ when :edit
64
+ (0..(genes.count - 1)).each do |i|
65
+ genes[i] += rand(-0.5..0.5) if rand < rate
66
+ end
67
+ end
68
+
69
+ genes
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ai
4
+ module Neat
5
+ class Network
6
+ attr_accessor :layers
7
+
8
+ def initialize(models)
9
+ @layers = []
10
+
11
+ models.each do |model|
12
+ @layers.push(Layer.new(model[:node_count], model[:node_type], model[:activationfunc]))
13
+ end
14
+
15
+ (0..(@layers.count - 2)).each do |i|
16
+ @layers[i].connect(@layers[i + 1].nodes.count)
17
+ end
18
+ end
19
+
20
+ def feed_forward
21
+ (0..(@layers.count - 2)).each do |i|
22
+ @layers[i].feed_forward(@layers[i + 1])
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ai
4
+ module Neat
5
+ class Node
6
+ attr_accessor :value, :weights
7
+
8
+ def initialize
9
+ @value = 0
10
+ @weights = []
11
+ end
12
+
13
+ def initWeights(count)
14
+ (1..count).each do |_i|
15
+ weights.push(rand(-1.0..1.0))
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ai
4
+ module Neat
5
+ VERSION = "0.1"
6
+ end
7
+ end
metadata ADDED
@@ -0,0 +1,66 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ai-neat
3
+ version: !ruby/object:Gem::Version
4
+ version: '0.1'
5
+ platform: ruby
6
+ authors:
7
+ - Sukrit Sunama
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-02-24 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: NeuroEvolution of Augmenting Topologies (NEAT) ruby gem.
14
+ email:
15
+ - sunama.sukrit@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".github/workflows/main.yml"
21
+ - ".gitignore"
22
+ - ".rspec"
23
+ - ".rubocop.yml"
24
+ - CODE_OF_CONDUCT.md
25
+ - Gemfile
26
+ - Gemfile.lock
27
+ - LICENSE.txt
28
+ - README.md
29
+ - Rakefile
30
+ - ai-neat.gemspec
31
+ - bin/console
32
+ - bin/setup
33
+ - lib/ai/neat.rb
34
+ - lib/ai/neat/creature.rb
35
+ - lib/ai/neat/layer.rb
36
+ - lib/ai/neat/method.rb
37
+ - lib/ai/neat/network.rb
38
+ - lib/ai/neat/node.rb
39
+ - lib/ai/neat/version.rb
40
+ homepage: https://github.com/Sunama/ai-neat
41
+ licenses:
42
+ - MIT
43
+ metadata:
44
+ homepage_uri: https://github.com/Sunama/ai-neat
45
+ source_code_uri: https://github.com/Sunama/ai-neat
46
+ changelog_uri: https://github.com/Sunama/ai-neat
47
+ post_install_message:
48
+ rdoc_options: []
49
+ require_paths:
50
+ - lib
51
+ required_ruby_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: 2.4.0
56
+ required_rubygems_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ requirements: []
62
+ rubygems_version: 3.1.4
63
+ signing_key:
64
+ specification_version: 4
65
+ summary: NeuroEvolution of Augmenting Topologies (NEAT) ruby gem.
66
+ test_files: []