Class: Parity

Inherits:
Object
  • Object
show all
Defined in:
lib/neuro/display.rb

Constant Summary collapse

MAX_BITS =
2

Instance Method Summary collapse

Constructor Details

#initialize(network) ⇒ Parity

Returns a new instance of Parity.



374
375
376
377
378
379
380
# File 'lib/neuro/display.rb', line 374

def initialize(network)
  @network = network
  @network.debug = STDERR
  @network.debug_step = 1000
  @eta = 0.2
  @max_error = 1.0E-5
end

Instance Method Details

#all_vectorsObject



399
400
401
402
403
404
405
# File 'lib/neuro/display.rb', line 399

def all_vectors
  vectors = []
  for x in 0...(2 ** MAX_BITS)
    vectors << (0...MAX_BITS).map { |i| x[i].zero? ? 0.0 : 1.0 }.reverse
  end
  vectors
end

#parity(vector) ⇒ Object



395
396
397
# File 'lib/neuro/display.rb', line 395

def parity(vector)
  (vector.inject(1) { |s,x| s * (x < 0.5 ? -1 : 1) }) < 0 ? 1 : 0
end

#pre_trainObject



382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/neuro/display.rb', line 382

def pre_train
  vectors = all_vectors
  max_count = vectors.size * 10
  count = max_count
  until count < max_count
    count = 0
    vectors.sort_by { rand }.each do |sample|
      desired = [ parity(sample) == 1 ? 0.95 : 0.05 ]
      count += @network.learn(sample, desired, @max_error, @eta)
    end
  end
end

#runObject



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/neuro/display.rb', line 407

def run
  loop do
    puts "#{@network.input_size} bits?"
    input = STDIN.gets.chomp
    /^[01]{#{@network.input_size}}$/.match(input) or next
    input = input.split(//).map { |x| x.to_i }
    parity, = @network.decide(input)
    rounded = parity.round
    puts "#{parity} -> #{rounded} - Learn, invert or skip? (l/i/s)"
    what_now = STDIN.gets.chomp
    case what_now
    when 'l'
      @network.learn(input, [ rounded == 0 ? 0.05 : 0.95 ], @max_error, @eta)
    when 'i'
      @network.learn(input, [ rounded == 0 ? 0.95 : 0.05 ], @max_error, @eta)
    end
  end
end