반응형

TensorFlow Lite는 구글이 개발한 TensorFlow의 경량 버전으로, 모바일 기기 및 임베디드 시스템에서 딥러닝 모델을 실행하기 위해 최적화된 라이브러리입니다. TensorFlow Lite는 딥러닝 모델의 크기와 성능을 최적화하여 모바일 기기에서도 효율적으로 동작할 수 있도록 합니다.

< TensorFlow Lite 특징 >

경량화: TensorFlow Lite는 모바일 기기와 임베디드 시스템의 제한된 자원을 고려하여 딥러닝 모델의 크기와 연산량을 최적화합니다. 이를 통해 모바일 환경에서도 효율적으로 모델을 실행할 수 있습니다.
하드웨어 가속: TensorFlow Lite는 하드웨어 가속을 지원하여 모바일 기기의 GPU, DSP 등을 활용하여 딥러닝 연산을 가속화할 수 있습니다. 이로 인해 모델의 추론 속도가 향상됩니다.
모바일 지원: TensorFlow Lite는 Android 및 iOS와 같은 주요 모바일 플랫폼에서 사용할 수 있도록 지원합니다. 또한, 임베디드 보드와 같은 다양한 장치에서도 실행 가능합니다.
모델 컨버터: TensorFlow Lite는 TensorFlow 모델을 TensorFlow Lite 모델로 변환하는 컨버터를 제공합니다. 이를 통해 기존에 훈련된 TensorFlow 모델을 모바일에서 실행 가능한 형식으로 변환할 수 있습니다.
지원되는 모델 형식: TensorFlow Lite는 다양한 모델 형식을 지원합니다. TensorFlow 모델을 변환하여 사용할 수 있으며, TensorFlow 모델 최적화 도구를 사용하여 모델 크기를 최소화할 수도 있습니다.
On-device 추론: TensorFlow Lite는 모바일 기기에서 모델을 로드하고 추론을 직접 수행할 수 있습니다. 이를 통해 모바일 애플리케이션에서 실시간으로 딥러닝 모델을 활용할 수 있습니다.
Custom 모델 지원: TensorFlow Lite는 사용자 정의 연산자를 지원하므로 사용자가 원하는 연산자를 직접 구현하고 모델에 통합할 수 있습니다.
TensorFlow Lite는 모바일 애플리케이션에서 딥러닝을 활용하고자 하는 개발자들에게 매우 유용한 도구이며, 경량화된 딥러닝 모델을 사용하여 모바일 기기에서 실시간 추론을 구현하는 데에 적합합니다. 또한, TensorFlow Lite는 TensorFlow와 통합되어 있어 TensorFlow에서 훈련한 모델을 간편하게 모바일 환경에서 실행할 수 있도록 지원합니다.

 

//
//  MNIST - TENSORFLOWLITE
//
//  Created by netcanis on 2023/07/20.
//

import tensorflow as tf
import dataset_loader
import model_tester


# Load MNIST data
training_images, training_labels, test_images, test_labels = dataset_loader.load_dataset("data/MNIST")

# Reshape the data
# 배열의 차원을 변경하여 크기를 자동으로 변경한다. (-1은 해당 차원의 크기를 자동으로 조정하라는 뜻)
training_images = training_images.reshape(-1, 28, 28, 1)
test_images = test_images.reshape(-1, 28, 28, 1)

# Print the image shapes
# reshape - Training Images shape: (60000, 28, 28, 1)
# reshape - Test Images shape: (10000, 28, 28, 1)
print("reshape - Training Images shape:", training_images.shape)
print("reshape - Test Images shape:", test_images.shape)

# Normalize the pixel values
training_images = training_images / 255.0
test_images = test_images / 255.0

# Assign images and labels to x_train, y_train, x_test, y_test
x_train, y_train = training_images, training_labels
x_test, y_test = test_images, test_labels




#
# TensorFlow Lite 모델 저장 (tflite)
#

# TensorFlow Keras model
keras_model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax') # 0~9 총 10개 클래스
])

# Train the model
keras_model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
keras_model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))

# Convert the model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
tflite_model = converter.convert()

# Save the TensorFlow Lite model
with open('tflite_mnist_model.tflite', 'wb') as file:
    file.write(tflite_model)

print("Complete Save the TensorFlow Lite model.")




#
# TEST
#

model_file = "tflite_mnist_model.tflite"
model_tester.test_model("data/MNIST", model_file)

# Error rate: 1.44%

 

2023.07.19 - [AI] - MNIST 데이터셋 다운로드

2023.07.19 - [AI] - MNIST 데이터셋을 이미지 파일로 복원

2023.07.19 - [AI] - MNIST 데이터셋 로더

2023.07.19 - [AI] - MNIST 모델 테스터

2023.07.19 - [AI] - MINST - SVC(Support Vector Classifier)

2023.07.19 - [AI] - MNIST - RandomForestClassifier

2023.07.19 - [AI] - MNIST - Keras

2023.07.19 - [AI] - MNIST - TensorFlowLite

 

 

 

반응형

'개발 > AI,ML,ALGORITHM' 카테고리의 다른 글

SARSA  (0) 2023.08.28
Q-learning  (0) 2023.08.28
MNIST - Keras  (0) 2023.07.19
MNIST - RandomForestClassifier  (0) 2023.07.19
MINST - SVC(Support Vector Classifier)  (0) 2023.07.19
블로그 이미지

SKY STORY

,
반응형

Keras 모델 학습

Keras는 딥러닝 모델을 쉽게 구축하고 훈련할 수 있도록 설계된 오픈 소스 딥러닝 라이브러리입니다. François Chollet이 개발한 Keras는 사용자 친화적인 API를 제공하여 TensorFlow, Theano, CNTK 등의 백엔드 엔진에서 실행할 수 있습니다. 하지만 2019년 9월 기준으로 TensorFlow 2.0부터는 Keras가 TensorFlow의 공식 고수준 API로 통합되어 TensorFlow의 일부가 되었습니다.

 

< Keras 특징 >

사용자 친화적인 API: Keras는 직관적이고 간결한 API를 제공하여 신경망 모델을 쉽게 설계할 수 있도록 도와줍니다. 따라서 딥러닝 경험이 적은 사용자도 비교적 쉽게 모델을 구축하고 수정할 수 있습니다.
모듈화: Keras는 레이어, 손실 함수, 최적화 알고리즘 등을 모듈화하여 개별 구성 요소들을 조합하여 모델을 구축할 수 있도록 합니다. 이를 통해 모델의 재사용성이 높아집니다.
다양한 백엔드 지원: Keras는 다양한 딥러닝 백엔드 엔진을 지원합니다. 초기에는 Theano와 TensorFlow를 지원했으며, 현재는 TensorFlow가 공식 백엔드로 사용되고 있습니다.
모듈화된 구조: Keras는 레이어로 구성된 모델을 생성하는 함수형 API와 순차적으로 레이어를 쌓는 Sequential API를 제공합니다. 이를 통해 간단한 모델에서부터 복잡한 모델까지 다양한 구조의 신경망을 쉽게 만들 수 있습니다.
커뮤니티와 생태계: Keras는 활발한 커뮤니티와 풍부한 생태계를 갖추고 있습니다. 이로 인해 다양한 확장 기능, 사전 훈련된 모델, 유틸리티 등을 쉽게 활용할 수 있습니다.
분산 훈련 및 모델 배포: Keras는 TensorFlow를 백엔드로 사용하기 때문에 TensorFlow의 기능을 활용하여 분산 훈련과 모델 배포를 지원합니다.
가벼운 라이브러리: Keras는 간단하고 가벼운 딥러닝 라이브러리이기 때문에 처음 딥러닝을 배우는 데 적합하며, 초보자와 중급 사용자 모두에게 추천됩니다.
Keras는 이러한 특징들로 인해 딥러닝 모델 개발에 있어서 많은 사용자들에게 인기가 있으며, 다양한 응용 분야에서 활용되고 있습니다. TensorFlow를 기반으로 하기 때문에 TensorFlow와의 호환성이 뛰어난 것도 Keras의 장점 중 하나입니다.


//
//  MNIST - KERAS
//
//  Created by netcanis on 2023/07/20.
//

import numpy as np
import tensorflow as tf
import dataset_loader
import model_tester

from keras.models import load_model


# Load MNIST data
training_images, training_labels, test_images, test_labels = dataset_loader.load_dataset("data/MNIST")

# Reshape the data
# 배열의 차원을 변경하여 크기를 자동으로 변경한다. (-1은 해당 차원의 크기를 자동으로 조정하라는 뜻)
training_images = training_images.reshape(-1, 28, 28, 1)
test_images = test_images.reshape(-1, 28, 28, 1)

# Print the image shapes
# reshape - Training Images shape: (60000, 28, 28, 1)
# reshape - Test Images shape: (10000, 28, 28, 1)
print("reshape - Training Images shape:", training_images.shape)
print("reshape - Test Images shape:", test_images.shape)

# Normalize the pixel values
training_images = training_images / 255.0
test_images = test_images / 255.0

# Assign images and labels to x_train, y_train, x_test, y_test
x_train, y_train = training_images, training_labels
x_test, y_test = test_images, test_labels




#
# Keras model 파일(keras) 저장
#

# TensorFlow Keras model
keras_model = tf.keras.Sequential([
    tf.keras.layers.Reshape(target_shape=(28, 28) + (1,), input_shape=(28, 28)),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax') # 0~9 총 10개 클래스
])

# Train the model
keras_model.compile(optimizer='adam', 
                    loss='sparse_categorical_crossentropy', 
                    metrics=['accuracy'])
keras_model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test))

# Save the Keras model
keras_model.save('keras_mnist_model.h5')

print("Complete Save the Keras model.")




#
# TEST
#

model_file = "keras_mnist_model.h5"
model_tester.test_model("data/MNIST", model_file)

# Error rate: 2.26%

 

2023.07.19 - [AI] - MNIST 데이터셋 다운로드

2023.07.19 - [AI] - MNIST 데이터셋을 이미지 파일로 복원

2023.07.19 - [AI] - MNIST 데이터셋 로더

2023.07.19 - [AI] - MNIST 모델 테스터

2023.07.19 - [AI] - MINST - SVC(Support Vector Classifier)

2023.07.19 - [AI] - MNIST - RandomForestClassifier

2023.07.19 - [AI] - MNIST - Keras

2023.07.19 - [AI] - MNIST - TensorFlowLite

 

 

반응형

'개발 > AI,ML,ALGORITHM' 카테고리의 다른 글

Q-learning  (0) 2023.08.28
MNIST - TensorFlowLite  (0) 2023.07.19
MNIST - RandomForestClassifier  (0) 2023.07.19
MINST - SVC(Support Vector Classifier)  (0) 2023.07.19
MNIST 모델 테스터  (0) 2023.07.19
블로그 이미지

SKY STORY

,
반응형

이번에는 RandomForestClassifier 모델로 학습해 보았다.

 

RandomForestClassifier는 앙상블 학습(Ensemble Learning) 기법 중 하나인 랜덤 포레스트(Random Forest)를 구현한 분류(Classification) 모델입니다. 
랜덤 포레스트는 여러 개의 의사결정 트리(Decision Tree)를 결합하여 강력한 예측 모델을 만드는 알고리즘입니다.

< 랜덤 포레스트 특징 >

앙상블 학습: 랜덤 포레스트는 여러 개의 의사결정 트리를 동시에 학습하고 이들의 예측 결과를 결합하여 최종 예측을 수행합니다. 이렇게 여러 개의 모델을 결합하는 앙상블 학습은 일반적으로 단일 모델보다 더욱 강력한 예측 성능을 제공합니다.
의사결정 트리: 랜덤 포레스트의 기본 모델로 사용되는 의사결정 트리는 데이터의 특성을 기반으로 하여 분류 작업을 수행하는 모델입니다. 의사결정 트리는 특정 기준에 따라 데이터를 분할하여 예측을 수행하는 방식으로 동작합니다.
랜덤성: 랜덤 포레스트는 의사결정 트리 학습 시에 랜덤성을 도입합니다. 이는 데이터의 일부 특성을 임의로 선택하거나 데이터를 부트스트랩 샘플링하는 등의 방법으로 랜덤성을 추가함으로써 모델의 다양성을 높입니다. 이는 과적합(Overfitting)을 방지하고 모델의 일반화 성능을 향상시킵니다.
랜덤 포레스트는 다양한 분야에서 활용되며, 데이터 분류, 패턴 인식, 텍스트 분석, 이미지 분류 등 다양한 문제에 적용될 수 있습니다. 또한, 특성 중요도를 제공하여 어떤 특성이 예측에 가장 중요한 역할을 하는지를 확인할 수도 있습니다.

 

//
//  MNIST - RANDOMFORESTCLASSIFIER
//
//  Created by netcanis on 2023/07/20.
//

import cv2
import os
import numpy as np
import pickle
import dataset_loader
import model_tester

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC


# Load MNIST data
training_images, training_labels, test_images, test_labels = dataset_loader.load_dataset("data/MNIST")

# Reshape the data
# 배열의 차원을 변경하여 크기를 자동으로 변경한다. (-1은 해당 차원의 크기를 자동으로 조정하라는 뜻)
training_images = np.reshape(training_images, (len(training_images), -1))
test_images = np.reshape(test_images, (len(test_images), -1))

# Print the image shapes
# reshape - Training Images shape: (60000, 784)
# reshape - Test Images shape: (10000, 784)
print("reshape - Training Images shape:", training_images.shape)
print("reshape - Test Images shape:", test_images.shape)
 
# Assign images and labels to x_train, y_train, x_test, y_test
x_train, y_train = training_images, training_labels
x_test, y_test = test_images, test_labels




#
# RandomForestClassifier 파일 저장.
#

# Train the model
model = RandomForestClassifier()
model.fit(x_train, y_train)

# Evaluate the model
score = model.score(x_test, y_test)
print('Accuracy:', score)

# Save the pkl model
with open("rfc_mnist_model.pkl", "wb") as file:
    pickle.dump(model, file)

print("Save the rfc_mnist_model.pkl.")




#
# TEST
#

model_file = "rfc_mnist_model.pkl"
model_tester.test_model("data/MNIST", model_file)

# Error rate: 3.09%

 

2023.07.19 - [AI] - MNIST 데이터셋 다운로드

2023.07.19 - [AI] - MNIST 데이터셋을 이미지 파일로 복원

2023.07.19 - [AI] - MNIST 데이터셋 로더

2023.07.19 - [AI] - MNIST 모델 테스터

2023.07.19 - [AI] - MINST - SVC(Support Vector Classifier)

2023.07.19 - [AI] - MNIST - RandomForestClassifier

2023.07.19 - [AI] - MNIST - Keras

2023.07.19 - [AI] - MNIST - TensorFlowLite

 

 

 

 

반응형

'개발 > AI,ML,ALGORITHM' 카테고리의 다른 글

MNIST - TensorFlowLite  (0) 2023.07.19
MNIST - Keras  (0) 2023.07.19
MINST - SVC(Support Vector Classifier)  (0) 2023.07.19
MNIST 모델 테스터  (0) 2023.07.19
MNIST 데이터셋 로더  (0) 2023.07.19
블로그 이미지

SKY STORY

,
반응형

이후 구현할 머신러닝 모델 구현을 위해 데이터 셋 로더 함수를 만들어 보았다.
이 함수는 데이터 셋 이미지들(트레이닝, 테스트)을 로딩하여 이미지, 라벨(해당 이미지 숫자) 리스트를 반환하도록 만들어 보았다.

//
//  MNIST 데이터셋 로더
//
//  Created by netcanis on 2023/07/20.
//


import cv2
import os
import numpy as np

#='data/MNIST'
def load_dataset(path):
    # 데이터셋 경로
    training_set_path = os.path.join(path, 'training_set')
    test_set_path = os.path.join(path, 'test_set')
    
    # Load the images from the training set
    training_images = []
    training_labels = []
    for digit_folder in os.listdir(training_set_path):
        if os.path.isdir(os.path.join(training_set_path, digit_folder)):
            label = int(digit_folder)
            for index, image_file in enumerate(os.listdir(os.path.join(training_set_path, digit_folder))):
                if image_file.endswith('.png') or image_file.endswith('.jpg'):
                    image = cv2.imread(os.path.join(training_set_path, digit_folder, image_file))
                    image = cv2.resize(image, (28, 28))

                    # Convert color image to grayscale if necessary
                    if image.shape[2] > 1:
                        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

                    # Print image path
                    print(str(index).zfill(5) + " " + os.path.join(training_set_path, digit_folder, image_file))

                    training_images.append(image)
                    training_labels.append(label)

    # Load the images from the test set
    test_images = []
    test_labels = []
    for digit_folder in os.listdir(test_set_path):
        if os.path.isdir(os.path.join(test_set_path, digit_folder)):
            label = int(digit_folder)
            for index, image_file in enumerate(os.listdir(os.path.join(test_set_path, digit_folder))):
                if image_file.endswith('.png') or image_file.endswith('.jpg'):
                    image = cv2.imread(os.path.join(test_set_path, digit_folder, image_file))
                    image = cv2.resize(image, (28, 28))

                    # Convert color image to grayscale if necessary
                    if image.shape[2] > 1:
                        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

                    # Print image path
                    print(str(index).zfill(5) + " " + os.path.join(test_set_path, digit_folder, image_file))

                    test_images.append(image)
                    test_labels.append(label)

    # Convert lists to numpy arrays
    training_images = np.array(training_images)
    training_labels = np.array(training_labels)
    test_images = np.array(test_images)
    test_labels = np.array(test_labels)

    # Print the image shapes
    # Training Images shape: (60000, 28, 28) or (20000, 32, 32)
    # Test Images shape: (10000, 28, 28) or (4000, 32, 32)
    print("Training Images shape:", training_images.shape)
    print("Test Images shape:", test_images.shape)

    return training_images, training_labels, test_images, test_labels

 
 
2023.07.19 - [AI] - MNIST 데이터셋 다운로드

2023.07.19 - [AI] - MNIST 데이터셋을 이미지 파일로 복원

2023.07.19 - [AI] - MNIST 데이터셋 로더

2023.07.19 - [AI] - MNIST 모델 테스터

2023.07.19 - [AI] - MINST - SVC(Support Vector Classifier)

2023.07.19 - [AI] - MNIST - RandomForestClassifier

2023.07.19 - [AI] - MNIST - Keras

2023.07.19 - [AI] - MNIST - TensorFlowLite

 

 


 
 
 
 

반응형

'개발 > AI,ML,ALGORITHM' 카테고리의 다른 글

MINST - SVC(Support Vector Classifier)  (0) 2023.07.19
MNIST 모델 테스터  (0) 2023.07.19
MNIST 데이터셋을 이미지 파일로 복원  (0) 2023.07.19
MNIST 데이터셋 다운로드  (0) 2023.07.19
Neural Network (XOR)  (0) 2022.11.18
블로그 이미지

SKY STORY

,
반응형

data/MNIST/row/ 폴더에 다운로드된 데이터셋 정보를 이용하여 image파일로 복원하고 해당 숫자(0-9)별로 폴더를 생성하고 각 숫자에 맞게 폴더내에 저장하도록 구현해 보았다.
labels.txt에는 각각의 이미지에대한 숫자 값을 기록하였다.

//
//  MNIST 데이터셋을 이미지 파일로 복원
//
//  Created by netcanis on 2023/07/20.
//

import matplotlib.pyplot as plt
import gzip
import numpy as np
import os



# 파일 압축 해제 함수 
def decompress_file(compressed_file, decompressed_file):
    with gzip.open(compressed_file, 'rb') as f_in, open(decompressed_file, 'wb') as f_out:
        f_out.write(f_in.read())



'''
================= training_set =================
'''

# 이미지 개수 및 크기 추출
training_num_images = 60000  # 예시로는 60,000개의 이미지가 있는 것으로 가정
image_size = 28  # 이미지 크기는 28x28 픽셀

# 압축 해제할 파일 경로 (training_set)
training_image_compressed_file = 'data/MNIST/raw/train-images-idx3-ubyte.gz'
training_label_compressed_file = 'data/MNIST/raw/train-labels-idx1-ubyte.gz'

# 압축 해제된 파일 경로 (training_set)
training_image_decompressed_file = 'data/MNIST/raw/train-images-idx3-ubyte'
training_label_decompressed_file = 'data/MNIST/raw/train-labels-idx1-ubyte'


# 이미지 저장 폴더 경로
training_set_folder = 'data/MNIST/training_set'

# 라벨 저장 파일 경로
training_label_file = 'data/MNIST/training_set/labels.txt'


# 이미지 파일 압축 해제 (training_set)
decompress_file(training_image_compressed_file, training_image_decompressed_file)

# 라벨 파일 압축 해제 (training_set)
decompress_file(training_label_compressed_file, training_label_decompressed_file)


# 이미지 저장 폴더 생성 (training_set)
if not os.path.exists(training_set_folder):
    os.makedirs(training_set_folder)


# 라벨 데이터를 numpy 배열로 변환 (training_set)
with open(training_label_decompressed_file, 'rb') as f:
    # 헤더 부분은 건너뛰기
    f.read(8)
    # 라벨 데이터 읽기
    buf = f.read()

# 라벨 배열 형태로 변환 (training_set)
training_labels = np.frombuffer(buf, dtype=np.uint8)


# 라벨 저장 파일 열기 (training_set)
with open(training_label_file, 'w') as f:
    # 이미지에 대한 라벨 값을 순차적으로 저장
    for i in range(training_num_images):
        image_path = f'{training_set_folder}/{training_labels[i]}/image_{i}.png'  # 이미지 파일 경로  (image_{i:05}.png)
        label_value = training_labels[i]  # 라벨 값

        # 이미지 파일 경로와 라벨 값을 파일에 저장
        f.write(f'{image_path}\t{label_value}\n')


# 이미지 데이터를 numpy 배열로 변환 (training_set)
with open(training_image_decompressed_file, 'rb') as f:
    # 헤더 부분은 건너뛰기
    f.read(16)
    # 이미지 데이터 읽기
    buf = f.read()

# 이미지 배열 형태로 변환
training_images = np.frombuffer(buf, dtype=np.uint8).reshape(training_num_images, image_size, image_size)


# 이미지를 순서대로 저장 (training_set)
for i, image in enumerate(training_images):
    label_value = training_labels[i]  # 라벨 값
    
    # 해당 숫자의 폴더 생성
    digit_folder = os.path.join(training_set_folder, str(label_value))
    if not os.path.exists(digit_folder):
        os.makedirs(digit_folder)

     # 이미지 파일 경로
    image_path = os.path.join(digit_folder, f'image_{i}.png')
    plt.imsave(image_path, image, cmap='gray')

 


'''
================= test_set =================
'''

# 이미지 개수 및 크기 추출
test_num_images = 10000  # 예시로는 60,000개의 이미지가 있는 것으로 가정
test_image_size = 28  # 이미지 크기는 28x28 픽셀

# 이미지 저장 폴더 경로
test_set_folder = 'data/MNIST/test_set'

# 라벨 저장 파일 경로
test_label_file = 'data/MNIST/test_set/labels.txt'

# 압축 해제할 파일 경로 (test_set)
test_image_compressed_file = 'data/MNIST/raw/t10k-images-idx3-ubyte.gz'
test_label_compressed_file = 'data/MNIST/raw/t10k-labels-idx1-ubyte.gz'

# 압축 해제된 파일 경로 (test_set)
test_image_decompressed_file = 'data/MNIST/raw/t10k-images-idx3-ubyte'
test_label_decompressed_file = 'data/MNIST/raw/t10k-labels-idx1-ubyte'


# 이미지 파일 압축 해제 (test_set)
decompress_file(test_image_compressed_file, test_image_decompressed_file)

# 라벨 파일 압축 해제 (test_set)
decompress_file(test_label_compressed_file, test_label_decompressed_file)


# 이미지 저장 폴더 생성 (test_set)
if not os.path.exists(test_set_folder):
    os.makedirs(test_set_folder)


# 라벨 데이터를 numpy 배열로 변환 (test_set)
with open(test_label_decompressed_file, 'rb') as f:
    # 헤더 부분은 건너뛰기
    f.read(8)
    # 라벨 데이터 읽기
    buf = f.read()

# 라벨 배열 형태로 변환 (test_set)
test_labels = np.frombuffer(buf, dtype=np.uint8)


# 라벨 저장 파일 열기 (test_set)
with open(test_label_file, 'w') as f:
    # 이미지에 대한 라벨 값을 순차적으로 저장
    for i in range(test_num_images):
        image_path = f'{test_set_folder}/{test_labels[i]}/image_{i}.png'  # 이미지 파일 경로  (image_{i:05}.png)
        label_value = test_labels[i]  # 라벨 값

        # 이미지 파일 경로와 라벨 값을 파일에 저장
        f.write(f'{image_path}\t{label_value}\n')


# 이미지 데이터를 numpy 배열로 변환 (test_set)
with open(test_image_decompressed_file, 'rb') as f:
    # 헤더 부분은 건너뛰기
    f.read(16)
    # 이미지 데이터 읽기
    buf = f.read()

# 이미지 배열 형태로 변환
test_images = np.frombuffer(buf, dtype=np.uint8).reshape(test_num_images, image_size, image_size)


# 이미지를 순서대로 저장 (test_set)
for i, image in enumerate(test_images):
    label_value = test_labels[i]  # 라벨 값
    
    # 해당 숫자의 폴더 생성
    digit_folder = os.path.join(test_set_folder, str(label_value))
    if not os.path.exists(digit_folder):
        os.makedirs(digit_folder)

     # 이미지 파일 경로
    image_path = os.path.join(digit_folder, f'image_{i}.png')
    plt.imsave(image_path, image, cmap='gray')

 
실행 결과는 다음과 같다.

 
2023.07.19 - [AI] - MNIST 데이터셋 다운로드

2023.07.19 - [AI] - MNIST 데이터셋을 이미지 파일로 복원

2023.07.19 - [AI] - MNIST 데이터셋 로더

2023.07.19 - [AI] - MNIST 모델 테스터

2023.07.19 - [AI] - MINST - SVC(Support Vector Classifier)

2023.07.19 - [AI] - MNIST - RandomForestClassifier

2023.07.19 - [AI] - MNIST - Keras

2023.07.19 - [AI] - MNIST - TensorFlowLite

 

 


 

반응형

'개발 > AI,ML,ALGORITHM' 카테고리의 다른 글

MNIST 모델 테스터  (0) 2023.07.19
MNIST 데이터셋 로더  (0) 2023.07.19
MNIST 데이터셋 다운로드  (0) 2023.07.19
Neural Network (XOR)  (0) 2022.11.18
2D 충돌처리  (0) 2020.12.12
블로그 이미지

SKY STORY

,
반응형

문자인식을 학습을 위해 MNIST 데이터셋을 다운로드 받아 

'data'폴더에 저장하는 코드이다.

//
//  MNIST 데이터셋 다운로드
//
//  Created by netcanis on 2023/07/20.
//

import torch
from torchvision import datasets, transforms

# MNIST 데이터셋 다운로드
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5,), (0.5,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)

 

저장 결과는 다음과 같다.

 

 

2023.07.19 - [AI] - MNIST 데이터셋 다운로드

2023.07.19 - [AI] - MNIST 데이터셋을 이미지 파일로 복원

2023.07.19 - [AI] - MNIST 데이터셋 로더

2023.07.19 - [AI] - MNIST 모델 테스터

2023.07.19 - [AI] - MINST - SVC(Support Vector Classifier)

2023.07.19 - [AI] - MNIST - RandomForestClassifier

2023.07.19 - [AI] - MNIST - Keras

2023.07.19 - [AI] - MNIST - TensorFlowLite

 

 

반응형

'개발 > AI,ML,ALGORITHM' 카테고리의 다른 글

MNIST 데이터셋 로더  (0) 2023.07.19
MNIST 데이터셋을 이미지 파일로 복원  (0) 2023.07.19
Neural Network (XOR)  (0) 2022.11.18
2D 충돌처리  (0) 2020.12.12
Generic algorithm  (0) 2020.05.19
블로그 이미지

SKY STORY

,