Class: Micrograd::Value

Inherits:
Object
  • Object
show all
Defined in:
lib/micrograd/value.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, op: NullOp.new) ⇒ Value

Returns a new instance of Value.



5
6
7
8
9
# File 'lib/micrograd/value.rb', line 5

def initialize(data, op: NullOp.new)
  @data = data
  @grad = 0.0
  @op = op
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



11
12
13
# File 'lib/micrograd/value.rb', line 11

def data
  @data
end

#gradObject

Returns the value of attribute grad.



11
12
13
# File 'lib/micrograd/value.rb', line 11

def grad
  @grad
end

#opObject (readonly)

Returns the value of attribute op.



12
13
14
# File 'lib/micrograd/value.rb', line 12

def op
  @op
end

Instance Method Details

#*(other) ⇒ Object



21
22
23
24
25
26
# File 'lib/micrograd/value.rb', line 21

def *(other)
  other = wrap(other)
  op = MulOp.new(self, other)

  Value.new(@data * other.data, op: op)
end

#**(n) ⇒ Object



34
35
36
37
# File 'lib/micrograd/value.rb', line 34

def **(n)
  op = PowOp.new(self, n)
  Value.new(@data**n, op: op)
end

#+(other) ⇒ Object



14
15
16
17
18
19
# File 'lib/micrograd/value.rb', line 14

def +(other)
  other = wrap(other)
  op = AddOp.new(self, other)

  Value.new(@data + other.data, op: op)
end

#-(other) ⇒ Object



41
# File 'lib/micrograd/value.rb', line 41

def -(other) = self + (-wrap(other))

#-@Object



39
# File 'lib/micrograd/value.rb', line 39

def -@ = self * -1

#/(other) ⇒ Object



42
# File 'lib/micrograd/value.rb', line 42

def /(other) = self * (wrap(other) ** -1)

#backwardObject



44
# File 'lib/micrograd/value.rb', line 44

def backward = op.backward(self)

#coerce(other) ⇒ Object



51
52
53
# File 'lib/micrograd/value.rb', line 51

def coerce(other)
  [Value.new(other), self]
end

#inspectObject



55
# File 'lib/micrograd/value.rb', line 55

def inspect = "Value(#{data}, grad: #{grad})"

#start_backwardObject



46
47
48
49
# File 'lib/micrograd/value.rb', line 46

def start_backward
  self.grad = 1.0
  op.backward(self)
end

#tanhObject



28
29
30
31
32
# File 'lib/micrograd/value.rb', line 28

def tanh
  n = Math.tanh(self.data)
  op = TanhOp.new(self)
  Value.new(n, op: op)
end

#to_sObject



56
# File 'lib/micrograd/value.rb', line 56

def to_s = inspect