LAB/Python

Deep Learning(딥러닝) - 알파벳 대문자 손 글씨 학습 시키기

it-lab-0130 2024. 11. 26. 20:43

 

 

알파벳 대문자 손 글씨 이미지 학습 모델 만들기

출처 입력

1. 알파벳 대문자 손 글씨 이미지 파일을 찾아 Pandas로 CSV 파일 불러오기

2. 데이터 전처리 과정

- 데이터 컬럼을 확인하고 rename()을 사용하여 첫 번째 열의 이름을 'label'로 변경

- drop()을 사용하여 'label' 열을 제외한 나머지 열을 X에 저장하고, 'label' 열을 y에 저장

- len(y.unique())를 사용하여 고유한 속성 수를 계산

3. 훈련셋 과 테스트셋으로 분할

4. CNN모델 생성

- Conv2D(), MaxPooling2D(), Dropout(), Flatten(), Dense()를 사용

5. 모델 컴파일

- 손실함수 (categorical_crossentropy) : A~Z 까지의 데이터에서 비슷한걸 찾기 때문에 다항 문제 분류 손실함수 사용

6. 모델 최적화 설정

- ModelCheckpoint()을 사용하여 모델을 저장 설정

- EarlyStopping()을 사용하여 최적의 모델 일때 조기 종료 설정

7. 모델 학습

8. 모델 평가

9. 학습 손실 그래프 출력

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os

from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.utils import to_categorical  # np_utils 대신 to_categorical을 직접 가져오기
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.metrics import confusion_matrix
from sklearn.utils import shuffle
# Warning 메시지 무시
import warnings
warnings.filterwarnings('ignore')

sns.set()

# 데이터셋 불러오기
dataset = pd.read_csv("../data/archive/A_Z Handwritten Data/A_Z Handwritten Data.csv").astype('float32')
dataset.rename(columns={'0':'label'}, inplace=True)

# 데이터 분할
X = dataset.drop('label', axis=1)
y = dataset['label']

# 고유 클래스 수 계산
num_classes = len(y.unique())

# y를 범주형 데이터로 변환
y = to_categorical(y)

# print("shape:", X.shape)
# print("columns count:", len(X.iloc[1]))
# print("784 = 28X28")
#
# X.head()

# train_test_split으로 데이터 나누기
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# numpy 배열로 변환 후 reshape
X_train = X_train.values.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255
X_test = X_test.values.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255


# CNN 모델 생성
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))  # num_classes로 변경

# 모델 컴파일
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# 모델 최적화 설정
MODEL_DIR = '../data/model/'
if not os.path.exists(MODEL_DIR):
    os.mkdir(MODEL_DIR)

modelpath = "../data/atoz_cnn_model.keras"
checkpointer = ModelCheckpoint(filepath = modelpath, monitor = 'val_loss', verbose = 1, save_best_only = True)
early_stopping_callback = EarlyStopping(monitor = 'val_loss', patience = 5)

# 모델 학습
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=30, batch_size=200, verbose=1,callbacks = [early_stopping_callback,checkpointer])

# 모델 평가
scores = model.evaluate(X_test, y_test, verbose=0)
print("CNN Score:", scores[1])

# 학습 손실 그래프
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
 
대표사진 삭제

사진 설명을 입력하세요.

대표사진 삭제

사진 설명을 입력하세요.

최적화 모델 저장 파일

사진 삭제

사진 설명을 입력하세요.

import numpy as np
from keras.models import load_model
from PIL import Image

# Load the pre-trained model
model_path = '../data/atoz_cnn_model.keras'  # 경로를 알맞게 설정하세요
model = load_model(model_path)

# Load and preprocess the image
image_path = '../data/a.jpg'  # 경로를 알맞게 설정하세요
image = Image.open(image_path).convert('L')  # Convert to grayscale
image = image.resize((28, 28))  # Ensure the size is 28x28

# Invert the image colors if needed (if background is white and digit is black)
image_data = np.array(image)
image_data = 255 - image_data  # Invert colors if necessary
image_data = image_data / 255.0  # Normalize the data
image_data = image_data.reshape(1, 28, 28, 1)  # Reshape for the model

# Make a prediction
prediction = model.predict(image_data)
predicted_class = np.argmax(prediction)  # Get the class with the highest probability

print(f"Predicted class: {predicted_class}")
 
대표사진 삭제

사진 설명을 입력하세요.

대표사진 삭제

사진 설명을 입력하세요.