Class: Newral::Functions::Polynomial

Inherits:
Base
  • Object
show all
Defined in:
lib/newral/functions/polynomial.rb

Instance Attribute Summary collapse

Attributes inherited from Base

#center

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#calculate_error, #calculate_for_center_distance, #error_gradient_approximation, #find_minimum, #move_random, #move_several, #move_with_gradient

Constructor Details

#initialize(factors: nil) ⇒ Polynomial

Returns a new instance of Polynomial.



5
6
7
8
# File 'lib/newral/functions/polynomial.rb', line 5

def initialize(  factors:nil )
  @factors = factors.dup || [1]
  @length = @factors.size
end

Instance Attribute Details

#factorsObject (readonly)

Returns the value of attribute factors.



4
5
6
# File 'lib/newral/functions/polynomial.rb', line 4

def factors
  @factors
end

Class Method Details

.create_random(length: 3, low_range: -9,, high_range: 9) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/newral/functions/polynomial.rb', line 27

def self.create_random(  length: 3, low_range: -9, high_range: 9 )
   factors = []
   length.times do 
     factors << low_range+rand(high_range-low_range)
   end
   self.new( factors: factors )
end

Instance Method Details

#calculate(input) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/newral/functions/polynomial.rb', line 10

def calculate( input ) 
  result = 0
  @factors.each_with_index do |factor, idx|
    result = result+input**(@length-idx-1)*factor # this way its more readable 
  end 
  result
end

#calculate_descent(input) ⇒ Object

caluates descent at input



19
20
21
22
23
24
25
# File 'lib/newral/functions/polynomial.rb', line 19

def calculate_descent( input )
  descent = 0
  @factors.each_with_index do |factor, idx|
    descent = descent+input**(@length-idx-2)*factor*(@length-idx-1) if @length-idx-2>= 0 # this way its more readable 
  end 
  descent
end

#move(direction: 0, step: 0.01, step_percentage: nil) ⇒ Object



39
40
41
42
43
44
# File 'lib/newral/functions/polynomial.rb', line 39

def move( direction: 0, step:0.01, step_percentage: nil )
  raise Errors::InvalidDirection if direction >= number_of_directions
  @factors = @factors.dup
  @factors[direction] = step_percentage ?  @factors[direction]*(1+step_percentage.to_f/100) : @factors[direction]+step
  self
end

#number_of_directionsObject



35
36
37
# File 'lib/newral/functions/polynomial.rb', line 35

def number_of_directions
  @factors.size 
end