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

Class GradientTracker

machine_learning/automatic_differentiation.py:156–322  ·  view source on GitHub ↗

Class contains methods to compute partial derivatives of Variable based on the computation graph. Examples: >>> with GradientTracker() as tracker: ... a = Variable([2.0, 5.0]) ... b = Variable([1.0, 2.0]) ... m = Variable([1.0, 2.0]) ... c = a + b

Source from the content-addressed store, hash-verified

154
155
156class GradientTracker:
157 """
158 Class contains methods to compute partial derivatives of Variable
159 based on the computation graph.
160
161 Examples:
162
163 >>> with GradientTracker() as tracker:
164 ... a = Variable([2.0, 5.0])
165 ... b = Variable([1.0, 2.0])
166 ... m = Variable([1.0, 2.0])
167 ... c = a + b
168 ... d = a * b
169 ... e = c / d
170 >>> tracker.gradient(e, a)
171 array([-0.25, -0.04])
172 >>> tracker.gradient(e, b)
173 array([-1. , -0.25])
174 >>> tracker.gradient(e, m) is None
175 True
176
177 >>> with GradientTracker() as tracker:
178 ... a = Variable([[2.0, 5.0]])
179 ... b = Variable([[1.0], [2.0]])
180 ... c = a @ b
181 >>> tracker.gradient(c, a)
182 array([[1., 2.]])
183 >>> tracker.gradient(c, b)
184 array([[2.],
185 [5.]])
186
187 >>> with GradientTracker() as tracker:
188 ... a = Variable([[2.0, 5.0]])
189 ... b = a ** 3
190 >>> tracker.gradient(b, a)
191 array([[12., 75.]])
192 """
193
194 instance = None
195
196 def __new__(cls) -> Self:
197 """
198 Executes at the creation of class object and returns if
199 object is already created. This class follows singleton
200 design pattern.
201 """
202 if cls.instance is None:
203 cls.instance = super().__new__(cls)
204 return cls.instance
205
206 def __init__(self) -> None:
207 self.enabled = False
208
209 def __enter__(self) -> Self:
210 self.enabled = True
211 return self
212
213 def __exit__(

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