본문 바로가기

ml_framework

cnn 정리

먼저 합성곱 연산 레이어,

합성곱 층 레이어를 쌓는 방법,

Sequential 객체를 생성,

model = Sequential()

add 함수를 통해 딕셔너리 형태의 층을 쌓는다.

 

Seqential 클래스의 add 함수

  # 각 층을 쌓기 위한 함수
  def add(self, dict):
    self.layer.append(dict)

 

 

딕셔너리 파일을 생성하는 CNN 클래스의 cnn_layer 함수,

    # cnn 층
    def cnn_layer(self, filter_size, filter_count = 1, activation = "relu", padding = "same", stride = 1, input_shape = [1, 1, 1]):
        cnn_dict = dict()

        cnn_dict['layer_type'] = "cnn"
        cnn_dict['filter_size'] = filter_size
        cnn_dict['filter_count'] = filter_count
        cnn_dict['activation'] = activation
        cnn_dict['padding'] = padding
        cnn_dict['stride'] = stride
        cnn_dict['input_shape'] = input_shape

        return cnn_dict

 

 

 

model = Sequential()

cnn = CNN()

model.add(cnn.cnn_layer((3,3), 32, padding = "same", stride = 1, input_shape=[28,28,1]))
model.add(cnn.pool_layer(pool_size=(2,2)))

필터 크기, 차원, 입력 데이터 크기 등을 지정하여 딕셔너리 객체를 생성하고 해당 객체를 Sequential() 객체에 쌓는다.

 

이후 최적화 방법 지정

Sequential 클래스의 compile 함수,

  # compile 함수
  def compile(self, loss = "mse", optimizer = "sgd", metrics = ['accuaray']):
    compile_dict = dict()
    compile_dict['loss'] = loss
    compile_dict['optimizer'] = optimizer
    compile_dict['metrics'] = metrics
    
    return compile_dict

해당 객체 내 compile_dict 의 딕셔너리 파일의 생성,

model.compile(~)

 

이후 fit 함수의 시행,

  # fit 함수
  def fit(self, train, target, epochs = 1, learning_rate = 0.01):
    
    self.fit_dir['train'] = train
    self.fit_dir['target'] = target
    self.fit_dir['epochs'] = epochs
    
    ~

먼저 훈련 정보에 대한 fit_dir 의 딕셔너리 형태의 정보 저장, (저장하지 않을 수도 있음)

 

이후 입력받은 훈련 횟수만큼의 반복,

    # 훈련 횟수 만큼의 반복
    for epoch in range(epochs):
      
      # 배치 개수 만큼의 반복
      for data in range(train.shape[0]):

지정한 학습 횟수와 데이터 개수만큼의 반복

각 반복에서 저장된 레이어를 돌게 된다.

        # 레이어의 순환
        for layer_num in self.layer:
                  
          layer_type = layer.get('layer_type')

각 레이어에서 레이어 타입을 획득, 해당 타입 별 정해진 연산 수행

 

cnn tarin 함수의 경우, 받는 파라미터로 해당 딕셔너리 파일과 입력 데이터로 구성,

          elif(layer_type == 'CNN'):
            self.cnn.train(layer, train_data)

해당 레이어의 딕셔너리 파일과 훈련 데이터의 전달,

 

train 을 통해 새로운 딕셔너리 파일과 그 출력을 return 받아야 한다. 

          elif(layer_type == 'CNN'):
            filter_weight, filter_result = self.cnn.train(layer, train_data)

            # 해당 레이어의 출력이 입력 데이터가 되어야 한다.
            train_data = filter_result

            # 가중치는 따로 저장 필요
            self.weight_layer.append(filter_weight)

레이어 연산 결과는 다음 레이어의 입력 데이터 값이 되어야 하고, 

해당 가중치의 저장,

 

연산 결과의 크기는 (width, height, dimension) 의 형태, 

cnn, pooling 연산 시 각 차원에 대해서 연산 수행,

 

pooling 시 데이터와 해당 레이어 딕셔너리 파일의 전달

    def pool_layer(self, pool_size=(2,2), pooling_type = "max"):
        pool_dict = dict()

        pool_dict['layer_type'] = "pool"
        pool_dict['pool_type'] = pooling_type
        pool_dict['pool_size'] = pool_size

풀링 딕셔너리 파일의 형태,

우선 풀링 사이즈에 따라 풀링 후 결과의 크기가 정해진다.

pooling_matrix = self.pad.padding(data.shape[1], (data.shape[1] % pooling_size))

패딩의 수행, 이후 풀링의 종류에 따라 연산 수행,

풀링 연산 함수 맥스 풀링의 경우,

        if(pooling_type == 'max'):
            # 데이터의 각 차원에 대해 연산 수행
            for data_dimension in range(data.shape[0]):
                for col in range(0, pooling_matrix.shape[0], pooling_size):
                    for row in range(0, pooling_matrix.shape[1], pooling_size):
                        pool_arr = []
                        for pooling_col in range(pooling_size):
                            for pooling_row in range(pooling_size):        
                                pool_arr.append(pooling_matrix[pooling_col + col, pooling_row + row])
                        self.pool_result.append(max(pool_arr))
                        
		# 연산 결과를 크기에 맞게 바꿔준다.
        pooling_result = np.array(result).reshape(int(pooling_matrix.shape[0] / pooling_size), -1)

 

 

 

 

 

 

'ml_framework' 카테고리의 다른 글

pooling_stride  (0) 2023.05.12
pooling, padding  (0) 2023.05.12
cnn 연산 수정  (0) 2023.05.09
cnn(layer)  (0) 2023.05.06
cnn(layer)  (0) 2023.05.04