Microsoft MVP성태의 닷넷 이야기
VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [링크 복사], [링크+제목 복사]
조회: 14350
글쓴 사람
정성태 (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)
13501정성태12/25/20232087개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232178디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20232823닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232294오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232309Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232318Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232500Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232558닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232262개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232232Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232345개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232133개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232067오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232381개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232195개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232088오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232162개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232298닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232821닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232267개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232607개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232302개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232482닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232207닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232279닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...