Microsoft MVP성태의 닷넷 이야기
VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [링크 복사], [링크+제목 복사]
조회: 14337
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 3개 있습니다.)

Visual Studio - ML.NET Model Builder 소개

이번 Microsoft Build 2019 행사 세션 중에 ML.NET에 관한 내용이 있습니다.

Welcome to the world of Machine Learning with ML.NET 1.0
; https://mybuild.techcommunity.microsoft.com/sessions/76977

세션 중에 보면 ML.NET을 좀 더 친숙하게 사용할 수 있도록 Visual Studio의 확장인 "ML.NET Model Builder"를 시연하는데,

ML.NET Model Builder
; https://dotnet.microsoft.com/apps/machinelearning-ai/ml-dotnet/model-builder?fbclid=IwAR21OxWEFvr-N_uETfkx9uy_Y28u2R2voiV95e2mM0LQ0EKMsfN7pgnJDrw

다음의 경로에서 vsix 파일을 다운로드해 비주얼 스튜디오(2017/2019)에 직접 설치해 볼 수 있습니다.

ML.NET Model Builder (Preview)
; https://marketplace.visualstudio.com/items?itemName=MLNET.07

게다가 굳이 세션 비디오를 시청하지 않아도 도움말 자체가 너무 잘 되어 있어서 ^^ 실습이 매우 쉽습니다.

ML.NET Tutorial - Get started in 10 minutes
; https://dotnet.microsoft.com/learn/machinelearning-ai/ml-dotnet-get-started-tutorial/intro

튜토리얼이기 때문에 기존 만들어진 예제 데이터를 사용하겠지만 현실적으로는 여러분들이 데이터를 이미 구축해놓아야 합니다. 일단 예제 데이터는,

Wikipedia detox dataset  - wikipedia-detox-250-line-data.tsv
; https://raw.githubusercontent.com/dotnet/machinelearning/master/test/data/wikipedia-detox-250-line-data.tsv

칼럼이 단 2개로써 "문자열 데이터"가 "SentimentText" 칼럼으로, 그 문자열이 부정적인 내용임을 판정(보통 Label이라고)하는 Sentiment 결괏값(0: 긍정, 1: 부정) 칼럼의 tsv 파일입니다.

Sentiment	SentimentText
1	        ==RUDE== Dude, you are rude upload that carl picture back, or else.
1	        == OK! ==  IM GOING TO VANDALIZE WILD ONES WIKI THEN!!!    
0	        I hope this helps.

간단하죠. 자, 그럼 이걸 가지고 ML.NET Model Builder를 사용해 보겠습니다.




우선, .NET Core/Framework 콘솔 프로젝트를 생성하는 것으로 시작합니다. 사실 이후의 "Model Builder" 사용으로 해당 프로젝트에 어떤 변화가 있는 것은 아닙니다. 단지 Machine Learning 메뉴를 선택하기 위한 과정에 지나지 않는데, 어쨌든 생성된 프로젝트 노드를 통해 다음과 같이 "Add" / "Machine Learning"을 실행할 수 있습니다.

mlnet_builder_1.gif

그럼 "1. Scenario" 단계로 진입하는데,

mlnet_builder_2.png

  1. Price Prediction
  2. Sentiment Analysis
  3. Custom Scenario

첫 번째 "Price Prediction"은 기계학습의 "회귀(Regression)", 두 번째 "Sentiment Analysis"는 "분류(Classification)" 중에서도 "Yes or No"에 해당하는 2진 분류(Binary classification)에 해당합니다. 그리고 세 번째 "Custom Scenario"는 앞의 2가지를 포함해 다중 분류(Multi-class classification)까지 선택할 수 있는 옵션을 제공합니다. (사실 Custom Scenario의 경우와 다른 2개의 옵션이 UI 상 크게 다른 면이 없기 때문에 제 개인적인 생각으로는 "1. Scenario" 단계는 "Custom Scenario" 하나만 포함해도 크게 무리가 없었을 거라고 보입니다.)

wikipedia-detox-250-line-data.tsv 파일의 경우에는 "Classify data into 2 categories (binary classification), e.g. predict positive or negative sentiment of comments" 시나리오가 맞습니다. 따라서, 여기서는 "Sentiment Analysis"를 선택합니다. (시험 삼아 "Custom Scenario"로 선택해도 이후의 진행에 무리가 없습니다.)

이제 "2. Data" 단계로 넘어가면 "File"로 "wikipedia-detox-250-line-data.tsv"를 선택, 2진 분류의 결괏값을 가지고 있는 "Sentiment" 칼럼을 "Column to Predict (Label)"로 지정하고,

mlnet_builder_3.png

하단의 "Tran" 링크를 누르면 "3. Train" 단계로 넘어갑니다. 여기서는 모델의 학습 시간을 설정하는데 도움말에 따르면,

ML.NET Model Builder Guide - Train
; https://github.com/dotnet/machinelearning-samples/blob/master/modelbuilder/readme.md#train

Dataset 크기에 따라 "Avg. Time to train"의 시간을 적절하게 설정하면 된다고 합니다. 실습에 사용하는 wikipedia-detox-250-line-data.tsv 파일은 겨우 70KB에 불과하므로 10초 기본값을 그대로 설정하겠습니다. "Start training" 버튼을 눌러 학습을 완료시킨 후 "4. Evaluate" 단계로 넘어가면 대체적인 학습 결과를 볼 수 있습니다.

mlnet_builder_4.png

마지막으로 "5. Code" 단계로 넘어가면 위의 학습 결과를 바탕으로 "ML.NET 모델 파일"을 포함한 C# 코드가 자동 생성됩니다.




자동 생성된 코드를 보면,

mlnet_builder_5.png

사실상 Model Builder가 만들어준 재활용 가능한 ML 기반의 라이브러리인 "ConsoleApp1ML.Model" 프로젝트가 가장 중요합니다. 여러분들은 이 프로젝트를 참조해 향후 웹 사이트의 덧글에 넘겨진 텍스트의 긍정/부정적인 내용을 판단하면 됩니다. (물론 예제 데이터가 영문이므로 한글을 위해서는 그에 맞는 데이터로 별도 학습을 시켜야 합니다.) 해당 ConsoleApp1ML.Model 라이브러리를 어떻게 사용하는지는 "ConsoleApp1ML.ConsoleApp" 예제 프로젝트를 통해 알 수 있습니다.

//*****************************************************************************************
//*                                                                                       *
//* This is an auto-generated file by Microsoft ML.NET CLI (Command-Line Interface) tool. *
//*                                                                                       *
//*****************************************************************************************

using System;
using System.IO;
using System.Linq;
using Microsoft.ML;
using ConsoleApp1ML.Model.DataModels;


namespace ConsoleApp1ML.ConsoleApp
{
    class Program
    {
        //Machine Learning model to load and use for predictions
        private const string MODEL_FILEPATH = @"MLModel.zip";

        //Dataset to use for predictions 
        private const string DATA_FILEPATH = @"c:\temp\ConsoleApp1\ConsoleApp1\wikipedia-detox-250-line-data.tsv";

        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext();

            // Training code used by ML.NET CLI and AutoML to generate the model
            //ModelBuilder.CreateModel();

            ITransformer mlModel = mlContext.Model.Load(GetAbsolutePath(MODEL_FILEPATH), out DataViewSchema inputSchema);
            var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(mlModel);

            // Create sample data to do a single prediction with it 
            ModelInput sampleData = CreateSingleDataSample(mlContext, DATA_FILEPATH);

            // Try a single prediction
            ModelOutput predictionResult = predEngine.Predict(sampleData);

            Console.WriteLine($"Single Prediction --> Actual value: {sampleData.Sentiment} | Predicted value: {predictionResult.Prediction}");

            Console.WriteLine("=============== End of process, hit any key to finish ===============");
            Console.ReadKey();
        }

        // Method to load single row of data to try a single prediction
        // You can change this code and create your own sample data here (Hardcoded or from any source)
        private static ModelInput CreateSingleDataSample(MLContext mlContext, string dataFilePath)
        {
            // Read dataset to get a single row for trying a prediction          
            IDataView dataView = mlContext.Data.LoadFromTextFile<ModelInput>(
                                            path: dataFilePath,
                                            hasHeader: true,
                                            separatorChar: '\t',
                                            allowQuoting: true,
                                            allowSparse: false);

            // Here (ModelInput object) you could provide new test data, hardcoded or from the end-user application, instead of the row from the file.
            ModelInput sampleForPrediction = mlContext.Data.CreateEnumerable<ModelInput>(dataView, false)
                                                                        .First();
            return sampleForPrediction;
        }

        public static string GetAbsolutePath(string relativePath)
        {
            FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
            string assemblyFolderPath = _dataRoot.Directory.FullName;

            string fullPath = Path.Combine(assemblyFolderPath, relativePath);

            return fullPath;
        }
    }
}

그래도 너무 복잡한가요? ^^ 그럼 좀 더 간단하게 축소해 보겠습니다. 여기서 엄밀하게는 MODEL_FILEPATH, 즉 ConsoleApp1ML.Model이 가지고 있는 MLModel.zip 파일이 핵심입니다. 따라서 MLModel.zip 파일만 있으면 다른 모든 것은 부수적인 요소에 불과합니다. 그렇다면, 이를 바탕으로 우리들의 "ConsoleApp1" 프로젝트를 완성해 볼 수도 있겠지요. ^^

우선, 프로젝트에 Microsoft.ML 라이브러리를 Nuget으로부터 참조 추가합니다.

Install-Package Microsoft.ML

그다음 ConsoleApp1ML.Model 프로젝트에 있는 MLModel.zip, ModelInput.cs, ModelOutput.cs 파일만 복사해 프로젝트에 추가합니다. 그리고 그중에서 MLModel.zip 파일은 "Copy to Output Directory" 설정을 "Copy if newer"로 합니다.

끝입니다. 이제 MLModel.zip 파일을 로드해 예측 엔진 타입을 만들고 원하는 문장을 ModelInput 타입에 실어 결과를 받아오면 됩니다. 그에 해당하는 코드는 다음과 같이 정리가 됩니다.

using ConsoleApp1ML.Model.DataModels;
using Microsoft.ML;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            MLContext mlContext = new MLContext();

            ITransformer mlModel = mlContext.Model.Load("MLModel.zip", out DataViewSchema inputSchema);
            var predEngine = mlContext.Model.CreatePredictionEngine(mlModel);

            ModelInput mi = new ModelInput { SentimentText = "Test it" };
            ModelOutput predictionResult = predEngine.Predict(mi);

            Console.WriteLine($"{predictionResult.Prediction}");
        }
    }
}




참고로, Model Builder에 설정해 "train"시키는 과정은 "ConsoleApp1ML.ConsoleApp" 프로젝트에 있는 "ModelBuilder.cs"의 코드 내용으로 남습니다. 그렇기 때문에 일단 한번 ModelBuilder.cs 파일이 생성되었으면 이후에는 UI를 통해서 데이터를 학습하기보다는 직접 ModelBuilder.cs의 코드를 재사용하는 것이 더 효율적입니다.

그나저나... 이젠 ML 분야도 개발자의 기본 소양이 되어가는 듯한 모습이군요. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/12/2019]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2019-05-30 10시01분
What is ML.NET 1.0 - Machine Learning for .NET
; https://devblogs.microsoft.com/cesardelatorre/what-is-ml-net-1-0-machine-learning-for-net

(2022-12-15)
ML.NET Model Builder 2022
; https://marketplace.visualstudio.com/items?itemName=MLNET.ModelBuilder2022

Text Classification in C# with ML.NET 2.0
; https://accessibleai.dev/post/ml_net_2_0_text_classification/

(2023-05-31)
Object Detection in ML.NET Model Builder
; https://devblogs.microsoft.com/dotnet/object-detection-ml-dotnet-model-builder/

(2023-10-06)
Empowering Real-World Solutions the Synergy of AI and .NET
; https://dzone.com/articles/empowering-real-world-solutions-the-synergy-of-ai
정성태
2021-01-22 08시08분
ML.NET으로 간단히 해보는 머신러닝
; https://www.youtube.com/watch?v=rJCeTkmd-iA
정성태
2021-02-15 09시07분
Using WinML in .NET5
; https://devblogs.microsoft.com/ifdef-windows/using-winml-in-net5/

WinML is a high-performance, reliable API for deploying hardware-accelerated ML (Machine Learning) inferences on Windows devices.
정성태
2021-10-28 10시36분
[정현욱] 혹시 한글 학습데이터도 될까요?
모델빌더에서 데이터 추가 하여 테스트 해보니 한글이 깨져서요.
혹 무엇인가 제가 놓치고 있는 부분이 있나 해서 질문 드립니다.
[guest]
2021-10-28 11시09분
본문의 "Build your machine learning model" - "2. Data" 단계에서 "Date Preview" 화면에 한글인 경우 문자가 깨져서 나온다는 건가요?
정성태

1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13446정성태11/16/20232416닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232690Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232452닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232489개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232305개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232644닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232350Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232837닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232457닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232653닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232875닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232797닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232609스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232341스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232371오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232699스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232596닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232849닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232897닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233079닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233260스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233084닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233059스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233199닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233237닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235257스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...