首页 > 试题广场 >

实现基本自动微分操作

[编程题]实现基本自动微分操作
  • 热度指数:146 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
实现一个支持基本自动微分(Automatic Differentiation)操作的`Value`类,该类需要支持标量值的基本运算并能够自动计算梯度。这是深度学习框架中的核心功能之一。

输入描述:
实现以下操作:
1. 加法运算(`__add__`)
2. 乘法运算(`__mul__`)
3. ReLU激活函数(`relu`)
4. 反向传播计算梯度(`backward`)


输出描述:
返回计算结果和梯度。
示例1

输入

1
2
3

输出

Value(data=1, grad=1) Value(data=2, grad=3) Value(data=3, grad=2) Value(data=7, grad=1) Value(data=14, grad=1) Value(data=21, grad=1) Value(data=21, grad=1)
class Value:
    def __init__(self, data, _children=(), _op=""):
        self.data = data
        self.grad = 0
        self._backward = lambda: None
        self._prev = set(_children)
        self._op = _op

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

        def _backward():
            self.grad += out.grad
            other.grad += out.grad

        out._backward = _backward
        return out

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

        def _backward():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad

        out._backward = _backward
        return out

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

        def _backward():
            self.grad += (out.data > 0) * out.grad

        out._backward = _backward
        return out

    def backward(self):
        topo = []
        visited = set()

        def build_topo(v):
            if v not in visited:
                visited.add(v)
                for child in v._prev:
                    build_topo(child)
                topo.append(v)

        build_topo(self)
        self.grad = 1
        for v in reversed(topo):
            v._backward()

    def __repr__(self):
        return f"Value(data={self.data}, grad={self.grad})"

发表于 2025-05-09 14:40:25 回复(0)