반응형
1. 설명
y=⍬x 단일 회귀분석을 수행한다
각 곱,합,평균 등의 계산을 클래스로 구현하고, forward와 back propagation함수를 각 클래스 내부에 구현한다.
2. 파일
(1) basic node.py
import numpy as np
class mean_node:
def __init__(self):
self._x=None
self._z=None
def forward(self, x):
self._x = x
self._z = np.mean(self._x)
return self._z
def backward(self, dz):
dx = dz * 1 / len(self._x) * np.ones_like(self._x)
return dx
class square_node:
def __init__(self):
self._x = None
self._z = None
def forward(self, x):
self._x = x
self._z = self._x * self._x
return self._z
def backward(self, dz):
return dz * 2 * self._x
class mul_node:
def __init__(self):
self._x, self._y = None, None
self._z = None
def forward(self, x, y):
self._x, self._y = x, y
self._z = self._x * self._y
return self._z
def backward(self, dz):
return dz * self._y, dz * self._x
class minus_node:
def __init__(self):
self._x, self._y = None, None
self._z = None
def forward(self, x, y):
self._x, self._y = x, y
self._z = self._x - self._y
return self._z
def backward(self, dz):
return dz, -1 * dz
class plus_node:
def __init__(self):
self._x, self._y = None, None
self._z = None
def forward(self, x, y):
self._x, self._y = x, y
self._z = self._x + self._y
return self._z
def backward(self, dz):
return dz, dz
(2) test2.py
import numpy as np
from dataset_generator import dataset_generator
import basic_nodes as nodes
#클래스
node1=nodes.mul_node()
node2=nodes.minus_node()
node3=nodes.square_node()
node4=nodes.mean_node()
# dataset preparation
dataset_gen = dataset_generator()
dataset_gen.set_coefficient([5,0])
x_data, y_data = dataset_gen.make_dataset()
dataset_gen.dataset_visualizer(x_data,y_data)
# hyperparameter setting
epochs = 50
lr = 0.05
th=-1
cost_list=[]
th_list = []
for epoch in range(epochs):
X, Y = x_data, y_data
#forward propagation
Z1 = node1.forward(th, X)
Z2 = node2.forward(Y, Z1)
L = node3.forward(Z2)
J = node4.forward(L)
#backward propagation
dL = node4.backward(1)
dZ2 = node3.backward(dL)
dY, dZ1 = node2.backward(dZ2)
dTh, dX = node1.backward(dZ1)
#gradient descent
th = th - lr * np.sum(dTh)
#히스토리 저장
th_list.append(th)
cost_list.append(J)
print(th_list)
print(cost_list)
3. 데이터생성
데이터를 처음 생성하면 다음과 같이 만들어지고 시각화 된다.
4. forward propagation
#forward propagation
Z1 = node1.forward(th, X)
Z2 = node2.forward(Y, Z1)
L = node3.forward(Z2)
J = node4.forward(L)
5. backward propagation
#backward propagation
dL = node4.backward(1)
dZ2 = node3.backward(dL)
dY, dZ1 = node2.backward(dZ2)
dTh, dX = node1.backward(dZ1)
반응형