전공기초/AI

[AI] 과제 #02. Logistic Regression MNIST

lxvxxu 2025. 4. 14. 22:01

 

Google Colaboratory

 

줄여서 'Colab', '코랩'이라고 한다. 브라우저 내에서 Python 스크립트를 작성하고 실행할 수 있다. 무료로 GPU를 사용할 수 있으며 공유가 간편하다.

 

Colab을 사용하면 Code 몇 줄만으로 Image Data Set를 가져오고, 이 Data Set로 Image 분류기를 학습시키며, 모델을 평가할 수 있다. Colab은 Google Cloud Server에서 Code를 실행하므로 사용 중인 Computer의 성능과 관계 없이 GPU 및 TPU를 포함한 Google H/W의 성능을 활용할 수 있다.

 

또한 Google Drive에 저장된 파일을 Colaboratory에서 불러올 수 있다.

from google.colab import drive
drive.mount('/content/drive')

 


sklearn(사이킷런)이란?

scikit-learn의 약자로 python을 대표하는 머신러닝 분석 시 유용하게 사용할 수 있는 라이브러리이다.

여러 가지 머신러닝 모듈로 구성되어 있으며, 오픈 소스로 공개되어 있다.

초심자가 기계 학습을 배우기 시작할 때 적합한 라이브러리이다.

 

sklearn에서는 mini Dataset을 제공한다.

from sklearn.datasets import fetch_openml
mnist = fetch_openml('mnist_784')
mnist.data.shape, mnist.target.shape
# (70000, 784)

 

 

Dataset을 train data와 test data로 split하기

1. 직접 구현하기

split_ratio = 0.9
n_train = int(mnist.data.shape[0] * split_ratio)
print(n_train)
# 63000

n_test = mnist.data.shape[0] - n_train
print(n_test)
#7000

X_train = mnist.data[:n_train]
y_train = mnist.target[:n_train]
print(X_train.shape, y_train.shape)
# ((63000, 784), (63000,))

X_test = mnist.data[n_train:]
y_test = mnist.target[n_train:]
print(X_test.shape, y_test.shape)
# ((7000, 784), (7000,))

# Checking uniqueness of the target
import numpy as np
print(np.unique(y_train))
# array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], dtype=object)

 

 ※ 추가로 shuffling하고 싶다면 numpy.random.permutation을 사용하면 된다. 

 

 

2. sklearn에서 제공하는 라이브러리 사용하기

train_test_split 모듈을 사용한다. 

default로 train:test = 0.75:0.25 ratio로 분류한다.

import numpy as np
from sklearn.model_selection import train_test_split

# generate samples
sample = np.arange(100)
print(sample)

# array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
#       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
#       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
#       51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
#       68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
#       85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])

print(train_test_split(sample))
#[array([46, 66, 42, 54, 58, 90, 11, 93, 28, 97, 17, 31, 55, 27, 74, 25, 91,
#         8, 57,  9, 86, 39, 53, 73, 98, 44, 60, 43, 12, 82, 69,  2, 89, 83,
#        10, 61,  0, 59, 99, 16, 88, 71, 68, 36, 20, 80, 76, 41, 30, 18, 22,
#        75, 34, 50, 79, 37, 78, 52, 32, 14, 63, 92, 87,  5, 21, 24, 38, 72,
#        96, 35, 51, 33, 94,  4, 65]),
# array([84, 26,  6,  1, 62, 81, 15, 19, 29, 23,  7, 56, 77, 45, 49, 95,  3,
#        85, 67, 13, 70, 40, 48, 64, 47])]

X_train, X_test = train_test_split(sample)
print(X_train.shape, X_test.shape)
# ((75,), (25,))

 


 

 

분류 (Classification)

실수 or 정수 등 수치로 정의된 것이 아닌

[강아지, 고양이, 호랑이, ... ] 등 Class로 정의된 종속변수를 특성(Features)들의 연산을 통해 분류해내는 것

 

 

 


참고 문헌

https://namu.wiki/w/Google%20Colaboratory

 

Google Colaboratory

Colaboratory(줄여서 'Colab'이라고 함)을 통해 브라우저 내에서 Python 스크립트를 작성하고 실행

namu.wiki

 

https://jaylala.tistory.com/entry/%EB%94%A5%EB%9F%AC%EB%8B%9D-with-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EB%B6%84%EB%A5%98Classification-MNIST-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%82%AC%EC%9A%A9

 

[딥러닝 with 파이썬] 분류(Classification) / MNIST 데이터 사용

[본 포스팅은 "Must Have 텐초의 파이토치 딥러닝 특강"의 내용을 참조하여 작성하였습니다] 이번에는 파이토치를 활용해서 분류기(Classifier)를 만들어 보겠습니다. 분류(Classification)는 실수 또는 정

jaylala.tistory.com

 

 

https://jimmy-ai.tistory.com/261

 

[Sklearn] 파이썬 MNIST 데이터셋 불러오기, 숫자 시각화 예제

파이썬 사이킷런으로 손글씨 숫자 인식 데이터셋 다루기 파이썬에서 손글씨 숫자 인식 데이터셋인 MNIST를 불러오고 데이터를 몇개 뽑아 숫자 글씨의 상태를 시각화해보는 예제를 살펴보도록 하

jimmy-ai.tistory.com

ㅌ`

https://teddylee777.github.io/scikit-learn/sklearn%EC%9C%BC%EB%A1%9C-mnist-%EC%86%90%EA%B8%80%EC%94%A8%EB%B6%84%EB%A5%98%ED%95%98%EA%B8%B0/

 

sklearn 라이브러리를 활용한 mnist 손글씨 10분만에 70,000개 분류하기

sklearn 라이브러리를 활용하여 mnist 손글씨 데이터를 분류하고 시각화 해보도록 하겠습니다.

teddylee777.github.io

https://scikit-learn.org/stable/index.html

 

scikit-learn: machine learning in Python — scikit-learn 1.6.1 documentation

Comparing, validating and choosing parameters and models. Applications: Improved accuracy via parameter tuning. Algorithms: Grid search, cross validation, metrics, and more...

scikit-learn.org

 

 

https://myoongs.tistory.com/6

 

[파이썬] 구글 코랩(colab)으로 파일 불러오기 - 구글 드라이브 연동 (마운트)

구글 코랩에서 특정 파일을 연결하여 사용하는 방법이 몇 가지 있는데, 그 중 구글 드라이브에서 파일 불러오는 방법을 정리해보겠다. 구글 드라이브에서 파일 불러오기 (마운트)내 구글 드라

myoongs.tistory.com

 

'전공기초 > AI' 카테고리의 다른 글

[AI] ABC - AI 모델, Big Data, Computing Resource  (0) 2025.05.06