상세 컨텐츠

본문 제목

[딥러닝초급]the convolutional classifier

로봇-AI

by happynaraepapa 2025. 2. 24. 13:54

본문

sources:
https://www.kaggle.com/code/ryanholbrook/the-convolutional-classifier

The Convolutional Classifier

Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources

www.kaggle.com

이번 코스에서
In this course, you'll:

Use modern deep-learning networks to build an image classifier with Keras
케라스와딥러닝네트워크 기술이 이용하여 이미지를 인지하는 분류기를 만들것.

Design your own custom convnet with reusable blocks
재사용 가능한 블록을 이용해서 나만의 커스텀 convnet(컨브이넷)을 만들것.

Learn the fundamental ideas behind visual feature extraction
단순한 이미지 피쳐 추출의 뒤쪽에 숨겨진 근본적인 아이디어를 배울 것.

Master the art of transfer learning to boost your models
모델을 부스팅하기 위한 트랜스퍼 러닝 기술 배울 것.

Utilize data augmentation to extend your dataset
데이터 셋을 확장시키기 위한 데이터 보완 기술

(중략)


Introduction
This course will introduce you to the fundamental ideas of computer vision. Our goal is to learn how a neural network can "understand" a natural image well-enough to solve the same kinds of problems the human visual system can solve.
이번 코스에서는 이미지 인식 기술에 대한 기초적인 지식을 얻고 신경망을 통해서 자연적인 이미지 (natrual image)를 이해할 수 있는 모델을 만들어서 인간의 인지와 유사한 문제를 해결할 수 있도록 해보자.

The neural networks that are best at this task are called convolutional neural networks (Sometimes we say convnet or CNN instead.) Convolution is the mathematical operation that gives the layers of a convnet their unique structure. In future lessons, you'll learn why this structure is so effective at solving computer vision problems.
사물 / 이미지를 인지하는 데에 가장 적합한 모델로는 Convolutional Neural Network (우리는 이걸 때로 컨브이넷 또는 CNN 이라고 부른다.; 번역하자면 합성곱 신경망)
합성곱이란 행렬 수학에서 사용하는 연산기능으로 컨브이넷의 핵심적인 구조는 이 합성곱을 활용하고 있다. 향후 이 구조가 어떻게 컴퓨터의 이미지 인식 문제를 해결하는데 도움을 주고 있는지 살펴볼 것이다.

We will apply these ideas to the problem of image classification: given a picture, can we train a computer to tell us what it's a picture of? You may have seen apps that can identify a species of plant from a photograph. That's an image classifier! In this course, you'll learn how to build image classifiers just as powerful as those used in professional applications.
자 우리는 일단 이미지 분류 모델에 이 기술을 사용한 모델을 만들려고 한다. 어떤 사진을 입력하면 해당 사진이 무엇인지를 말해주는 모델이 될 것이다.

아마 이미 사진을 입력하면 사진 속의 식물이 어떤 식물인지를 구분해내는 앱을 알고 있을 것이다. (구글 렌즈 등.)
이하 생략.

While our focus will be on image classification, what you'll learn in this course is relevant to every kind of computer vision problem. At the end, you'll be ready to move on to more advanced applications like generative adversarial networks and image segmentation.
그리고 이번 강의에서 배운 내용은 이미지 인식 뿐만 아니라 기타 다양한 컴퓨터의 비젼 처리 문제에도 관여된다. 마지막으로 GAN (Generative Adversarial Network)이나 이미지 세그먼트와 같은 고급기술에 대해서도 맛보게 될것이다.

The Convolutional Classifier
합성곱 분류기
A convnet used for image classification consists of two parts: a convolutional base and a dense head.
컨브이넷은 두가지 파트로 구성되는데 하나는 합성곱 베이스이고 다른 하나는 덴스 레이어 헤드다.

The base is used to extract the features from an image. It is formed primarily of layers performing the convolution operation, but often includes other kinds of layers as well. (You'll learn about these in the next lesson.)
베이스는 이미지로 부터 피쳐를 추출해 내는 것으로 합성곱 연산을 구성하는 가장 기초적인 레이어를 형성하고 그 외에도 다양한 레이어를 담고 있다. (이부분은 나중에 학습)

The head is used to determine the class of the image. It is formed primarily of dense layers, but might include other layers like dropout.
헤드는 이미지의 분류(클래스)를 정하는 것으로 기본적으로 덴스레이어로 이루어져있고, 기타 드랍아웃과 같은 레이어가 포함된다.

What do we mean by visual feature? A feature could be a line, a color, a texture, a shape, a pattern -- or some complicated combination.
시각적 인자(Visual Feature, 여기서 피쳐라고 자꾸 부르고 있는 것은 앞서 배운 머신러닝의 테이블 데이터에서 컬럼의 컬럼 이름이 곧 특성값 이름이고 이걸 피쳐라고 부르고 있다.)로는 어떤 것들이 있을까? - 색, 선, 질감, 형상, 패턴등 또는 복잡 다양한 조합도 가능하다.
(중략)

Training the Classifier
분류기 학습
이 신경망의 학습 목표는 두가지다.
하나는 이미지로 부터 어떤 피쳐를 추출해오라고 학습시키는 베이스가 있고, 그게 어떤 클래스가 될것인지를 구분해내는 헤드를 학습시키는 것이다.
오늘날 컨브이넷을 제로부터 학습시키는 경우는 드물고 대부분 이미 학습된 모델을 활용한다.
통상 이미 학습된 베이스에 학습 전인 헤드를 붙여서 사용한다.
다시말하자면, 우리는 피쳐를 추출하는 것에 대해 이미 학습을 마친 1번 베이스를 활용해서 어떻게 분류할 것인지에 대한 2번 헤드를 학습시켜 나간다는 것이다.

These days, convnets are rarely trained from scratch. More often, we reuse the base of a pretrained model. To the pretrained base we then attach an untrained head. In other words, we reuse the part of a network that has already learned to do 1. Extract features, and attach to it some fresh layers to learn 2. Classify.

Attaching a new head to a trained base.
Because the head usually consists of only a few dense layers, very accurate classifiers can be created from relatively little data.
헤드는 통상 몇 개의 덴스 레이어로 구성되어 있고, 비교적 적은 데이터에서 매우 정확한 분류기를 학습시킬 수 있다.

Reusing a pretrained model is a technique known as transfer learning. It is so effective, that almost every image classifier these days will make use of it.
그런데 이미 학습된 모델을 재사용하는 기술을 우리는  트랜스퍼 러닝(Transfer Learning : 전이학습)이라고 부른다. 이것은 매우 효과적이며 오늘날 사용하는 이미지 분류 모델은 대부분 이방식을 사용하고 있다.



아래 예시는 컨브이넷 분류 모델에 대한 예시이고, 여기서는 자가용과 트럭의 사진을 주고 이것이 자가용인지 트럭인지를 구분하는 목표를 가진다.
물론 실습 창에서 진행해도 되지만, 만약 로컬에서 진행하려면 해당 캐글 노트를 방문해서 데이터셋을 다운로드 받아야 한다.(그리고 코딩 상에 데이터 패스(path)를 잘 조정하자.)

Example - Train a Convnet Classifier
중략
아래는 파이썬 코드를 여러 부분으로 잘라서 설명하고 있는데 번역제공은 필요치 않은 걸로 보인다.
참고로 step 1도 감춰진 부분을 펴서 코딩을 읽어보자.

Step 1 - Load Data
This next hidden cell will import some libraries and set up our data pipeline. We have a training split called ds_train and a validation split called ds_valid.

Found 5117 files belonging to 2 classes.
Found 5051 files belonging to 2 classes.
Let's take a look at a few examples from the training set.

Step 2 - Define Pretrained Base
The most commonly used dataset for pretraining is ImageNet, a large dataset of many kind of natural images. Keras includes a variety models pretrained on ImageNet in its applications module. The pretrained model we'll use is called VGG16.

pretrained_base = tf.keras.models.load_model(
    '../input/cv-course-models/cv-course-models/vgg16-pretrained-base',
)
pretrained_base.trainable = False
Step 3 - Attach Head
Next, we attach the classifier head. For this example, we'll use a layer of hidden units (the first Dense layer) followed by a layer to transform the outputs to a probability score for class 1, Truck. The Flatten layer transforms the two dimensional outputs of the base into the one dimensional inputs needed by the head.

from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    pretrained_base,
    layers.Flatten(),
    layers.Dense(6, activation='relu'),
    layers.Dense(1, activation='sigmoid'),
])

Step 4 - Train
Finally, let's train the model. Since this is a two-class problem, we'll use the binary versions of crossentropy and accuracy. The adam optimizer generally performs well, so we'll choose it as well.

model.compile(
    optimizer='adam',
    loss='binary_crossentropy',
    metrics=['binary_accuracy'],
)

history = model.fit(
    ds_train,
    validation_data=ds_valid,
    epochs=30,
    verbose=0,
)
When training a neural network, it's always a good idea to examine the loss and metric plots. The history object contains this information in a dictionary history.history. We can use Pandas to convert this dictionary to a dataframe and plot it with a built-in method.

import pandas as pd

history_frame = pd.DataFrame(history.history)
history_frame.loc[:, ['loss', 'val_loss']].plot()
history_frame.loc[:, ['binary_accuracy', 'val_binary_accuracy']].plot();




Conclusion
In this lesson, we learned about the structure of a convnet classifier: a head to act as a classifier atop of a base which performs the feature extraction.
이번 강의에서 우리는 컨브이넷 분류기의 구조에 대해서 배웠다. 피쳐 추출을 담당하는 베이스 위에 분류기에 해당하는 헤드를 얹어서 작동하는 방식이라는 것도 배웠다.

The head, essentially, is an ordinary classifier like you learned about in the introductory course. For features, it uses those features extracted by the base. This is the basic idea behind convolutional classifiers: that we can attach a unit that performs feature engineering to the classifier itself.
이전 강의에서 배운 분류 문제와 유사하게 헤드는 일반적인 분류기이고 피쳐는 베이스로부터 추출된 피쳐다. 컨브이넷 분류기의 이런 구조적인 특징 덕분에 우리는 헤드 분류기에 앞서 배웠던 피쳐 엔지니어링을 추가할 수 있다.

This is one of the big advantages deep neural networks have over traditional machine learning models: given the right network structure, the deep neural net can learn how to engineer the features it needs to solve its problem.
이것이 딥러닝 신경망 모델이 갖는 매우 큰 장점 중의 하나다. 잘 짜여진 신경망 모델이 있다면, 딥 신경망은 해당 피쳐에 대해 문제를 어떻게 해결하는 것이 좋을지 피쳐 엔지니어링을 가할 수 있다.

For the next few lessons, we'll take a look at how the convolutional base accomplishes the feature extraction. Then, you'll learn how to apply these ideas and design some classifiers of your own.
앞으로의 몇가지 레슨을 통해서 컨브이넷 베이스가 피쳐 추출을 어떻게 하는지 살펴보고, 분류 헤드에 자기만의 아이디어를 더해보게 될 것이다.
<끝>

관련글 더보기