새소식

머신러닝 & 딥러닝

[Tensorflow] 신경망 모델 구축 방식

  • -

순차형 (Sequential) 모델

순차형 모델은 간단한 신경망 구조를 구성하는 데 사용되며, 층을 순차적으로 쌓아올린다. 이 방식은 각 층에 대한 복잡한 연결이 없을 때 적합하다. TensorFlow의 Keras API를 사용하여 순차형 모델을 구성하는 방법은 다음과 같다.

from tensorflow.keras import models
from tensorflow.keras import layers

model = models.Sequential()
model.add(layers.Dense(128, activation='relu', input_shape=(784,)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

 

함수형 (Functional) 모델

함수형 모델은 복잡한 신경망 구조를 구성할 수 있게 해준다. 이 방식은 다중 입력이나 출력, 공유 층, 그래프 형태의 모델 등을 만들기에 적합하다. TensorFlow의 Keras API를 사용하여 함수형 모델을 구성하는 방법은 다음과 같다.

from tensorflow.keras import Model
from tensorflow.keras import layers

class MyModel(Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.dense1 = layers.Dense(128, activation='relu')
        self.dense2 = layers.Dense(64, activation='relu')
        self.dense3 = layers.Dense(10, activation='softmax')

    def call(self, inputs):
        x = self.dense1(inputs)
        x = self.dense2(x)
        return self.dense3(x)

model = MyModel()

 

모델 하위 클래스화 (Model Subclassing)

모델 하위 클래스화는 사용자 정의 신경망 구조를 구성할 수 있게 해주며, 객체 지향 프로그래밍 방식을 따른다. 이 방식은 층과 연산을 직접 정의하고자 할 때 사용한다. TensorFlow의 Keras API를 사용하여 모델 하위 클래스화를 구성하는 방법은 다음과 같다.

from tensorflow.keras import Model
from tensorflow.keras import layers

class MyModel(Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.dense1 = layers.Dense(128, activation='relu')
        self.dense2 = layers.Dense(64, activation='relu')
        self.dense3 = layers.Dense(10, activation='softmax')

    def call(self, inputs):
        x = self.dense1(inputs)
        x = self.dense2(x)
        return self.dense3(x)

model = MyModel()
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.