[SWTT] Getting Started with MNIST using Tensorflow and Keras

Posted by

[SWTT] Tensorflow와 Keras: MNIST 시작하기

Tensorflow와 Keras는 머신 러닝 및 딥 러닝을 위한 라이브러리로서 매우 인기 있는 프레임워크입니다. 이들을 사용하여 MNIST 데이터셋을 이용한 숫자 인식 모델을 만들어 보겠습니다.

Step 1: 데이터 불러오기

먼저 Tensorflow에서 제공하는 MNIST 데이터를 불러옵니다.

    <code>
      import tensorflow as tf
      from tensorflow.keras.datasets import mnist

      (x_train, y_train), (x_test, y_test) = mnist.load_data()
    </code>
  

Step 2: 데이터 전처리

데이터를 0과 1 사이의 값으로 정규화하고, 이미지 데이터를 28×28 크기로 reshape합니다.

    <code>
      x_train = x_train / 255.0
      x_test = x_test / 255.0

      x_train = x_train.reshape(-1, 28, 28, 1)
      x_test = x_test.reshape(-1, 28, 28, 1)
    </code>
  

Step 3: 모델 구성

Keras를 사용하여 간단한 컨볼루션 신경망(CNN) 모델을 구성합니다.

    <code>
      model = tf.keras.models.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(128, activation='relu'),
          tf.keras.layers.Dense(10, activation='softmax')
      ])
    </code>
  

Step 4: 모델 컴파일 및 학습

모델을 컴파일하고 훈련 데이터를 이용하여 모델을 학습시킵니다.

    <code>
      model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
      model.fit(x_train, y_train, epochs=5)
    </code>
  

Step 5: 모델 평가

테스트 데이터를 이용하여 모델을 평가합니다.

    <code>
      test_loss, test_acc = model.evaluate(x_test, y_test)
      print("Test accuracy:", test_acc)
    </code>
  

이제 Tensorflow와 Keras를 사용하여 MNIST 데이터셋을 이용한 숫자 인식 모델을 만들어 보았습니다. 더 많은 머신 러닝과 딥 러닝 프로젝트를 통해 실력을 향상시켜보세요!

0 0 votes
Article Rating

Leave a Reply

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x