# 3.3 Fine-tuning images

이번 페이지에서는 커스텀 데이터셋을 통해 학습을 진행하고, 배포를 통해 object-detection을 진행해 보겠습니다.

해당 데이터는 작업자들의 안전모 착용 여부를 탐지하기 위해 이미지 모델링을 진행합니다.\
([Hard Hat Workers Dataset](https://public.roboflow.com/object-detection/hard-hat-workers))

<figure><img src="/files/ML6CLRIuQ60O3Mp43QQk" alt=""><figcaption></figcaption></figure>

먼저 해당 데이터셋을 작업하기 위해, 아래와 같은 구조로 이미지 파일을 배치할 필요가 있습니다.

```
input_directory
    |--images
        |--abc.png
        |--def.png
    |--annotations.json
```

또한 annotations.json 파일의 형식은 아래와 같은 내용이 포함되어야 합니다.

```
keys = "images", "annotations"
"images" : {"file_name": image_name, "height": height, "width": width, "id": image_id}
"annotations" :{"image_id": image_id, "bbox": \[xmin, ymin, xmax, ymax\], "category_id": bbox_label}
```

1. 위의 [3.2 Jumpstart with notebook](/sagemaker-image-workshop/lab3.-object-detction-with-low-code/3.2-jumpstart-with-notebook.md) 진행 했던 노트북 파일의 아랫 부분부터 시작합니다.
2. 다음 셀을 실행시켜 학습을 위한 컨테이너를 정의합니다. 셀을 실행시켜줍니다.

<figure><img src="/files/zij9sTl05LNeWmix4t7F" alt=""><figcaption></figcaption></figure>

3. 학습을 진행하기 위해 파라미터 설정과 학습을 위한 경로 지정이 필요합니다. 아래 셀인 3.2 Set Training parameters 부분에 복사하여 실행시켜줍니다.

<figure><img src="/files/L5QWwswPuFhGvAhXjNb8" alt=""><figcaption></figcaption></figure>

```python
# Sample training data is available in this bucket
training_data_bucket = f"imagedataset0413"
training_data_prefix = "a/hardhat/hardhatb/hardhatb/"

training_dataset_s3_path = f"s3://{training_data_bucket}/{training_data_prefix}"

output_bucket = sess.default_bucket()
output_prefix = "jumpstart-example-od-training"

s3_output_location = f"s3://{output_bucket}/{output_prefix}/output"
```

5. 학습을 위한 경로 설정에 사전에 세팅된 이미지 폴더를 아래와 같이 확인 해 볼 수 있습니다.

<figure><img src="/files/sF5L6trCYOjJnhTY1Bky" alt=""><figcaption></figcaption></figure>

해당 폴더의 구조는 위에서 지정한것과 같이, Images폴더와 annotations.json 파일로 구성되어있습니다.

6. 다음셀에서는 학습을 위한 Hyperparameters를 정의할 수 있습니다. Epoch값 조정과 Learning-rate 등의 조정이 가능합니다.

```python
from sagemaker import hyperparameters

# Retrieve the default hyper-parameters for fine-tuning the model
hyperparameters = hyperparameters.retrieve_default(
    model_id=train_model_id, model_version=train_model_version
)

# [Optional] Override default hyperparameters with custom values
hyperparameters["epochs"] = "10"
hyperparameters["adam-learning-rate"] = "0.005"
print(hyperparameters)
```

7. 학습 실행을 위해 3.3. Start Training 셀을 실행시켜줍니다. 학습에는 약 10분의 시간이 소요됩니다.

<figure><img src="/files/MLRuCAngu7bwBEo9ueRi" alt=""><figcaption></figcaption></figure>

8. 학습된 모델 배포와 추론을 위해 3.4. Deploy and run inference on the fine-tuned model 부분을 실행시켜 컨테이너를 통해 엔드포인트를 생성합니다. 엔드포인트 생성에 약 5분정도의 시간이 소요됩니다.

<figure><img src="/files/q8fzstX7zXMpzdA8RwKr" alt=""><figcaption></figcaption></figure>

9. 다음으로는 추론을 위한 이미지를 다운로드 한 뒤, 추론을 진행 하겠습니다. \
   해당 부분을 아래의 코드들로 변경 뒤 실행합니다.

<figure><img src="/files/5e4GCJl7ieU2GCyIM86D" alt=""><figcaption></figcaption></figure>

```python
#추론 이미지 경로 설정
jumpstart_assets_bucket = f"imagedataset0413"
pedestrian_image_key = "a/hardhat/hardhatb/hardhatb/images"
pedestrian_image_file_name = "000183_jpg.rf.91111a46ebb349d7d3627ff82be227fb.jpg"

boto3.client("s3").download_file(
    jumpstart_assets_bucket,
    f"{pedestrian_image_key}/{pedestrian_image_file_name}",
    pedestrian_image_file_name,
)
```

<pre><code>#이미지 추론 실행
query_response = query(finetuned_predictor, pedestrian_image_file_name)

normalized_boxes, classes_names, confidences = parse_response(query_response)

display_predictions(pedestrian_image_file_name, normalized_boxes, classes_names, confidences)
<strong>print (confidences)
</strong></code></pre>

10. 추론 결과로 다음과 같이 bounding box와 추론 확률을 확인해 볼 수 있습니다.

    <figure><img src="/files/w9NVXn2dRwbd2yYPiCRP" alt=""><figcaption></figcaption></figure>
11. 추론이 완료된 후, 해당 셀을 실행하여 엔드포인트를 삭제해 줍니다.

<figure><img src="/files/YJgCamAVuUV7fxtbuh8I" alt=""><figcaption></figcaption></figure>

축하합니다. 일부 코드를 활용하여 이미지 학습 및 추론을 진행하는 방법에 대해 완료되었습니다.

다음 페이지에서 부터는 외부의 모델 또는 알고리즘을 통해 학습을 진행하는 방법에 대해 알아보겠습니다.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cheolmin-ki.gitbook.io/sagemaker-image-workshop/lab3.-object-detction-with-low-code/3.3-fine-tuning-images.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
