implement_ml_models

implement_forwardPropagation

명징직조지훈 2022. 11. 25. 23:28

MLP의 구현

먼저 노드간 계산을 위한 mlp 클래스 생성

class mlp:
  # 가중치 w
  w = []
  x_b = []

  def __init__(self):
    self.w = []

  def cal_dense(self, input, unit):
    """
    Args
      input : 입력 데이터
      unit : 은닉층 노드의 개수
    return 
      각 가중치 별 입력 데이터와의 연산 결과
    """
    # 입력 데이터에 편향 가중치를 위한 열, 1의 추가
    self.x_b = np.c_[input, np.ones((input.shape[0],1))]
    
    # 가중치 w의 생성
    self.w = np.random.rand(self.x_b.shape[0], unit)

    return input.T.dot(self.w)
hidden_input = m.cal_dense(perch_length,2)
hidden_input
>>>
array([[752.86102554, 605.8363627 ]])

노드간 완전 연결 계산을 위한 cal_dense 함수,

입력 파라미터로는 입력 값과 은닉 노드 개수가 존재한다. 

입력 값에 편향 가중치를 계산하기 위한 값, 상수를 추가하고, 

추가된 입력값에 랜덤하게 생성한 가중치에 대한 연산을 수행, 내적 결과는 은닉 노드에 대한 입력으로 은닉층 노드의 활성화 함수 계산에 대한 입력이 된다.

  def activation(self, input, activation):
    """
    args
      input : 은닉 노드의 입력 데이터, 이전 층의 가중치와의 내적 연산 결과이다.
      activatoin : 활성화 함수
    return
      활성화 함수 연산 결과
    """
    result = []

    for i in range(input.shape[1]):
      result.append(activation.subs([(e,np.e), (x,input[0][i])]))

    return result
    
activation_function = 1/(1+e**(-x))

hidden_output = m.activation(hidden_input, activation_function)
hidden_output
>>>
[1.00000000000000, 1.00000000000000]

활성화 함수로, 시그모이드 함수를 사용하여 전달했고, 각 은닉층 노드 별 출력을 확인할 수 있다.

위 두 연산을 통한 순전파 계산을 수행할 수 있다.