Class: DNN::Models::Chain

Inherits:
Object
  • Object
show all
Defined in:
lib/dnn/core/models.rb

Direct Known Subclasses

Model

Instance Method Summary collapse

Constructor Details

#initializeChain

Returns a new instance of Chain.



42
43
44
# File 'lib/dnn/core/models.rb', line 42

def initialize
  @layers_cache = nil
end

Instance Method Details

#call(input_tensors) ⇒ Tensor

Forward propagation and create a link.

Parameters:

  • input_tensors (Tensor | Array)

    Input tensors.

Returns:



56
57
58
# File 'lib/dnn/core/models.rb', line 56

def call(input_tensors)
  forward(input_tensors)
end

#forward(input_tensors) ⇒ Tensor

Forward propagation.

Parameters:

  • input_tensors (Tensor)

    Input tensors.

Returns:

Raises:

  • (NotImplementedError)


49
50
51
# File 'lib/dnn/core/models.rb', line 49

def forward(input_tensors)
  raise NotImplementedError, "Class '#{self.class.name}' has implement method 'forward'"
end

#layersArray

Get the all layers.

Returns:

  • (Array)

    All layers array.



62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/dnn/core/models.rb', line 62

def layers
  return @layers_cache if @layers_cache
  layers_array = []
  instance_variables.sort.each do |ivar|
    obj = instance_variable_get(ivar)
    if obj.is_a?(Layers::Layer)
      layers_array << obj
    elsif obj.is_a?(Chain) || obj.is_a?(LayersList)
      layers_array.concat(obj.layers)
    end
  end
  @layers_cache = layers_array
end

#load_hash(layers_hash) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/dnn/core/models.rb', line 89

def load_hash(layers_hash)
  instance_variables.sort.each do |ivar|
    hash_or_array = layers_hash[ivar]
    if hash_or_array.is_a?(Array)
      instance_variable_set(ivar, LayersList.from_hash_list(hash_or_array))
    elsif hash_or_array.is_a?(Hash)
      obj_class = DNN.const_get(hash_or_array[:class])
      obj = obj_class.allocate
      if obj.is_a?(Chain)
        obj = obj_class.new
        obj.load_hash(hash_or_array)
        instance_variable_set(ivar, obj)
      else
        instance_variable_set(ivar, Layers::Layer.from_hash(hash_or_array))
      end
    end
  end
end

#to_hashObject



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/dnn/core/models.rb', line 76

def to_hash
  layers_hash = { class: self.class.name }
  instance_variables.sort.each do |ivar|
    obj = instance_variable_get(ivar)
    if obj.is_a?(Layers::Layer) || obj.is_a?(Chain)
      layers_hash[ivar] = obj.to_hash
    elsif obj.is_a?(LayersList)
      layers_hash[ivar] = obj.to_hash_list
    end
  end
  layers_hash
end