Study/class note

딥러닝 / 패션 mnist 신경망에 사진을 넣고 잘 예측하는지 확인하기(+구글 코랩)

chanzae 2022. 4. 10. 23:21

11 패션 mnist 신경망에 사진을 넣고 잘 예측하는지 확인하기

패션 mnist 데이터는 옷과 신발, 가방과 같은 데이터셋인데 28x28의 흑백이미지 데이터입니다.

 

문제81. 패션 mnist 데이터를 불러와서 이미지 하나를 시각화하시오.

# 1. 패션 mnist 데이터를 불러오는 코드
import tensorflow as tf
from tensorflow.keras.datasets.fashion_mnist import load_data

(x_train, y_train), (x_test, y_test) = load_data()
print(x_train.shape) #(60000,28,28)

#2. 시각화 하는 코드
import matplotlib.pyplot as plt

aa = x_train[0].reshape(28,28)
plt.imshow(aa, cmap = 'gray')

 

 

문제82. 위의 x_train[0]  데이터의 정답 y_train[0] 이 무엇인지 출력하시오 !

import numpy as np

target_dict = {   #정답 정보
 0: 'T-shirt/top',
 1: 'Trouser',
 2: 'Pullover',
 3: 'Dress',
 4: 'Coat',
 5: 'Sandal',
 6: 'Shirt',
 7: 'Sneaker',
 8: 'Bag',
 9: 'Ankle boot',
}

label = y_train[0]
print(label)  #9 출력 <- 정답 'Ankle boot'

 

 

문제83. 어제 마지막 코드 중 유하나님이 작성한 코드를 가져와서 학습 시켜서 모델을 fashion_model.h5로 저장하시오.

# 1. 필요한 패키지를 불러옵니다. 
import  tensorflow  as  tf
from  tensorflow.keras.models  import  Sequential
from  tensorflow.keras.layers  import  Dense, Flatten
import  numpy  as  np
tf.random.set_seed(777)   # 만약 시드값을 설정하지 않게 되면 가중치의 초기값이 너무 어이없는 값부터 시작되면
                                 # 학습이 잘 안되고 수렴을 못하므로 777 정도로 주면 비교적 적당한 가중치 초기값이
                                 # 생성이 되어져서 잘 수렴할 수 있게 됩니다. 

#2. 모델을 구성합니다.
model = Sequential()
model.add(Flatten(input_shape=(784, )  )  ) # 입력층(0층)
model.add(Dense( 500, activation='relu') )  # 은닉층(1층)
model.add(Dense( 300, activation='relu') )  # 은닉층(2층)
model.add(Dense( 100, activation='relu') )  # 은닉층(2층)
model.add(Dense( 10, activation='softmax')  )  # 출력층(3층)

#3. 입력 데이터 만들기
from tensorflow.keras.datasets.fashion_mnist import load_data
(x_train, y_train), (x_test, y_test) = load_data()

# 3차원 --> 2차원으로 변경하면서 정규화 작업을 수행합니다.
x_train = x_train.reshape(60000, 28*28)
x_test = x_test.reshape(10000, 28*28) 

x_train = x_train /255.0
x_test = x_test /255.0

#4. 정답 데이터 만들기
from  tensorflow.keras.utils  import  to_categorical

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)


#5. 모델을 설정합니다.
model.compile(optimizer='adam',  # 경사하강법의 종류중에 adam 사용하겠다.
                   loss='categorical_crossentropy',  # 오차함수를 크로스 엔트로피 함수 사용하겠다.
                   metrics=['acc'] )

#6. 모델을 훈련합니다.
model.fit(x_train, y_train, epochs=250 , batch_size=1000)

#7. 모델을 평가합니다.
model.evaluate(x_test, y_test)

#8. 모델 저장
model.save("c:\\deep\\fashion_model.h5")

 

 

ㅇ구글 코랩 사용하기

구글 코랩에서 파이썬 실행

> 코드 돌리기 전에 런타임 GPU로 바꿔주기(런타임 유형)

#8. 모델저장
model.save("fashion_model.h5")
%pwd       #위치확인 - 구글 코랩이 리눅스라서 리눅스 명령어 사용함

 

 

문제85. 저장한 모델인 fashion_model.h5를 불러와서 신경망을 구성한 후 테스트 데이터의 정확도를 확인하시오.

from tensorflow.keras.models import load_model
new_model = load_model("fashion_model.h5")
new_model.evaluate(x_test,y_test)

주피터노트북에서 돌릴경우 모델 로드할 때 파일경로 "c:\\~~~" 전부 써줘야 하지만 코랩에서 실행할 경우에는 파일경로 지정해주지 않아도 됨.

(세션 끝나면 초기화 되니까, 모델을 저장할 경우 컴퓨터로 내리거나 구글 드라이브 위치 지정하면 됨)

 

 

문제86. 한 장의 사진을 넣고 시각화 합니다.

import matplotlib.pyplot as plt

aa = x_test[4].reshape(28,28)
plt.imshow(aa, cmap = 'gray')

 

문제87. 위의 시각화 된 사진을 new_model에 입력해서 예측값을 출력합니다.

result = new_model.predict(x_test[4].reshape(1,784))

import numpy as np
np.argmax(result)  # 6 출력

 

문제88. 위의 테스트 데이터 4번의 정답을 확인하시ㅗㅇ.

t = y_test[4]
np.argmax(t)  # 정답 6

-> 예측도 shirt, 정답도 shirt

 

 

문제89. 구글에서 찾아 다운로드 받은 사진(dress.jpg)을 코랩에 올리시오.

문제90. 드레스 사진의 바탕을 검은색으로 바꾸시오.

import cv2

frame = 'dress.jpg'
img = cv2.imread(frame)  #이미지를 숫자로 불러옴
img = cv2.bitwise_not(img)  #이미지의 바탕을 검은색 코드로 변경하는 코드

plt.imshow(img)

 

 

문제91. 바탕을 검은색으로 변경한 이미지를 흑백처리 하시오.

# 로드한 사진 흑백처리
import numpy as np

def rgb2gray(rgb):  # 흑백으로 색깔을 변경하기 위한 함수 
    return np.dot(rgb[ :, :, : ], [0.299, 0.587, 0.114])                    

gray_img = rgb2gray(img)  # 컬러를 흑백으로 변환 
plt.imshow(gray_img)
gray_img.shape  #(638,427)

 

 

문제92. 신경망에 위의 사진을 넣기 위해 사이즈를 28x28로 변경하시오.

resize_img = cv2.resize( gray_img, (28,28), interpolation = cv2.INTER_CUBIC)
plt.imshow(resize_img, cmap = 'gray')

 

 

문제93. 위의 resize한 이미지를 fashion_model.h5 모델에 넣고 예측값을 출력하시오.

x = resize_img.reshape(1,784)

result2 = new_model.predixt(x)

a2 = np.argmax(result2)

target_dict = {
 0: 'T-shirt/top',
 1: 'Trouser',
 2: 'Pullover',
 3: 'Dress',
 4: 'Coat',
 5: 'Sandal',
 6: 'Shirt',
 7: 'Sneaker',
 8: 'Bag',
 9: 'Ankle boot',
}

target_dict[a2]  #3 Dress 출력 <- 정답

 

 

문제94. 인터넷에서 티셔츠나 드래스 사진 등을 다운 받아 데이터 전처리를 하고 신경망에 넣어 예측하시오.

#1. 데이터 로드
import cv2
import matplotlib.pyplot as plt


j= 'sandal.jpg'
img = cv2.imread(j,0)  # cv2.imread에서 회색조로 불러오기
img = cv2.bitwise_not(img)  # 이미지 바탕 검정으로 변환
print('img.shape :',img.shape)  #img.shape : (28, 28)

plt.imshow(img, cmap = 'gray')  #이미지 확인
plt.show()

# 리사이즈
resize_img = cv2.resize(img,(28,28), interpolation = cv2.INTER_CUBIC)
print(resize_img.shape)  #(28,28)
plt.imshow(resize_img)
plt.show()

#label 정보
target_dict = {
 0: 'T-shirt/top',
 1: 'Trouser',
 2: 'Pullover',
 3: 'Dress',
 4: 'Coat',
 5: 'Sandal',
 6: 'Shirt',
 7: 'Sneaker',
 8: 'Bag',
 9: 'Ankle boot',
}


#예측
test = resize_img.reshape(1,784)
result = new_model.predict(test)
print(f'예측 : {target_dict[np.argmax(result)]}')
print(f'정답 : sandal')  # 8로 예측함

예측 : Bag   <- 틀림
정답 : sandal  

반응형