<해달(1)과 수달(0) 분류하는 신경망>
from google.colab import drive
drive.mount('/content/drive')
!unzip -qq /content/drive/MyDrive/animal/test.zip -d /content/drive/MyDrive/animal/test/
!unzip -qq /content/drive/MyDrive/animal/train.zip -d /content/drive/MyDrive/animal/train/
path="/content/drive/MyDrive/animal/train_label.csv"
file = open( path, 'w')
for i in range(1, 592):
file.write( str(1) + '\n') # 해달
for i in range(592, 1366):
file.write( str(0) + '\n') # 수달
file.close()
path="/content/drive/MyDrive/animal/test_label.csv"
file = open( path, 'w')
for i in range(1, 51):
file.write( str(1) + '\n') # 해달
for i in range(51, 101):
file.write( str(0) + '\n') # 수달
file.close()
import os
import re
import cv2
import numpy as np
def image_load(path):
file_list = os.listdir(path)
file_name=[]
for i in file_list:
a = int( re.sub('[^0-9]','', i) ) # i 가 숫자가 아니면 null 로 변경해라 ~
file_name.append(a)
file_name.sort() # 정렬작업
file_res=[]
for j in file_name:
file_res.append('%s/%d.jpg' %(path,j) )
image=[]
for k in file_res:
img = cv2.imread(k)
image.append(img)
return np.array(image)
import csv
def label_load(path):
file = open(path)
labeldata = csv.reader(file)
labellist = []
for i in labeldata:
labellist.append(int(i[0]))
return np.array(labellist)
import cv2
import os
import numpy as np
path = "/content/drive/MyDrive/animal/train/"
file_list = os.listdir(path) # 파일이름 불러오는 부분
for k in file_list: # 리스트안에 있는 파일들을 하나씩 빼내는 코드
img = cv2.imread(path + '/' + k) # 사진을 숫자행렬로 변경합니다.
#크롤링으로 긁어온 사진들은 크기가 다 달라, 일괄적으로 변경해줍니다.
resize_img = cv2.resize(img, (32 , 32), interpolation=cv2.INTER_CUBIC)
cv2.imwrite('/content/drive/MyDrive/animal/train_resize/' + k, resize_img)
# resize 한 이미지를 저장
import cv2
import os
import numpy as np
path = "/content/drive/MyDrive/animal/test/"
file_list = os.listdir(path) # 파일이름 불러오는 부분
for k in file_list: # 리스트안에 있는 파일들을 하나씩 빼내는 코드
img = cv2.imread(path + '/' + k) # 사진을 숫자행렬로 변경합니다.
resize_img = cv2.resize(img, (32 , 32), interpolation=cv2.INTER_CUBIC)
cv2.imwrite('/content/drive/MyDrive/animal/test_resize/' + k, resize_img)
===============================================
## 해달과 수달 데이터를 불러옵니다.
# 이미지 데이터와 라벨위치
train_image = '/content/drive/MyDrive/animal/train_resize/'
test_image = '/content/drive/MyDrive/animal/test_resize/'
train_label = '/content/drive/MyDrive/animal/train_label.csv'
test_label = '/content/drive/MyDrive/animal/test_label.csv'
# 데이터 로드
x_train = image_load(train_image)
y_train = label_load(train_label)
x_test = image_load(test_image)
y_test = label_load(test_label)
print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)
##VGG16
from tensorflow.keras.applications import VGG16
vgg16= VGG16(weights = 'imagenet', input_shape = (32, 32, 3), include_top = False)
##드롭아웃과 L2규제 적용, 러닝레이트는 주지 않은 구성
# 1. 필요한 패키지 가져오는 코드
import tensorflow as tf # 텐써 플로우 2.0
from tensorflow.keras.models import Sequential # 모델을 구성하기 위한 모듈
from tensorflow.keras.layers import Dense, BatchNormalization, Dropout, Conv2D, MaxPooling2D ,Flatten
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical # one encoding 하는 모듈
import numpy as np
tf.random.set_seed(777)
# 2. 정규화 진행
x_train = x_train.reshape(-1, 32, 32, 3) / 255
x_test = x_test.reshape(-1, 32,32, 3) / 255
# 3. 정답 데이터를 준비한다.
# 하나의 숫자를 one hot encoding 한다. (예: 4 ---> 0 0 0 0 1 0 0 0 0 0 )
y_train = to_categorical(y_train) # 훈련 데이터의 라벨(정답)을 원핫 인코딩
y_test = to_categorical(y_test) # 테스트 데이터의 라벨(정답)을 원핫 인코딩
# 4. 모델을 구성합니다.
model = Sequential()
model.add(vgg16)
model.add( Flatten() )
model.add(Dense(100, kernel_regularizer='l2', activation = 'relu', input_shape = (32*32, )))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dense(100, kernel_regularizer='l2', activation = 'relu') )
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dense(2, activation = 'softmax'))
# 5. 모델을 설정합니다. ( 경사하강법, 오차함수, 러닝레이트 정의. )
model.compile(optimizer='Adam',
loss = 'binary_crossentropy',
metrics=['acc']) # 학습과정 정확도를 보려고
#6. 모델을 훈련시킵니다.
from tensorflow.keras.callbacks import EarlyStopping
# 콜백을 정의합니다.
callbacks = [EarlyStopping(monitor = 'val_acc', patience = 10, verbose = 1)]
# callbacks 인자를 통해 정의한 콜백을 전달합니다.
history= model.fit(x_train, y_train,
batch_size = 100,
validation_data = (x_test, y_test),
epochs = 200,
callbacks = callbacks)
# 7.모델을 평가합니다. (오차, 정확도가 출력됩니다.)
model.evaluate(x_test, y_test)
train_acc_list=history.history['acc']
train_acc_list
test_acc_list=history.history['val_acc']
test_acc_list
import matplotlib.pyplot as plt
x = np.arange( len(train_acc_list) )
plt.plot( x, train_acc_list, label='train acc')
plt.plot( x, test_acc_list, label='test acc', linestyle='--')
plt.ylim(0, 1)
plt.legend(loc='lower right')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.show()
model.save('/content/drive/MyDrive/animal/animal_vgg_model2.h5')
===================================================
# 모델을 불러와서 해달이나 수달 이미지 한장 예측하기
# 1. 모델을 불러옵니다.
from tensorflow.keras.models import load_model
new_model = load_model('/content/drive/MyDrive/animal/animal_vgg_model2.h5')
# 2.모델을 평가합니다. (오차, 정확도가 출력됩니다.)
new_model.evaluate(x_test, y_test)
###
[0.28914597630500793, 0.9399999976158142]
# 테스트할 이미지 한 장을 불러와 전처리하고, 모델에 넣어 예측해봅니다!
import tensorflow as tf
import cv2
img_path = '/content/drive/MyDrive/animal/img/19.jpg'
img = cv2.imread(img_path)
#img = cv2.bitwise_not(img)
#print(img.shape)
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
resized_images=tf.image.resize_images(img, (32, 32))
print(resized_images.shape)
import numpy as np
x2 =tf.reshape(resized_images, [-1,32,32,3])
print(x2.shape)
from tensorflow.keras.models import load_model
new_model = load_model('/content/drive/MyDrive/animal/animal_vgg_model2.h5')
results = new_model.predict(x2,steps=1)
np.argmax(results) # 1 이 해달, 0 이 수달
====================================================
## 비슷하게 귀여운 동물들인 해달과 수달을 잘 구분합니다.