다음을 통해 공유


Windows Machine Learning API를 사용하여 Windows 앱에 모델 배포

이 자습서의 이전 부분에서는 ONNX 형식으로 모델을 빌드하고 내보내는 방법을 알아보았습니다. 이제 해당 모델을 Windows 애플리케이션에 포함하고 WinML API를 호출하여 디바이스에서 로컬로 실행할 수 있습니다.

완료되면 작동하는 이미지 분류자 WinML UWP 앱(C#)이 제공됩니다.

샘플 앱 정보

모델을 사용하여 음식 이미지를 분류할 수 있는 앱을 만듭니다. 이를 통해 로컬 디바이스에서 이미지를 선택하고 이전 부분에서 빌드하고 학습한 로컬로 저장된 분류 ONNX 모델로 처리할 수 있습니다. 반환된 태그는 이미지 옆에 표시되며 분류의 신뢰도 확률도 표시됩니다.

지금까지 이 자습서를 수행한 경우 앱 개발에 필요한 필수 구성 요소가 이미 있어야 합니다. 새로 고침이 필요한 경우 이 자습서의 첫 번째 부분을 참조하세요.

비고

전체 샘플 코드를 다운로드하려는 경우 솔루션 파일을 복제할 수 있습니다. 리포지토리를 복제하고 이 샘플로 이동한 다음 Visual Studio를 사용하여 ImageClassifierAppUWP.sln 파일을 엽니다. 그런 다음 [애플리케이션 시작](애플리케이션 #Launch) 단계로 건너뛸 수 있습니다.

WinML UWP 만들기(C#)

아래에서는 앱 및 WinML 코드를 처음부터 만드는 방법을 보여 줍니다. 다음을 배우게 됩니다:

  • 기계 학습 모델을 로드합니다.
  • 필요한 형식으로 이미지를 로드합니다.
  • 모델의 입력 및 출력을 바인딩합니다.
  • 모델을 평가하고 의미 있는 결과를 표시합니다.

또한 기본 XAML을 사용하여 간단한 GUI를 만들므로 이미지 분류자를 테스트할 수 있습니다.

앱 만들기

  1. Visual Studio를 열고 을 선택합니다 create a new project.

새 Visual Studio 프로젝트 만들기

  1. 검색 창에서 )를 입력 UWP 하고 선택합니다 Blank APP (Universal Windows. 이렇게 하면 미리 정의된 컨트롤이나 레이아웃이 없는 단일 페이지 UWP(유니버설 Windows 플랫폼) 앱에 대한 새 C# 프로젝트가 열립니다. 프로젝트에 대한 구성 창을 열려면 선택합니다 Next .

새 UWP 앱 만들기

  1. 구성 창에서 다음을 수행합니다.
  • 프로젝트의 이름을 선택합니다. 여기서는 ImageClassifierAppUWP를 사용합니다.
  • 프로젝트의 위치를 선택합니다.
  • 사용 중인 VS 2019에서 Place solution and project in the same directory가 선택되지 않았는지 확인하세요.
  • VS 2017을 사용하는 경우 Create directory for solution가 선택되어 있는지 확인하십시오.

프로젝트를 생성하려면 create를 누르십시오. 최소 대상 버전 창이 나타날 수 있습니다. 최소 버전이 Windows 10 빌드 17763 이상으로 설정되어 있는지 확인합니다.

앱을 만들고 WinML 앱을 사용하여 모델을 배포하려면 다음이 필요합니다.

  1. 프로젝트를 만든 후 프로젝트 폴더로 이동하여 자산 폴더 [....\ImageClassifierAppUWP\Assets]를 열고 모델을 이 위치에 복사합니다.

  2. 모델 이름을 model.onnx에서 classifier.onnx로 변경합니다. 이렇게 하면 상황이 좀 더 명확해지고 자습서의 형식에 맞춥니다.

모델을 탐색하세요

모델 파일의 구조를 알아보겠습니다.

  1. classifier.onnx 모델 파일을 Netron을 사용하여 엽니다.

  2. 모델 속성을 열려면 Data를 누르십시오.

모델 속성

이 모델은 32비트 Tensor(다차원 배열) float 개체를 입력으로 필요로 하며 두 개의 출력을 반환합니다. 첫 번째 출력은 `classLabel`라는 이름의 문자열 텐서이고, 두 번째 출력인 `loss`은 레이블이 지정된 각 분류의 확률을 설명하는 문자열-부동 소수점 맵 시퀀스입니다. Windows 앱에서 모델 출력을 성공적으로 표시하려면 이 정보가 필요합니다.

프로젝트 솔루션 살펴보기

프로젝트 솔루션을 살펴보겠습니다.

Visual Studio는 솔루션 탐색기 내에 여러 cs-code 파일을 자동으로 만들었습니다. MainPage.xaml는 GUI에 대한 XAML 코드를 포함하고, MainPage.xaml.cs는 애플리케이션 코드를 포함합니다. 이전에 UWP 앱을 만든 경우 이러한 파일은 매우 익숙해야 합니다.

애플리케이션 GUI 만들기

먼저 앱에 대한 간단한 GUI를 만들어 보겠습니다.

  1. MainPage.xaml 파일을 두 번 클릭하십시오. 빈 앱에서 앱의 GUI에 대한 XAML 템플릿이 비어 있으므로 일부 UI 기능을 추가해야 합니다.

  2. 의 본문 MainPage.xaml에 아래 코드를 추가합니다.

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <StackPanel Margin="1,0,-1,0">
            <TextBlock x:Name="Menu" 
                       FontWeight="Bold" 
                       TextWrapping="Wrap"
                       Margin="10,0,0,0"
                       Text="Image Classification"/>
            <TextBlock Name="space" />
            <Button Name="recognizeButton"
                    Content="Pick Image"
                    Click="OpenFileButton_Click" 
                    Width="110"
                    Height="40"
                    IsEnabled="True" 
                    HorizontalAlignment="Left"/>
            <TextBlock Name="space3" />
            <Button Name="Output"
                    Content="Result is:"
                    Width="110"
                    Height="40"
                    IsEnabled="True" 
                    HorizontalAlignment="Left" 
                    VerticalAlignment="Top">
            </Button>
            <!--Display the Result-->
            <TextBlock Name="displayOutput" 
                       FontWeight="Bold" 
                       TextWrapping="Wrap"
                       Margin="30,0,0,0"
                       Text="" Width="1471" />
            <Button Name="ProbabilityResult"
                    Content="Probability is:"
                    Width="110"
                    Height="40"
                    IsEnabled="True" 
                    HorizontalAlignment="Left"/>
            <!--Display the Result-->
            <TextBlock Name="displayProbability" 
                       FontWeight="Bold" 
                       TextWrapping="Wrap"
                       Margin="30,0,0,0"
                       Text="" Width="1471" />
            <TextBlock Name="space2" />
            <!--Image preview -->
            <Image Name="UIPreviewImage" Stretch="Uniform" MaxWidth="300" MaxHeight="300"/>
        </StackPanel>
    </Grid>

Windows Machine Learning 코드 생성기

Windows Machine Learning 코드 생성기 또는 mlgen은 UWP 앱에서 WinML API 사용을 시작하는 데 도움이 되는 Visual Studio 확장입니다. 학습된 ONNX 파일을 UWP 프로젝트에 추가할 때 템플릿 코드를 생성합니다.

Windows Machine Learning의 코드 생성기 mlgen은 Windows ML API를 호출하는 래퍼 클래스를 사용하여 인터페이스(C#, C++/WinRT 및 C++/CX용)를 만듭니다. 이렇게 하면 프로젝트에서 모델을 쉽게 로드, 바인딩 및 평가할 수 있습니다. 이 자습서에서는 이 함수를 사용하여 많은 함수를 처리할 것입니다.

코드 생성기는 Visual Studio 2017 이상에서 사용할 수 있습니다. Windows 10 버전 1903 이상에서는 mlgen이 더 이상 Windows 10 SDK에 포함되지 않으므로 확장을 다운로드하고 설치해야 합니다. 소개에서 이 자습서를 수행한 경우 이미 이 작업을 처리했지만 그렇지 않은 경우 VS 2019 또는 VS 2017용으로 다운로드해야 합니다.

비고

mlgen에 대한 자세한 내용은 mlgen 설명서를 참조하세요.

  1. 아직 설치하지 않은 경우 mlgen을 설치합니다.

  2. Visual Studio의 Assets 솔루션 탐색기에서 폴더를 마우스 오른쪽 단추로 클릭하고 선택합니다 Add > Existing Item.

  3. 내부 ImageClassifierAppUWP [….\ImageClassifierAppUWP\Assets]자산 폴더로 이동하여 이전에 복사한 ONNX 모델을 찾은 다음 선택합니다 add.

  4. VS의 솔루션 탐색기에서 자산 폴더에 ONNX 모델(이름: "분류자")을 추가한 후 프로젝트에는 이제 두 개의 새 파일이 있어야 합니다.

  • classifier.onnx - 이것이 당신의 ONNX 형식 모델입니다.
  • classifier.cs – WinML 코드 파일을 자동으로 생성합니다.

ONNX 모델이 추가된 프로젝트 구조

  1. 애플리케이션을 컴파일할 때 모델이 빌드되도록 하려면 파일을 선택하고 classifier.onnx 선택합니다 Properties. Build Action의 경우 Content를 선택합니다.

이제 classifier.cs 파일에서 새로 생성된 코드를 살펴보겠습니다.

생성된 코드에는 다음 세 가지 클래스가 포함됩니다.

  • classifierModel: 이 클래스에는 모델 인스턴스화 및 모델 평가를 위한 두 가지 메서드가 포함됩니다. 기계 학습 모델 표현을 만들고, 시스템 기본 디바이스에서 세션을 만들고, 특정 입력 및 출력을 모델에 바인딩하고, 모델을 비동기적으로 평가하는 데 도움이 됩니다.
  • classifierInput: 이 클래스는 모델이 예상하는 입력 형식을 초기화합니다. 모델 입력은 입력 데이터에 대한 모델 요구 사항에 따라 달라집니다. 이 경우 입력에는 모델에 전달하는 데 사용되는 이미지의 속성을 설명하는 클래스인 ImageFeatureValue가 필요합니다.
  • classifierOutput: 이 클래스는 모델이 출력할 형식을 초기화합니다. 모델 출력은 모델에서 정의하는 방법에 따라 달라집니다. 이 경우, 출력은 손실이라고 불리는 String 및 TensorFloat(Float32) 형식의 맵(사전) 시퀀스입니다.

이제 이러한 클래스를 사용하여 프로젝트에서 모델을 로드, 바인딩 및 평가합니다.

모델과 입력을 로드하기

모델을 로드하세요

  1. 코드 파일을 두 번 클릭하여 MainPage.xaml.cs 애플리케이션 코드를 엽니다.

  2. 필요한 모든 API에 대한 액세스를 얻으려면 "using" 문을 다음으로 바꿉니다.

// Specify all the using statements which give us the access to all the APIs that you'll need
using System;
using System.Threading.Tasks;
using Windows.AI.MachineLearning;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
  1. 클래스 내 MainPage 의 using 문 다음에 네임스페이스 아래에 다음 변수 선언을 추가합니다 ImageClassifierAppUWP.
        // All the required variable declaration
        private classifierModel modelGen;
        private classifierInput input = new classifierModelInput();
        private classifierOutput output;
        private StorageFile selectedStorageFile;
        private string result = "";
        private float resultProbability = 0;

결과는 다음과 같습니다.

// Specify all the using statements which give us the access to all the APIs that we'll need
using System;
using System.Threading.Tasks;
using Windows.AI.MachineLearning;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

namespace ImageClassifierAppUWP
{
    public sealed partial class MainPage : Page
    {
        // All the required fields declaration
        private classifierModel modelGen;
        private classifierInput input = new classifierInput();
        private classifierOutput output;
        private StorageFile selectedStorageFile;
        private string result = "";
        private float resultProbability = 0;

이제 메서드를 구현합니다 LoadModel . 이 메서드는 ONNX 모델에 액세스하여 메모리에 저장합니다. 그런 다음 이 메서드를 CreateFromStreamAsync 사용하여 모델을 개체로 LearningModel 인스턴스화합니다. 클래스는 LearningModel 학습된 기계 학습 모델을 나타냅니다. 인스턴스화 LearningModel 되면 Windows ML과 상호 작용하는 데 사용하는 초기 개체입니다.

모델을 로드하려면 클래스에서 여러 정적 메서드를 LearningModel 사용할 수 있습니다. 이 경우 메서드를 CreateFromStreamAsync 사용합니다.

이 메서드는 CreateFromStreamAsync mlgen을 사용하여 자동으로 생성되었으므로 이 메서드를 구현할 필요가 없습니다. mlgen에서 생성된 classifier.cs 파일을 두 번 클릭하여 이 메서드를 검토할 수 있습니다.

클래스에 대한 LearningModel 자세한 내용은 LearningModel 클래스 설명서를 검토하세요. 모델을 로드하는 추가 방법에 대한 자세한 내용은 모델 로드 설명서를 검토하세요.

  1. loadModel 클래스 내부의 MainPage.xaml.cs 코드 파일에 MainPage 메서드를 추가합니다.
        private async Task loadModel()
        {
            // Get an access the ONNX model and save it in memory.
            StorageFile modelFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/classifier.onnx"));
            // Instantiate the model. 
            modelGen = await classifierModel.CreateFromStreamAsync(modelFile);
        }
  1. 이제 클래스의 생성자에 새 메서드에 대한 호출을 추가합니다.
        // The main page to initialize and execute the model.
        public MainPage()
        {
            this.InitializeComponent();
            loadModel();
        }

결과는 다음과 같습니다.

        // The main page to initialize and execute the model.
        public MainPage()
        {
            this.InitializeComponent();
            loadModel();
        }

        // A method to load a machine learning model.
        private async Task loadModel()
        {
            // Get an access the ONNX model and save it in memory.  
            StorageFile modelFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/classifier.onnx"));
            // Instantiate the model. 
            modelGen = await classifierModel.CreateFromStreamAsync(modelFile);
        }

이미지 로드

  1. 모델 실행에 대한 네 개의 메서드 호출 시퀀스(변환, 바인딩 및 평가, 출력 추출 및 결과 표시)를 시작하려면 클릭 이벤트를 정의해야 합니다. MainPage.xaml.cs 클래스 안에 있는 MainPage 코드 파일에 다음 메소드를 추가하세요.
        // Waiting for a click event to select a file 
        private async void OpenFileButton_Click(object sender, RoutedEventArgs e)
        {
            if (!await getImage())
            {
                return;
            }
            // After the click event happened and an input selected, begin the model execution. 
            // Bind the model input
            await imageBind();
            // Model evaluation
            await evaluate();
            // Extract the results
            extractResult();
            // Display the results  
            await displayResult();
        }
  1. 이제 메서드를 구현합니다 getImage() . 이 메서드는 입력 이미지 파일을 선택하고 메모리에 저장합니다. MainPage.xaml.cs 클래스 안에 있는 MainPage 코드 파일에 다음 메소드를 추가하세요.
        // A method to select an input image file
        private async Task<bool> getImage()
        {
            try
            {
                // Trigger file picker to select an image file
                FileOpenPicker fileOpenPicker = new FileOpenPicker();
                fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                fileOpenPicker.FileTypeFilter.Add(".jpg");
                fileOpenPicker.FileTypeFilter.Add(".png");
                fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
                selectedStorageFile = await fileOpenPicker.PickSingleFileAsync();
                if (selectedStorageFile == null)
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

이제 비트맵 BGRA8 형식으로 파일의 표현을 가져오는 이미지 Bind() 메서드를 구현합니다.

  1. MainPage 클래스 내 convert() 코드 파일에 MainPage.xaml.cs 메서드 구현을 추가합니다. convert 메서드는 입력 파일의 표현을 BGRA8 형식으로 가져옵니다.
// A method to convert and bind the input image.  
        private async Task imageBind()
        {
            UIPreviewImage.Source = null;
            try
            {
                SoftwareBitmap softwareBitmap;
                using (IRandomAccessStream stream = await selectedStorageFile.OpenAsync(FileAccessMode.Read))
                {
                    // Create the decoder from the stream 
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
                    // Get the SoftwareBitmap representation of the file in BGRA8 format
                    softwareBitmap = await decoder.GetSoftwareBitmapAsync();
                    softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                }
                // Display the image
                SoftwareBitmapSource imageSource = new SoftwareBitmapSource();
                await imageSource.SetBitmapAsync(softwareBitmap);
                UIPreviewImage.Source = imageSource;
                // Encapsulate the image within a VideoFrame to be bound and evaluated
                VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
                // bind the input image
                ImageFeatureValue imageTensor = ImageFeatureValue.CreateFromVideoFrame(inputImage);
                input.data = imageTensor;
            }
            catch (Exception e)
            {
            }
        }

이 섹션에서 수행한 작업의 결과는 다음과 같습니다.

        // Waiting for a click event to select a file 
        private async void OpenFileButton_Click(object sender, RoutedEventArgs e)
        {
            if (!await getImage())
            {
                return;
            }
            // After the click event happened and an input selected, we begin the model execution. 
            // Bind the model input
            await imageBind();
            // Model evaluation
            await evaluate();
            // Extract the results
            extractResult();
            // Display the results  
            await displayResult();
        }

        // A method to select an input image file
        private async Task<bool> getImage()
        {
            try
            {
                // Trigger file picker to select an image file
                FileOpenPicker fileOpenPicker = new FileOpenPicker();
                fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                fileOpenPicker.FileTypeFilter.Add(".jpg");
                fileOpenPicker.FileTypeFilter.Add(".png");
                fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
                selectedStorageFile = await fileOpenPicker.PickSingleFileAsync();
                if (selectedStorageFile == null)
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        // A method to convert and bind the input image.  
        private async Task imageBind()
        {
            UIPreviewImage.Source = null;

            try
            {
                SoftwareBitmap softwareBitmap;
                using (IRandomAccessStream stream = await selectedStorageFile.OpenAsync(FileAccessMode.Read))
                {
                    // Create the decoder from the stream 
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    // Get the SoftwareBitmap representation of the file in BGRA8 format
                    softwareBitmap = await decoder.GetSoftwareBitmapAsync();
                    softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                }
                // Display the image
                SoftwareBitmapSource imageSource = new SoftwareBitmapSource();
                await imageSource.SetBitmapAsync(softwareBitmap);
                UIPreviewImage.Source = imageSource;

                // Encapsulate the image within a VideoFrame to be bound and evaluated
                VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);

                // bind the input image
                ImageFeatureValue imageTensor = ImageFeatureValue.CreateFromVideoFrame(inputImage);
                input.data = imageTensor;
            }
            catch (Exception e)
            {
            }
        }

모델 바인딩 및 평가

다음으로 모델을 기반으로 세션을 만들고, 세션의 입력 및 출력을 바인딩하고, 모델을 평가합니다.

모델을 바인딩하는 세션을 만듭니다.

세션을 만들려면 클래스를 LearningModelSession 사용합니다. 이 클래스는 기계 학습 모델을 평가하는 데 사용되며 모델을 실행하고 평가하는 디바이스에 바인딩합니다. 머신의 특정 디바이스에서 모델을 실행하는 세션을 만들 때 디바이스를 선택할 수 있습니다. 기본 디바이스는 CPU입니다.

비고

디바이스를 선택하는 방법에 대한 자세한 내용은 세션 만들기 설명서를 검토하세요.

모델 입력 및 출력 바인딩:

입력 및 출력을 바인딩하려면 클래스를 LearningModelBinding 사용합니다. 기계 학습 모델에는 입력 및 출력 기능이 있으며, 이 기능은 모델 내부 및 외부로 정보를 전달합니다. 필요한 기능은 Window ML API에서 지원되어야 합니다. 클래스는 LearningModelBinding 명명된 LearningModelSession 입력 및 출력 기능에 값을 바인딩하기 위해 적용됩니다.

바인딩의 구현은 mlgen에 의해 자동으로 생성되므로 처리할 필요가 없습니다. 바인딩은 클래스의 미리 정의된 메서드를 호출하여 구현됩니다 LearningModelBinding . 이 경우 메서드를 Bind 사용하여 명명된 기능 형식에 값을 바인딩합니다.

현재 Windows ML은 Tensors(다차원 배열), 시퀀스(값 벡터), 맵(정보 값 쌍) 및 이미지(특정 형식)와 같은 모든 ONNX 기능 유형을 지원합니다. 모든 이미지는 텐서 형식으로 Windows ML로 표시됩니다. 텐서화는 이미지를 텐서로 변환하는 프로세스이며 바인딩하는 동안 발생합니다.

다행히 텐서화 변환을 처리할 필요가 없습니다. 이전 부분에서 사용한 메서드는 ImageFeatureValue 변환 및 텐서화를 모두 처리하므로 이미지가 모델의 필수 이미지 형식과 일치합니다.

비고

WinML에서 지원하는 기능 유형 및 바인딩 LearningModel 하는 방법에 대한 자세한 내용은 모델 바인딩 설명서를 검토하세요.

모델을 평가합니다.

모델 및 바인딩된 값을 모델의 입력 및 출력에 바인딩하는 세션을 만든 후 모델의 입력을 평가하고 예측을 가져올 수 있습니다. 모델 실행을 실행하려면 LearningModelSession에서 미리 정의된 평가 메서드를 호출해야 합니다. 이 경우 메서드를 EvaluateAsync 사용합니다.

CreateFromStreamAsync마찬가지로 이 EvaluateAsync 메서드도 WinML 코드 생성기에서 자동으로 생성되므로 이 메서드를 구현할 필요가 없습니다. 이 메서드는 classifier.cs 파일에서 검토할 수 있습니다.

이 메서드는 EvaluateAsync 바인딩에 이미 바인딩된 기능 값을 사용하여 기계 학습 모델을 비동기적으로 평가합니다. LearningModelSession으로 세션을 만들고, LearningModelBinding을 사용하여 입력과 출력을 바인딩하며, 모델 평가를 실행하고, LearningModelEvaluationResult 클래스를 사용하여 모델의 출력 특징을 얻습니다.

비고

모델을 실행하는 다른 평가 방법에 대해 알아보려면 LearningModelSession 클래스 설명서를 검토하여 LearningModelSession에서 구현할 수 있는 메서드를 확인하세요.

  1. MainPage 클래스 내의 코드 파일에 다음 메서드 MainPage.xaml.cs 를 추가하여 세션을 만들고 모델을 바인딩하고 평가합니다.
        // A method to evaluate the model
        private async Task evaluate()
        {
            output = await modelGen.EvaluateAsync(input);
        }

결과 추출 및 표시

이제 모델 출력을 추출하고 올바른 결과를 표시해야 합니다. extractResultdisplayResult 메서드를 구현하여 수행합니다.

앞에서 살펴본 것처럼 모델은 두 개의 출력을 반환합니다. 첫 번째는 classLabel라고 불리는 문자열 텐서이고, 두 번째는 손실이라고 불리는 레이블이 지정된 각 분류의 확률을 설명하는 문자열-부동 소수점 맵의 시퀀스입니다. 따라서 결과와 확률을 성공적으로 표시하려면 손실 출력에서 출력을 추출하기만 하면됩니다. 올바른 결과를 반환하려면 가장 높은 확률을 찾아야 합니다.

  1. extractResult 클래스 내의 MainPage.xaml.cs 코드 파일에 MainPage 메서드를 추가합니다.
        private void extractResult()
        {
        // A method to extract output (result and a probability) from the "loss" output of the model 
            var collection = output.loss;
            float maxProbability = 0;
            string keyOfMax = "";

            foreach (var dictionary in collection)
            {
                foreach (var key in dictionary.Keys)
                {
                    if (dictionary[key] > maxProbability)
                    {
                        maxProbability = dictionary[key];
                        keyOfMax = key;
                    }
                }
            }
            result = keyOfMax;
            resultProbability = maxProbability;
        }
  1. displayResult 클래스 내의 MainPage.xaml.cs 코드 파일에 MainPage 메서드를 추가합니다.
        // A method to display the results
        private async Task displayResult()
        {
            displayOutput.Text = result.ToString();
            displayProbability.Text = resultProbability.ToString();
        }

바인딩 및 평가의 결과와 앱의 WinML 코드의 결과 부분 추출 및 표시는 다음과 같습니다.

        // A method to evaluate the model
        private async Task evaluate()
        {
            output = await modelGen.EvaluateAsync(input);
        }

        // A method to extract output (string and a probability) from the "loss" output of the model 
        private void extractResult()
        {
            var collection = output.loss;
            float maxProbability = 0;
            string keyOfMax = "";

            foreach (var dictionary in collection)
            {
                foreach (var key in dictionary.Keys)
                {
                    if (dictionary[key] > maxProbability)
                    {
                        maxProbability = dictionary[key];
                        keyOfMax = key;
                    }
                }
            }
            result = keyOfMax;
            resultProbability = maxProbability;
        }

        // A method to display the results
        private async Task displayResult()
        {
            displayOutput.Text = result.ToString();
            displayProbability.Text = resultProbability.ToString();
        }

완료! 분류 모델을 테스트하기 위해 기본 GUI를 사용하여 Windows 기계 학습 앱을 성공적으로 만들었습니다. 다음 단계는 애플리케이션을 시작하고 Windows 디바이스에서 로컬로 실행하는 것입니다.

애플리케이션 시작

애플리케이션 인터페이스를 완료하고, 모델을 추가하고, WinML 코드를 생성하면 애플리케이션을 테스트할 수 있습니다. 위쪽 도구 모음의 드롭다운 메뉴가 .로 설정되어 있는지 확인합니다 Debug. 디바이스가 Solution Platform 64비트이거나 x64 32비트인 경우 로컬 컴퓨터에서 프로젝트를 실행하도록 x86 변경합니다.

우리의 응용 프로그램을 테스트하기 위해, 당신은 과일의 아래 이미지를 사용합니다. 앱이 이미지의 콘텐츠를 분류하는 방법을 살펴보겠습니다.

과일 이미지 예제

  1. 로컬 디바이스에 이 이미지를 저장하여 앱을 테스트합니다. 필요한 경우 이미지 형식을 jpg로 변경합니다. .jpg, .png, .bmp또는 .gif 형식과 같은 적절한 형식으로 로컬 디바이스의 다른 관련 이미지를 추가할 수도 있습니다.

  2. 프로젝트를 실행하려면 도구 모음의 Start Debugging 단추를 누르거나 F5를 누릅니다.

  3. 애플리케이션이 시작되면 Pick Image를 눌러 로컬 디바이스에서 이미지를 선택하세요.

이미지 선택 대화 상자

결과는 화면에 바로 표시됩니다. 당신이 볼 수 있듯이, 우리의 WinML 응용 프로그램은 성공적으로 99.9% 신뢰 등급으로, 과일이나 야채로 이미지를 분류했다.

성공적인 이미지 분류

요약

모델 생성부터 성공적인 실행까지 첫 번째 Windows Machine Learning 앱을 만들었습니다.

추가 리소스

이 자습서에서 언급한 항목에 대해 자세히 알아보려면 다음 리소스를 방문하세요.