From 3ce1ab85f0fda71a7a63b5ab32a76899933e0056 Mon Sep 17 00:00:00 2001 From: dhern023 Date: Sun, 9 Jun 2024 17:47:04 -0400 Subject: [PATCH 1/2] Use the class attribute instead of the hard-coded name. --- micrograd/engine.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/micrograd/engine.py b/micrograd/engine.py index afd82cc5..9ecf935b 100644 --- a/micrograd/engine.py +++ b/micrograd/engine.py @@ -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 @@ -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 @@ -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 @@ -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 From 6fa8dda9c4a6271a5375873a5b3e29ae88650728 Mon Sep 17 00:00:00 2001 From: dhern023 Date: Sun, 9 Jun 2024 17:47:13 -0400 Subject: [PATCH 2/2] Create test_inheritance.py --- test/test_inheritance.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 test/test_inheritance.py diff --git a/test/test_inheritance.py b/test/test_inheritance.py new file mode 100644 index 00000000..bb36047f --- /dev/null +++ b/test/test_inheritance.py @@ -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 \ No newline at end of file