MLP-MINST

Doya·2025년 5월 8일

ESTSOFT_AI개발7기

목록 보기
36/43

개요

  • MINST 실습 내용 정리

MINST 데이터베이스
손으로 쓴 숫자들로 이루어진 대형 데이터베이스
다양한 화상 처리 시스템을 트레이닝 하기 위해 일반적으로 사용됨

실습 코드

  • 데이터 가져오기 및 데이터 분리
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()

이미지 형태 확인

fig, axs = plt.subplots(1, 10, figsize = (10,6))
for i in range(10):
    axs[i].imshow(train_images[i])
plt.show()

데이터 전처리 과정

train_images = train_images.reshape((60000, 784)).astype('float32') / 255.0
test_images = test_images.reshape((10000, 784)).astype('float32') / 255.0
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

train_images = train_images.reshape((60000, 784)).astype('float32') / 255.0
test_images = test_images.reshape((10000, 784)).astype('float32') / 255.0

  • 이미지 전처리
  • 28 * 28 차원의 1차원 벡터로 변환 -> 신경망에 넣기 위함
  • 255.0으로 나누어서 0~1 사이로 조정 -> 입력값이 너무 크면 학습이 불안정하거나 느려질수 있음
  • 정규화를 통해 모델이 더 빠르고 정확하게 수렴하도록 도와줌

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

  • 레이블 전처리
  • One-Hot encoding으로 변환함
  • 다중 클래스 분류에서 categorical_crossentropy와 같은 손실 함수와 호환되기 위해 필수적

모델 학습 및 정확도 확인

model = Sequential([
    Input(shape=(784,)),  #  입력 차원 수정
    Dense(512, activation='relu'),
    Dropout(0.1),
    Dense(16, activation='relu'),
    Dropout(0.1),
    Dense(10, activation='sigmoid') # sigmoid
])
model.compile(optimizer='rmsprop', loss='mse', metrics=['accuracy'])
model.fit(train_images, train_labels, batch_size=128, epochs=100, verbose=1)
print(model.predict(train_images))
predictions = model.predict(train_images)

test_loss, test_acc = model.evaluate(test_images, test_labels)
print('정확도: ',test_acc)
print('손실도: ',test_loss)

정확도: 0.9840999841690063
손실도: 0.0026808881666511297

opencv를 이용하여 테스트

import cv2
image  =  cv2.imread('./images/4.png', cv2.IMREAD_GRAYSCALE)
plt.imshow(image)
plt.show()

image = cv2.resize(image, (28,28))
image = image.astype('float32')
image = image.reshape(1, 784)
image = 255-image
image = image/255.0

pred = model.predict(image.reshape(1,784), batch_size = 1)

pred.argmax()

이미지

예측 결과

profile
안녕하세요. 도야입니다

0개의 댓글