[1] Data download & data load
import requests
url_1 = 'https://storage.googleapis.com/tensorflow-1-public/course2/week3/horse-or-human.zip'
file_name_1 = "horse-or-human.zip"
response = requests.get(url_2)
with open(file_name_1, 'wb') as f:
f.write(response.content)
print('말-인간 학습 데이터셋 다운로드 완료')
url_2 = 'https://storage.googleapis.com/tensorflow-1-public/course2/week3/validation-horse-or-human.zip'
file_name_2 = "validation-horse-or-human.zip"
response = requests.get(url_2)
with open(file_name_2, 'wb') as f:
f.write(response.content)
print('말-인간 검증 데이터셋 다운로드 완료')
다운 받은 압축 파일 풀기
import os
import zipfile
# Extract the archive
zip_ref = zipfile.ZipFile('./horse-or-human.zip', 'r')
zip_ref.extractall('horse-or-human')
zip_ref = zipfile.ZipFile('./validation-horse-or-human.zip', 'r')
zip_ref.extractall('validation-horse-or-human')
zip_ref.close()
학습 데이터와 검증 데이터의 폴더 위치 지정
# Directory with training horse pictures
train_horse_dir = os.path.join('horse-or-human/horses')
# Directory with training human pictures
train_human_dir = os.path.join('horse-or-human/humans')
# Directory with validation horse pictures
validation_horse_dir = os.path.join('validation-horse-or-human/horses')
# Directory with validation human pictures
validation_human_dir = os.path.join('validation-horse-or-human/humans')
print(train_horse_dir)
print(train_human_dir)
print(validation_horse_dir)
print(validation_human_dir)
horse-or-human/horses
horse-or-human/humans
validation-horse-or-human/horses
validation-horse-or-human/humans
[2] model build & model compile & ImageGenerator & model train
import tensorflow as tf
# Build the model
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.summary()
모델 컴파일
model.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.RMSprop(learning_rate=1e-4),
metrics=['accuracy'])
ImageGenerator 생성
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
validation_datagen = ImageDataGenerator(rescale=1/255)
train_generator = train_datagen.flow_from_directory(
'horse-or-human/',
target_size=(300, 300),
batch_size=128,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
'validation-horse-or-human/',
target_size=(300, 300),
batch_size=32,
class_mode='binary')
#output
Found 1027 images belonging to 2 classes.
Found 256 images belonging to 2 classes.
모델 학습
EPOCHS = 20
history = model.fit(
train_generator,
steps_per_epoch= 8,
epochs = EPOCHS,
verbose = 1,
validation_data = validation_generator,
validation_steps=8,
)
[3] 모델 평가
import matplotlib.pyplot as plt
# Plot the model results
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.figure()
plt.plot(epochs, loss, 'r', label='Training Loss')
plt.plot(epochs, val_loss, 'b', label='Validation Loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()