MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / Variable

Class Variable

machine_learning/automatic_differentiation.py:35–128  ·  view source on GitHub ↗

Class represents n-dimensional object which is used to wrap numpy array on which operations will be performed and the gradient will be calculated. Examples: >>> Variable(5.0) Variable(5.0) >>> Variable([5.0, 2.9]) Variable([5. 2.9]) >>> Variable([5.0, 2.9]) + Varia

Source from the content-addressed store, hash-verified

33
34
35class Variable:
36 """
37 Class represents n-dimensional object which is used to wrap numpy array on which
38 operations will be performed and the gradient will be calculated.
39
40 Examples:
41 >>> Variable(5.0)
42 Variable(5.0)
43 >>> Variable([5.0, 2.9])
44 Variable([5. 2.9])
45 >>> Variable([5.0, 2.9]) + Variable([1.0, 5.5])
46 Variable([6. 8.4])
47 >>> Variable([[8.0, 10.0]])
48 Variable([[ 8. 10.]])
49 """
50
51 def __init__(self, value: Any) -> None:
52 self.value = np.array(value)
53
54 # pointers to the operations to which the Variable is input
55 self.param_to: list[Operation] = []
56 # pointer to the operation of which the Variable is output of
57 self.result_of: Operation = Operation(OpType.NOOP)
58
59 def __repr__(self) -> str:
60 return f"Variable({self.value})"
61
62 def to_ndarray(self) -> np.ndarray:
63 return self.value
64
65 def __add__(self, other: Variable) -> Variable:
66 result = Variable(self.value + other.value)
67
68 with GradientTracker() as tracker:
69 # if tracker is enabled, computation graph will be updated
70 if tracker.enabled:
71 tracker.append(OpType.ADD, params=[self, other], output=result)
72 return result
73
74 def __sub__(self, other: Variable) -> Variable:
75 result = Variable(self.value - other.value)
76
77 with GradientTracker() as tracker:
78 # if tracker is enabled, computation graph will be updated
79 if tracker.enabled:
80 tracker.append(OpType.SUB, params=[self, other], output=result)
81 return result
82
83 def __mul__(self, other: Variable) -> Variable:
84 result = Variable(self.value * other.value)
85
86 with GradientTracker() as tracker:
87 # if tracker is enabled, computation graph will be updated
88 if tracker.enabled:
89 tracker.append(OpType.MUL, params=[self, other], output=result)
90 return result
91
92 def __truediv__(self, other: Variable) -> Variable:

Callers 6

__add__Method · 0.85
__sub__Method · 0.85
__mul__Method · 0.85
__truediv__Method · 0.85
__matmul__Method · 0.85
__pow__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected