Module: Neuronet::Exportable

Included in:
Deep, FeedForward, MLP, Perceptron
Defined in:
lib/neuronet/exportable.rb

Overview

Exportable serializes network biases and weights only. Human-readable, compact, excludes activations.

Instance Method Summary collapse

Instance Method Details

#export(writer) ⇒ Object

Writes serialized network to writer(from self). rubocop: disable Metrics



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/neuronet/exportable.rb', line 9

def export(writer)
  sizes = map(&:size)
  writer.puts "# #{self.class}"
  # The first "float" here is the number of layers in the FFN...
  # Just to be consistent:
  writer.puts "#{sizes.size.to_f} #{sizes.join(' ')}"
  each_with_index do |layer, i|
    next if i.zero? # skip input layer

    layer.each_with_index do |neuron, j|
      writer.puts "# neuron = FFN[#{i}, #{j}]"
      writer.puts "#{neuron.bias} #{i} #{j}"
      neuron.connections.each_with_index do |connection, k|
        writer.puts "#{connection.weight} #{i} #{j} #{k}"
      end
    end
  end
end

#export_to_file(filename) ⇒ Object

rubocop: enable Metrics



29
# File 'lib/neuronet/exportable.rb', line 29

def export_to_file(filename) = File.open(filename, 'w') { export it }

#import(reader) ⇒ Object

Reads and validates serialized network from reader to set self. rubocop: disable Metrics



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/neuronet/exportable.rb', line 34

def import(reader)
  gets_data = lambda do |reader|
    return nil unless (line = reader.gets)

    line = reader.gets while line.start_with?('#')
    fs, *is = line.strip.split
    [fs.to_f, *is.map(&:to_i)]
  end

  size, *sizes = gets_data[reader]
  raise 'Size/Sizes mismatch' unless size == sizes.size
  raise 'Sizes mismatch' unless sizes == map(&:size)

  each_with_index do |layer, i|
    next if i.zero? # skip input layer

    layer.each_with_index do |neuron, j|
      bias, *indeces = gets_data[reader]
      raise "bad bias index: #{indeces}" unless indeces == [i, j]

      neuron.bias = bias
      neuron.connections.each_with_index do |connection, k|
        weight, *indeces = gets_data[reader]
        raise "bad weight index: #{indeces}" unless indeces == [i, j, k]

        connection.weight = weight
      end
    end
  end
  raise 'Expected end of file.' unless gets_data[reader].nil?
end

#import_from_file(filename) ⇒ Object



30
# File 'lib/neuronet/exportable.rb', line 30

def import_from_file(filename) = File.open(filename, 'r') { import it }