RAD 5월 26일, 2022에 포스트됨 공유하기 5월 26일, 2022에 포스트됨 원문: https://blogs.embarcadero.com/how-to-make-a-state-of-the-art-deep-learning-app-with-fastai/ 작성자: Muhammad Azizul Hakim (2022.5) Did you know it’s easy to make use of some truly excellent Python libraries to super-charge your Delphi app development on Windows? Adding Python to your toolbox of Delphi code can enhance your app development, bringing in new capabilities which help you provide innovative and powerful solutions to your app’s users, which combine the best of Python with the supreme low-code and unparalleled power of native Windows development you get with Delphi. 윈도우에서 델파이 앱 개발에 힘을 실어줄 수 있는 훌륭한 파이썬 라이브러리를 매우 쉽게 사용할 수 있다는 사실을 알고 있는가? 델파이 코드 툴박스에 파이썬을 추가하면 새로운 기능들을 활용할 수 있어 앱 개발 능력이 더욱 높아진다. 앱 사용자에게 혁신적이면서도 강력한 솔루션을 제공할 수도 있고, 델파이로 가능한 최고 전력의 네이티브 윈도우 개발, 최고 수준의 로우 코드와 파이썬의 장점을 결합할 수도 있다. Are you looking for how to build a GUI for a powerful AI library? You can build a state-of-the-art deep learning solution with fastai on Delphi. This post will show you how to build a Delphi GUI app, dedicated to the fastai library. 강력한 AI 라이브러리용 GUI 개발 방법을 찾고 있다면? 델파이에서 fastai로 최첨단 딥 러닝 솔루션을 구축할 수 있다. 이번 글에서는 fastai 라이브러리로 델파이 GUI 앱을 개발하는 방법에 대해서 소개하고자 한다. Watch this video by Jim McKeeth, as a comprehensive introduction about why you can love both Delphi and Python at the same time: 아래 짐 맥키트가 진행한 영상을 통해 델파이와 파이썬을 동시에 사랑할 수 있는 이유를 다룬 소개를 볼 수 있다: 목차 fastai 라이브러리란? fastai 라이브러리 설치 방법 fastai 라이브러리용 델파이 GUI 구축 방법 델파이 앱에서 fastai로 딥 러닝 실행하기 fastai와 델파이로 이미지를 분류하는 딥 러닝 구현하기 1. 라벨이 있는 이미지 데이터셋 불러오기 2. 딥 러닝 모델 훈련하기 3. fastai를 사용한 결과값 최고의 fastai 델파이 예제를 활용할 준비가 되었는가! fastai 라이브러리란? (What is the fastai library?) fastai is a deep learning library that provides practitioners with high-level components that can quickly and easily provide state-of-the-art results in standard deep learning domains and provides researchers with low-level components that can be mixed and matched to build new approaches. It aims to do both things without substantial compromises in ease of use, flexibility, or performance. fastai는 딥 러닝 라이브러리로, 실무자들에게 표준 딥 러닝에서 최첨단 결과를 쉽고 빠르게 제공할 수 있는 높은 수준의 컴포넌트와 새로운 접근 방식 구축에 믹스 앤 매치할 수 있는 로우 레벨 컴포넌트를 제공한다. 쉬운 사용성, 유연함, 성능 면에서 무엇 하나를 포기하지 않고도 모두를 취하는 것을 목표로 한다. fastai 기능: A new type dispatch system for Python along with a semantic type hierarchy for tensors 파이썬용 새로운 유형 디스패치 시스템과 텐서용 시맨틱 유형 계층 A GPU-optimized computer vision library that can be extended in pure Python 순수 파이썬에서 확장 가능한 GPU에 최적화된 컴퓨터 비전 라이브러리 An optimizer which refactors out the common functionality of modern optimizers into two basic pieces, allowing optimization algorithms to be implemented in 4–5 lines of code 4-5줄의 코드로 구현되는 최적화 알고리즘으로 두 가지 기본 요소에서 현대식 최적화 도구의 공통 기능을 리팩토링하는 최적화 도구 A novel 2-way callback system that can access any part of the data, model, or optimizer and change it at any point during training 트레이닝 중 언제든 변경이 가능하고 데이터, 모델, 최적화 도구 일부에 액세스할 수 있는 새로운 양방향 콜백 시스템 A new data block API 새로운 데이터 블록 API And much more… 등등 다양한 기능들을 제공한다. And the best of it is, fastai is organized around two main design goals: to be approachable and rapidly productive, while also being deeply hackable and configurable. 그 중에서도 가장 좋은 점은, fastai가 두 가지 주요 설계 목표를 가지고 설계되었다는 것이다: 접근성과 신속한 생산성을 유지하면서 동시에 깊이있는 구성과 꼼수가 가능하다. fastai is built on top of a hierarchy of lower-level APIs which provide composable building blocks. This way, a user wanting to rewrite part of the high-level API or add particular behavior to suit their needs does not have to learn how to use the lowest level. fastai는 구성 가능한 요소들을 제공하는 하위 레벨 API 계층 상단에 구축된다. 이러한 방식으로, 높은 수준의 API 일부를 재작성하거나 필요에 따라 특정 동작을 추가하고자 하는 경우 가장 낮은 수준의 사용 방법을 배울 필요가 없다. fastai API 계층도 fastai 라이브러리 설치 방법 (How do I install the fastai Library?) pip로 쉽게 설치할 수 있다. pip install fastai Or, if you are using Anaconda Python distribution, you can use this command to avoid complexities and conflicts between required libraries: 또는 Anaconda Python 배포를 사용한다면, 다음 명령을 사용해 필요한 라이브러리 간의 복잡성과 충돌을 방지할 수 있다. conda install -c fastai -c pytorch -c anaconda -c conda-forge fastai gh anaconda fastai 라이브러리용 델파이 GUI 구축 방법 (How do I build a Delphi GUI for the fastai library?) The following is the user interface structure for our project: 다음은 프로젝트의 UI 구조이다: fastai4D 프로젝트의 UI 구조 fastai4D 데모 앱에서 사용한 컴포넌트는 다음과 같다: TPythonEngine TPythonModule TPythonType TPythonVersions TPythonGUIInputOutput TForm TMemo TOpenDialog TSaveDialog TSplitter TImage TPanel TLabel TComboBox TButton Navigate to the UnitFastai4D.pas, and add the following line to the FormCreate, to load our basic fastaiApp.py: UniFastai4D.pas로 이동해 FormCreate에 다음 코드를 추가하여 기본 fastaiApp.py를 불러온다: Memo1.Lines.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'fastaiApp.py'); UnitFastai4D.pas 파일에 있는 fastai 앱 파이썬 파일을 원활하게 불러올 수 있다. And make sure that the fastaiApp.py is in the same directory as our Fastai4D.exe or inside your Delphi project folder. fastaiApp.py과 Fast4D.exe와 동일한 디렉토리 또는 본인의 델파이 프로젝트 폴더 내에 있는지 확인이 필요하다. You can change the “fastaiApp.py” with any fastai script you want, or you can load your fastai scripts at runtime, by clicking the “Load script…” like we will show you in the next Demo Sections. 다음 Demo Sections에서 보여주는 것과 같이 "Load script..."를 클릭해 런타임 시 fastai 스크립트를 불러오거나 원하는 fastai 스크립트로 "fastaiApp.py"를 변경할 수 있다. 델파이 앱에서 fastai로 딥 러닝 실행하기 (How to perform Deep Learning using fastai in a Delphi app?) 권장 예제: 1. This GUI was created by modifying Python4Delphi Demo34, which makes us possibly change the Python version in the runtime (this will save you from the seemingly complicated dll issues). 1. 해당 GUI는 Python4Delphi Demo34를 수정해 만들었으며, 런타임 시 파이썬 버전을 변경할 수 있다 (이 방식은 복잡해보이는 dll 이슈를 벗어날 수 있도록 해준다). 2. Add “Jpeg” to the Uses-list at the top of our UnitMatplotlib4D.pas code. We have to do that, because otherwise, Delphi can not understand the JPG format. With this correction, it should work. 2. UnitMatplotlib4D.pas 코드 가장 상단의 Uses-list에 "Jpeg"을 추가한다. 이 작업을 해야만, 델파이는 JPG 형식을 이해할 수 있다. After that, the above change should look similar to this: 그 후, 상단 변경사항은 다음과 같이 나타나게 된다: Uses 절에 Jpeg을 임포트한다. And we can load JPG images into our TImage. 이제 TImage에 JPG 이미지를 불러올 수 있다. 3. Set up these paths to your Environment Variable, for regular Python: 3. 일반 파이썬의 경우, Environment Variable에 다음과 같이 경로를 설정해야 한다: C:/Users/ASUS/AppData/Local/Programs/Python/Python38 C:/Users/ASUS/AppData/Local/Programs/Python/Python38/DLLs C:/Users/ASUS/AppData/Local/Programs/Python/Python38/Lib/bin C:/Users/ASUS/AppData/Local/Programs/Python/Python38/Lib/site-packages/bin C:/Users/ASUS/AppData/Local/Programs/Python/Python38/Scripts Anaconda Python 방식을 사용한다면, 다음과 같이 경로를 설정해야 한다: C:/Users/ASUS/anaconda3/DLLs C:/Users/ASUS/anaconda3/Lib/site-packages C:/Users/ASUS/anaconda3/Library C:/Users/ASUS/anaconda3/Library/bin C:/Users/ASUS/anaconda3/Library/mingw-w64/bin C:/Users/ASUS/anaconda3/pkgs C:/Users/ASUS/anaconda3/Scripts 4. To load the image dataset or to create plots, you will need to use Matplotlib in a way that is outside the “normal” command-line process. To do it, you will need to add these lines to all your Python code: 4. 이미지 데이터셋을 불러오거나 plot을 생성하려면 "일반" 커맨드 라인 프로세스 영역 외에 있는 방법으로 Matplotlib를 사용해야 한다. 이를 위해서는 모든 파이썬 코드에 다음의 코드를 작성하면 된다: import matplotlib import matplotlib.pyplot as plt matplotlib.use("Agg") … plt.savefig("fastaiImage.jpg") … We strongly recommend you to name your image output as fastaiImage.jpg, to enable it to load automatically on your GUI after clicking the ”Show plot” button. 이미지 출력명은 fastaiImage.jpg 로 하면 "Show plot" 버튼을 클릭해 GUI에 자동으로 불러올 수 있어 이 방법을 가장 권장한다. 5. Set MaskFPUExceptions(True); to the UnitFastai4D.pas file, to avoid the Delphi raises an exception when floating operations result produce +/- infinity (e.g. division by zero) that is caused by incompatible with a number of Python libraries such as NumPy, SciPy, pandas, and Matplotlib. 5. UnitFastai4D.pas 파일에 MaskFPUExceptions(True)를 설정하면, floating operation 결과가 Numpy, SciPy, pandas, Matplotlib 등 여러 파이썬 라이브러리와 호환되지 않는 +/- infinity (예. 0으로 나눗셈)가 발생하는 경우 델파이에 예외가 발생하는 걸 막을 수 있다. One of the best parts of this Fastai4D Demo GUI is that you can choose the Python version you prefer, and it can be interchangeable. Fastai4D Demo GUI의 가장 좋은 점 중 하나는 선호하는 파이썬 버전을 선택할 수 있고 상호 호환이 가능하다는 것이다. 이 GUI를 사용하면 시스템에 설치된 모든 파이썬 버전을 선택할 수 있다. 그리고 "Execute" 버튼을 클릭해 기본 예제를 실행한다. As we’ve already tested this GUI for regular Python and Anaconda Python, this Fastai4D GUI works better for regular Python distribution. GUI를 일반 파이썬과 Anaconda Python 용으로 이미 테스트했기 떄문에, Fastai4D GUI는 일반 파이썬 방식에 더 잘 작동한다. Next, click the “Execute” button to run the very basic example to download, load the image dataset, and print out their labels (the Python code is already called inside the UnitFastai4D.pas file), and click the “Show plot” button to show the figure. Here is the output: 그리고 "Execute" 버튼을 클릭하면 매우 기본적인 예제를 실행해 이미지 데이터셋을 다운로드, 불러오기하고 라벨 출력 (파이썬 코드는 UnitFastai4D.pas 파일에서 이미 호출됨)이 가능하다. 그리고 "Show plot" 버튼을 클랙해 그림을 표시할 수 있다. 출력 결과는 다음과 같다: Fastai4D 가장 기본 예제. fastai와 델파이로 이미지를 분류하는 딥 러닝 구현하기 (How to implement deep learning for image classification using fastai and Delphi?) 구현 예제: 1. 라벨이 있는 이미지 데이터셋 불러오기 (Load image datasets with their labels) In this fastai embedded Python code, we are going to use the Oxford-IIIT Pet Dataset by O. M. Parkhi et al., 2012 which features 12 cat breeds and 25 dog breeds. Our model will learn how to differentiate between these 37 distinct categories. According to their paper, the best accuracy they could get in 2012 was 59.21%, using a complex model that was specific to pet detection, with separate “Image”, “Head”, and “Body” models for the pet photos. fastai가 적용된 파이썬 코드에 12종의 고양이 품종과, 25종의 견종이 있는 Oxford-IIIT Pet Dataset by O. M. Parkhi et al., 2012 를 사용해보겠다. 이 모델에서는 총 37개로 구분되는 카테고리를 구별하는 방법을 적용해보겠다. 관련 자료에 따르면, 2012년 얻은 정확도는 59.21%라고 한다. 당시에는 애완동물 사진을 "이미지", "머리", "몸"으로 구분한 애완동물 특유의 구별이 적용된 복잡한 모델을 사용했다. Here is the default example embedded on the Fastai4D GUI: Fastai4D GUI가 기본 제공하는 예제는 다음과 같다: Fastai4D를 사용해 라벨이 있는 이미지 데이터셋을 불러올 수 있다. You can download the script here. 스크립트는 여기를 클릭해 다운로드 할 수 있다. If you have low computational power, set up the batch size as 16 (by uncommenting this line: #bs = 16 ## Use this if you have low computational power, on this fastaiApp.py code. 컴퓨터 전력이 낮다면, 배치 크기를 16으로 설정한다 (해당 라인에는 주석을 달지 않음: #bs = 16 ## 컴퓨터 전력이 낮은 경우, fastaiApp.py 코드에서 이를 활용한다. 2. 딥 러닝 모델 훈련하기 (Train deep learning model) This example will train ResNet-34. We will use a convolutional neural network backbone and a fully connected head with a single hidden layer as a classifier. ResNet-34 is a 34 layer convolutional neural network that can be utilized as a state-of-the-art image classification model. 이 예제에서는 ResNet-34를 훈련한다. 나선형 신경망 백본 그리고 숨겨진 단일 레이어와 완벽하기 연결된 헤드를 분류기로 사용해보겠다. ResNet-34는 34 레이어의 나선형 신경망으로 최첨단 이미지 분류 모델로 활용할 수 있다. Illustrated below, on the right-hand side is Resnet34’s architecture where the 34 layers and the residuals from one layer to another are visualized: 아래 그림의 오른쪽은 Restnet34 아키텍처로, 한 레이어에서 다른 레이어로의 남아있는 부분과 34 레이어를 시각적으로 보여준다. 우측의 ResNet-34 레이어 아키텍처 그림 (원본은 이 페이지에서 확인할 수 있음) We are building a model which will take images as input and will output the predicted probability for each of the categories (in this case, it will have 37 outputs), and we will train for 4 epochs (4 cycles through all our data). 이미지는 입력값으로 받고, 각 카테고리에 대한 예측 확률을 출력하는 모델을 구축하고(이 케이스에서는 37개의 출력값이 나옴), 네 번의 에포크(모든 데이터를 4번 반복)로 훈련해보겠다. Load the demo02_trainModel.py at runtime by clicking the “Load script…” button, and then “Execute”. Here is the output: "Load script..."을 클릭하고 "Execute"를 클릭해 런타임 시 demo02_trainModel.py를 불러온다. 출력값은 다음과 같다: Fastai4D를 사용해 딥 러닝 모델을 훈련할 수 있다. The code in this section will train the model for 4 epochs (4 cycles through all our data) and save the result. 해당 부분의 코드는 네 번의 에포크 (모든 데이터를 4번 반복) 동안 모델을 훈련하고 결과를 저장한다. If you run this without a GPU, it will need a long time to run. The following is our test on a regular CORE i5 laptop, with an onboard graphic card, and 12 Gb of RAM: GPU없이 이를 실행하면, 실행 시간이 오래 걸릴 것이다. 다음은 장착된 그래픽 카드와 12 GB RAM이 장착된 일반적인 CORE i5 노트북에서 테스트한 것이다: 3. fastai를 사용한 결과값 (What do the results of using fastai look like?) If you completed the deep learning model training, you would see the following results: 딥 러닝 모델 훈련을 마치고 나면, 다음과 같은 결과를 확인할 수 있다: The result will show you the categories that the model most confused with one another. We will identify if what the model predicted was reasonable or not. In this case, the mistakes look reasonable (none of the mistakes seems obviously naive). This is an indicator that our classifier is working correctly. 결과에서는 모델이 다른 모델과 가장 혼동했던 카테고리를 보여준다. 모델이 예측한 결과의 타당성 여부를 확인해보겠다. 이 케이스에서 실수한 결과물은 그럴만한 이유가 있어 보인다 (실수한 것 중 어떤 것도 정말 몰라서 그런 것으로 보이지는 않는다). 이는 우리의 분류기가 올바르게 작동하고 있다는 의미이다. The result inside Python4Delphi GUI: Python4Delphi GUI의 결과는 다음과 같다: Furthermore, we want to plot the confusion matrix. From the confusion matrix result, we can see that the distribution is heavily skewed: The model makes the same mistakes over and over again, but it rarely confuses other categories. This suggests that it just finds it difficult to distinguish some specific categories between each other; this is a normal behavior. 이제, 혼동 행렬을 표시해보겠다. 혼동 행렬 결과를 보면 분포가 심하게 치우쳐있는 걸 볼 수 있다: 해당 모델은 같은 실수는 반복하지만, 다른 범주로 혼동하는 경우는 드물다. 이는 단지 서로 간의 특정 카테고리 구별이 어려움을 의미한다. 정상적인 것이다. The confusion matrix inside Python4Delphi GUI: Python4Delphi GUI 내부의 혼동 행렬: Let’s print out the most confused result, until the minimum value 2: 가장 혼동되는 결과를 최소값 2까지 출력해보겠다: Since our model is working as we expect it to, we will unfreeze our model and train some more, and here are the results: 모델은 예상했던대로 작동하였으며, 자유롭게 풀어놓고 몇 가지를 더 훈련해보았다. 결과는 다음과 같다: Plot the learning rate: 학습률 도표: Fitting for two cycles: 두 번의 사이클: Such a powerful deep learning library, right? 정말 강력한 딥 러닝 라이브러리이지 않은가? Visit this repository for the complete source code for this Fastai4Delphi project, and this repository (https://github.com/fastai/fastai/blob/master/dev_nbs/course/lesson1-pets.ipynb) for the original and more comprehensive concepts about fastai for image classification. Fastai4Delphi 프로젝트의 전체 소스 코드는 다음 경로의 리파지토리에서 확인할 수 있다. 이를 통해 이미지 분류 관련 fastai 기본적인 개념과 더 폭넓은 이해가 가능하다. 리파지토리 경로: https://github.com/fastai/fastai/blob/master/dev_nbs/course/lesson1-pets.ipynb 최고의 fastai 델파이 예제를 활용할 준비가 되었는가! (Are you ready to try this excellent fastai Delphi example?) Congratulations, now you have learned a lot about fastai: A state-of-the-art deep learning library, and how you can use Delphi to create a simple yet powerful GUI for it! We have learned the fundamentals of deep learning to perform image classification, and now you can explore them to boost your productivity in creating your own deep learning apps. 자 이제 fastai에 대해 많은 것을 배웠다. 최신 딥 러닝 라이브러리, 델파이로 단순하지만 강력한 GUI를 만드는 방법까지! 이미지 분류를 할 수 있는 딥 러닝의 기본적인 내용을 배웠고, 이를 활용해 나만의 딥 러닝 앱을 만들 때 생산성을 더욱 높일 수 있다. If you are looking for other powerful AI libraries, please read this article: 강력한 AI 라이브러리들에 대해 더 알고 싶다면, 다음 글이 도움이 될 것이다: https://devgear.co.kr/archives/4699 https://pythongui.org/learn-to-build-a-gui-for-these-10-ultimate-python-ai-libraries/ 지금! 델파이 최신 버전 무료 평가판을 다운로드 받아 직접 테스트 해볼 수 있다! 인용하기 이 댓글 링크 다른 사이트에 공유하기 더 많은 공유 선택 사항
Recommended Posts
이 토의에 참여하세요
지금 바로 의견을 남길 수 있습니다. 그리고 나서 가입해도 됩니다. 이미 회원이라면, 지금 로그인하고 본인 계정으로 의견을 남기세요.