Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions micrograd/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ def __init__(self, data, _children=(), _op=''):
self._op = _op # the op that produced this node, for graphviz / debugging / etc

def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other), '+')
other = other if isinstance(other, self.__class__) else self.__class__(other)
out = self.__class__(self.data + other.data, (self, other), '+')

def _backward():
self.grad += out.grad
Expand All @@ -22,8 +22,8 @@ def _backward():
return out

def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other), '*')
other = other if isinstance(other, self.__class__) else self.__class__(other)
out = self.__class__(self.data * other.data, (self, other), '*')

def _backward():
self.grad += other.data * out.grad
Expand All @@ -34,7 +34,7 @@ def _backward():

def __pow__(self, other):
assert isinstance(other, (int, float)), "only supporting int/float powers for now"
out = Value(self.data**other, (self,), f'**{other}')
out = self.__class__(self.data**other, (self,), f'**{other}')

def _backward():
self.grad += (other * self.data**(other-1)) * out.grad
Expand All @@ -43,7 +43,7 @@ def _backward():
return out

def relu(self):
out = Value(0 if self.data < 0 else self.data, (self,), 'ReLU')
out = self.__class__(0 if self.data < 0 else self.data, (self,), 'ReLU')

def _backward():
self.grad += (out.data > 0) * out.grad
Expand Down
27 changes: 27 additions & 0 deletions test/test_inheritance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import micrograd
import math

def test_new_method():
"""
Creates a new class that inherits with
same parameters
new method
"""
class Value(micrograd.Value):

def tanh(self):
x = self.data
temp = math.exp(2*x)
t = (temp - 1) / (temp + 1)
out = self.__class__(data=t, _children = (self,), label = "tanh")
return out

n = Value(data = 0.6, label = "neuron")
is_successful = True
try:
n.tanh()
except AttributeError as error:
is_successful = False
raise(error)

assert is_successful