728x90
반응형
새로운 Dezero로!
class Variable:
def backward(self, retain_grad=False):
if self.grad is None:
# self.grad = np.ones_like(self.data)
self.grad = Variable(np.ones_like(self.data))
- 이러한 변경 덕에 미분값을 자동으로 저장하는 코드에서 self.grad가 Variable 인스턴스를 담게 된다.
함수 클래스의 역전파
Add 클래스
class Add(Function):
def forward(self, x0, x1):
y = x0 + x1
return y
def backward(self, gy):
return gy, gy
Mul 클래스
class Mul(Function):
def forward(self, x0, x1):
y = x0 * x1
return y
def backward(self, gy):
# x0, x1 = self.inputs[0].data, self.inputs[1].data
x0, x1 = self.inputs
return gy * x1, gy * x0
- 수정 후에는 Mul 클래스에서 Variable 인스턴스를 그대로 사용
역전파를 더 효율적으로(모드 추가)
- 역전파를 처음 한 번 이후로 다시 할 일이 없다면 역전파 계산도 '역전파 비활성 모드'로 실행하도록 변경
class Variable:
while funcs:
f = funcs.pop()
gys = [output().grad for output in f.outputs]
with using_config('enable_backprop', create_graph):
gxs = f.backward(*gys) # 메인 backward
if not isinstance(gxs, tuple):
gxs = (gxs,)
for x, gx in zip(f.inputs, gxs):
if x.grad is None:
x.grad = gx
else:
x.grad = x.grad + gx # 이 계산도 대상
if x.creator is not None:
add_func(x.creator)
__init__.py 변경
is_simple_core = False # True
if is_simple_core:
from dezero.core_simple import Variable
from dezero.core_simple import Function
from dezero.core_simple import using_config
from dezero.core_simple import no_grad
from dezero.core_simple import as_array
from dezero.core_simple import as_variable
from dezero.core_simple import setup_variable
else:
from dezero.core import Variable
from dezero.core import Parameter
from dezero.core import Function
from dezero.core import using_config
from dezero.core import no_grad
from dezero.core import test_mode
from dezero.core import as_array
from dezero.core import as_variable
from dezero.core import setup_variable
setup_variable()
출처 : http://www.yes24.com/Product/Goods/95343845?OzSrank=2
728x90
반응형
최근댓글