05-08 11:44
Recent Posts
Recent Comments
관리 메뉴

너와나의 관심사

tensorflow keras 로 모델 training save (ModelSave 활용) 본문

머신러닝/딥러닝

tensorflow keras 로 모델 training save (ModelSave 활용)

벤치마킹 2022. 2. 6. 02:50
import os

# horses/humans 데이터셋 경로 지정
train_horse_dir = './classification_data/horses'
train_human_dir = './classification_data/humans'

train_horse_or_human = './classification_data/'


# horses 파일 이름 e
train_horse_names = os.listdir(train_horse_dir)
print(train_horse_names[:10])

# humans 파일 이름 리스트
train_human_names = os.listdir(train_human_dir)
print(train_human_names[:10])

# horses/humans 총 이미지 파일 개수
print('total training horse images:', len(os.listdir(train_horse_dir)))
print('total training human images:', len(os.listdir(train_human_dir)))


import matplotlib.pyplot as plt
import matplotlib.image as mpimg

nrows = 4
ncols = 4

pic_index = 0

fig = plt.gcf()
fig.set_size_inches(ncols * 4, nrows * 4)

pic_index += 8
next_horse_pix = [os.path.join(train_horse_dir, fname) for fname in train_horse_names[pic_index-8:pic_index]]
next_human_pix = [os.path.join(train_human_dir, fname) for fname in train_human_names[pic_index-8:pic_index]]

for i, img_path in enumerate(next_horse_pix+next_human_pix):
  sp = plt.subplot(nrows, ncols, i + 1)
  sp.axis('Off')

  img = mpimg.imread(img_path)
  plt.imshow(img)

#plt.show()

import tensorflow as tf

def create_model():
    # 모델 define
    model = tf.keras.models.Sequential([
        # The first convolution
        tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(300, 300, 3)),
        tf.keras.layers.MaxPool2D(2, 2),
        # The second convolution
        tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
        tf.keras.layers.MaxPool2D(2, 2),
        # The third convolution
        tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
        tf.keras.layers.MaxPool2D(2, 2),
        # The fourth convolution
        tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
        tf.keras.layers.MaxPool2D(2, 2),
        # The fifth convolution
        tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
        tf.keras.layers.MaxPool2D(2, 2),
        # Flatten
        tf.keras.layers.Flatten(),
        # 512 Neuron (Hidden layer)
        tf.keras.layers.Dense(512, activation='relu'),
        # 1 Output neuron
        tf.keras.layers.Dense(1, activation='sigmoid')
    ])


    return model;





from tensorflow.keras.optimizers import RMSprop
model = create_model();
model.summary()
model.compile(loss='binary_crossentropy',
            optimizer=RMSprop(learning_rate=0.001),
            metrics=['accuracy'])


from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale=1/255)

train_generator = train_datagen.flow_from_directory(
  train_horse_or_human,
  target_size=(300, 300),
  batch_size=128,
  class_mode='binary'
)

checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

# 모델의 가중치를 저장하는 콜백 만들기
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                 save_weights_only=True,
                                                 verbose=1)

history = model.fit(
  train_generator,
  steps_per_epoch=8,
  epochs=15,
  verbose=1
  #,callbacks = [cp_callback]
)

tf.saved_model.save(model, "./training_2")

Comments