Keras model - pai-plznw4me/tensorflow_basic GitHub Wiki

์—ฌ๋Ÿฌ๊ฐœ์˜ Layer ์„ ํ•˜๋‚˜๋กœ ๋ชจ๋“ˆ๋กœ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํŽธ๋ฆฌํ•œ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” class.
Keras Model์€ tf.Variable ์˜ ๊ด€๋ฆฌ ๋ฐ Keras Layer ์„ ์‰ฝ๊ฒŒ ๊ด€๋ฆฌ ํ•  ์ˆ˜ ์žˆ๋Š” ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค.
Model ์ƒ์„ฑ ๋ฐฉ๋ฒ•์— ๋”ฐ๋ฅธ ๋ถ„๋ฅ˜๋กœ Functional Model API ์™€ Custom Model API ๋กœ ๋‚˜๋ˆŒ์ˆ˜ ์žˆ๋‹ค.

๊ธฐ๋ณธ์ฝ”๋“œ
from tensorflow.keras.layers import Layer
import tensorflow as tf
from tensorflow.keras.datasets.mnist import load_data
import numpy as np


class Dense(Layer):
    def __init__(self, out_features, **kwargs):
        super().__init__(**kwargs)
        self.out_features = out_features
        self.w, self.b = None, None

    def build(self, input_shape):
        self.w = tf.Variable(tf.random.normal([input_shape[-1], self.out_features], stddev=0.1), name='w')
        self.b = tf.Variable(tf.zeros([self.out_features]), name='b')

    @tf.function
    def call(self, inputs, activation):
        return activation(tf.matmul(inputs, self.w) + self.b)


class DNN(tf.keras.Model):
    def __init__(self, name=None, **kwargs):
        super().__init__(**kwargs)
        self.dense_1 = Dense(256)
        self.dense_2 = Dense(256)

    def call(self, x):
        x = self.dense_1(x, activation=tf.nn.relu)
        return self.dense_2(x, activation=tf.nn.relu)


if __name__ == '__main__':
    (train_xs, train_ys), (test_xs, test_ys) = load_data()
    train_xs = train_xs.reshape(-1, 784)
    batch_ys = train_ys[:6]
    batch_xs = (train_xs[:6] / 255.).astype(np.float32)

    dense = Dense(256, name='dynamic')
    print(dense(batch_xs, tf.nn.relu))

    # DNN Model
    dnn = DNN('dynamic dnn')
    print(dnn(batch_xs))
1. tf.Variables ๊ด€๋ฆฌ
  • keras.Model ๋‚ด ์ƒ์„ฑ๋œ ๋ณ€์ˆ˜ ๊ด€๋ฆฌ

1.1 trainable weights ์ ‘๊ทผ ํ•˜๊ธฐ

model = Model(input_, output_)
dnn.trainable_weights

1.2 non trainable weights ์ ‘๊ทผ ํ•˜๊ธฐ

model = Model(input_, output_)
dnn.non_trainable_weights

1.3 model ์—์„œ weights ๊ฐ’ ๊ฐ€์ ธ์˜ค๊ธฐ

model = Model(input_, output_)
model.get_weights()

1.4 model ์—์„œ weights ๊ฐ’ ๋ณ€๊ฒฝ ํ•˜๊ธฐ

model = Model(input_, output_)
model.set_weights(model.get_weights())
2. Keras Layer ๊ด€๋ฆฌ

2.1 ๋ชจ๋“  layers ์ •๋ณด ๊ฐ€์ ธ์˜ค๊ธฐ

dnn = Model(input_, output_)
dnn.layers

2.2 ํŠน์ • layer ์— ์ด๋ฆ„์œผ๋กœ ์ ‘๊ทผํ•˜๊ธฐ

dnn.get_layer('dense')
3. build() ์„ ํ™œ์šฉํ•œ weight ์ดˆ๊ธฐ ์ƒ์„ฑ ๊ธฐ๋Šฅ

Keras model pattern> Dynamic input ์ฐธ์กฐ

4. get_config, from_config ์„ ํ™œ์šฉํ•œ model clone ๊ธฐ๋Šฅ
dnn = Model(input_, output_)
config = dnn.get_config()
Model.from_config(config)
5. ๋ชจ๋ธ ์ด์–ด ๋ถ™์ด๊ธฐ

Keras model pattern

  1. Model ์ด์–ด ๋ถ™์ด๊ธฐ
  2. Custom Model ์ด์–ด ๋ถ™์ด๊ธฐ
โš ๏ธ **GitHub.com Fallback** โš ๏ธ