Microsoft MVP성태의 닷넷 이야기
VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [링크 복사], [링크+제목 복사]
조회: 14393
글쓴 사람
정성태 (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" 화면에 한글인 경우 문자가 깨져서 나온다는 건가요?
정성태

... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13203정성태12/22/20224392.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224801기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225395오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224272오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224536개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224446.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224375.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
13196정성태12/16/20224534.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
13195정성태12/15/20225073개발 환경 구성: 655. docker - bridge 네트워크 모드에서 컨테이너 간 통신 시 --link 옵션 권장 이유
13194정성태12/14/20225100오류 유형: 833. warning C4747: Calling managed 'DllMain': Managed code may not be run under loader lock파일 다운로드1
13193정성태12/14/20225181오류 유형: 832. error C7681: two-phase name lookup is not supported for C++/CLI or C++/CX; use /Zc:twoPhase-
13192정성태12/13/20225175Linux: 55. 리눅스 - bash shell에서 실수 연산
13191정성태12/11/20226075.NET Framework: 2077. C# - 직접 만들어 보는 SynchronizationContext파일 다운로드1
13190정성태12/9/20226576.NET Framework: 2076. C# - SynchronizationContext 기본 사용법파일 다운로드1
13189정성태12/9/20227292오류 유형: 831. Visual Studio - Windows Forms 디자이너의 도구 상자에 컨트롤이 보이지 않는 문제
13188정성태12/9/20226048.NET Framework: 2075. C# - 직접 만들어 보는 TaskScheduler 실습 (SingleThreadTaskScheduler)파일 다운로드1
13187정성태12/8/20225930개발 환경 구성: 654. openssl - CA로부터 인증받은 새로운 인증서를 생성하는 방법 (2)
13186정성태12/6/20224499오류 유형: 831. The framework 'Microsoft.AspNetCore.App', version '...' was not found.
13185정성태12/6/20225473개발 환경 구성: 653. Windows 환경에서의 Hello World x64 어셈블리 예제 (NASM 버전)
13184정성태12/5/20224750개발 환경 구성: 652. ml64.exe와 link.exe x64 실행 환경 구성
13183정성태12/4/20224610오류 유형: 830. MASM + CRT 함수를 사용하는 경우 발생하는 컴파일 오류 정리
13182정성태12/4/20225329Windows: 217. Windows 환경에서의 Hello World x64 어셈블리 예제 (MASM 버전)
13181정성태12/3/20224721Linux: 54. 리눅스/WSL - hello world 어셈블리 코드 x86/x64 (nasm)
13180정성태12/2/20224913.NET Framework: 2074. C# - 스택 메모리에 대한 여유 공간 확인하는 방법파일 다운로드1
13179정성태12/2/20224333Windows: 216. Windows 11 - 22H2 업데이트 이후 Terminal 대신 cmd 창이 뜨는 경우
13178정성태12/1/20224832Windows: 215. Win32 API 금지된 함수 - IsBadXxxPtr 유의 함수들이 안전하지 않은 이유파일 다운로드1
... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...