Microsoft MVP성태의 닷넷 이야기
VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [링크 복사], [링크+제목 복사]
조회: 14352
글쓴 사람
정성태 (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)
12897정성태1/2/20227848.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
12896정성태1/1/202210716.NET Framework: 1127. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성파일 다운로드1
12895정성태12/31/20219224.NET Framework: 1126. C# - snagit처럼 화면 캡처를 연속으로 수행해 동영상 제작 [1]파일 다운로드1
12894정성태12/30/20217173.NET Framework: 1125. C# - DefaultObjectPool<T>의 IDisposable 개체에 대한 풀링 문제 [3]파일 다운로드1
12893정성태12/27/20218708.NET Framework: 1124. C# - .NET Platform Extension의 ObjectPool<T> 사용법 소개파일 다운로드1
12892정성태12/26/20216701기타: 83. unsigned 형의 이전 값이 최댓값을 넘어 0을 지난 경우, 값의 차이를 계산하는 방법
12891정성태12/23/20216624스크립트: 38. 파이썬 - uwsgi의 --master 옵션
12890정성태12/23/20216760VC++: 152. Golang - (문자가 아닌) 바이트 위치를 반환하는 strings.IndexRune 함수
12889정성태12/22/20219173.NET Framework: 1123. C# - (SharpDX + DXGI) 화면 캡처한 이미지를 빠르게 JPG로 변환하는 방법파일 다운로드1
12888정성태12/21/20217364.NET Framework: 1122. C# - ImageCodecInfo 사용 시 System.Drawing.Image와 System.Drawing.Bitmap에 따른 Save 성능 차이파일 다운로드1
12887정성태12/21/20219417오류 유형: 777. OpenCVSharp4를 사용한 프로그램 실행 시 "The type initializer for 'OpenCvSharp.Internal.NativeMethods' threw an exception." 예외 발생
12886정성태12/20/20217360스크립트: 37. 파이썬 - uwsgi의 --enable-threads 옵션 [2]
12885정성태12/20/20217605오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경
12884정성태12/20/20216674개발 환경 구성: 620. Windows 10+에서 WMI root/Microsoft/Windows/WindowsUpdate 네임스페이스 제거
12883정성태12/19/20217516오류 유형: 775. uwsgi-plugin-python3 환경에서 "ModuleNotFoundError: No module named 'django'" 오류 발생
12882정성태12/18/20216612개발 환경 구성: 619. Windows Server에서 WSL을 위한 리눅스 배포본을 설치하는 방법
12881정성태12/17/20217159개발 환경 구성: 618. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법 (2)
12880정성태12/16/20216935VS.NET IDE: 170. Visual Studio에서 .NET Core/5+ 역어셈블 소스코드 확인하는 방법
12879정성태12/16/202113171오류 유형: 774. Windows Server 2022 + docker desktop 설치 시 WSL 2로 선택한 경우 "Failed to deploy distro docker-desktop to ..." 오류 발생
12878정성태12/15/20218218개발 환경 구성: 617. 윈도우 WSL 환경에서 같은 종류의 리눅스를 다중으로 설치하는 방법
12877정성태12/15/20216887스크립트: 36. 파이썬 - pymysql 기본 예제 코드
12876정성태12/14/20216720개발 환경 구성: 616. Custom Sources를 이용한 Azure Monitor Metric 만들기
12875정성태12/13/20216443스크립트: 35. python - time.sleep(...) 호출 시 hang이 걸리는 듯한 문제
12874정성태12/13/20216410오류 유형: 773. shell script 실행 시 "$'\r': command not found" 오류
12873정성태12/12/20217534오류 유형: 772. 리눅스 - PATH에 등록했는데도 "command not found"가 나온다면?
12872정성태12/12/20217339개발 환경 구성: 615. GoLang과 Python 빌드가 모두 가능한 docker 이미지 만들기
... 16  17  18  19  20  21  22  23  24  25  26  27  28  [29]  30  ...