Share via


Xamarin.iOS의 코어 ML 2

핵심 ML은 iOS, macOS, tvOS 및 watchOS에서 사용할 수 있는 기계 학습 기술입니다. 이를 통해 앱은 기계 학습 모델을 기반으로 예측을 할 수 있습니다.

iOS 12에서 Core ML에는 일괄 처리 API가 포함됩니다. 이 API는 Core ML을 보다 효율적으로 만들고 모델이 예측 시퀀스를 만드는 데 사용되는 시나리오에서 성능 향상을 제공합니다.

샘플 데이터 생성

에서 ViewController샘플 앱의 ViewDidLoad 메서드 호출 LoadMLModel은 포함된 Core ML 모델을 로드합니다.

void LoadMLModel()
{
    var assetPath = NSBundle.MainBundle.GetUrlForResource("CoreMLModel/MarsHabitatPricer", "mlmodelc");
    model = MLModel.Create(assetPath, out NSError mlErr);
}

그런 다음 샘플 앱은 순차적 Core ML 예측에 대한 입력으로 사용할 100,000 MarsHabitatPricerInput 개의 개체를 만듭니다. 생성된 각 샘플에는 태양 전지판 수, 온실 수 및 에이커 수에 대해 임의의 값이 설정됩니다.

async void CreateInputs(int num)
{
    // ...
    Random r = new Random();
    await Task.Run(() =>
    {
        for (int i = 0; i < num; i++)
        {
            double solarPanels = r.NextDouble() * MaxSolarPanels;
            double greenHouses = r.NextDouble() * MaxGreenHouses;
            double acres = r.NextDouble() * MaxAcres;
            inputs[i] = new MarsHabitatPricerInput(solarPanels, greenHouses, acres);
        }
    });
    // ...
}

앱의 세 가지 단추를 탭하면 두 가지 예측 시퀀스가 실행됩니다. 하나는 루프를 for 사용하고 다른 하나는 iOS 12에 도입된 새 일괄 처리 GetPredictions 방법을 사용합니다.

async void RunTest(int num)
{
    // ...
    await FetchNonBatchResults(num);
    // ...
    await FetchBatchResults(num);
    // ...
}

for 루프

for 테스트의 루프 버전은 지정된 수의 입력을 순진하게 반복하여 각각을 호출 GetPrediction 하고 결과를 카드. 메서드는 예측을 수행하는 데 걸리는 시간을 초과합니다.

async Task FetchNonBatchResults(int num)
{
    Stopwatch stopWatch = Stopwatch.StartNew();
    await Task.Run(() =>
    {
        for (int i = 0; i < num; i++)
        {
            IMLFeatureProvider output = model.GetPrediction(inputs[i], out NSError error);
        }
    });
    stopWatch.Stop();
    nonBatchMilliseconds = stopWatch.ElapsedMilliseconds;
}

GetPredictions(새 일괄 처리 API)

테스트의 일괄 처리 버전은 입력 배열에서 개체를 만듭니다 MLArrayBatchProvider (메서드에 GetPredictions 필요한 입력 매개 변수이므로). MLPredictionOptions예측 계산이 CPU로 제한되지 않도록 하고 API를 사용하여 GetPredictions 예측을 가져오고 결과를 다시 카드 개체입니다.

async Task FetchBatchResults(int num)
{
    var batch = new MLArrayBatchProvider(inputs.Take(num).ToArray());
    var options = new MLPredictionOptions()
    {
        UsesCpuOnly = false
    };

    Stopwatch stopWatch = Stopwatch.StartNew();
    await Task.Run(() =>
    {
        model.GetPredictions(batch, options, out NSError error);
    });
    stopWatch.Stop();
    batchMilliseconds = stopWatch.ElapsedMilliseconds;
}

결과

시뮬레이터와 디바이스 GetPredictions 모두에서 루프 기반 Core ML 예측보다 더 빠르게 완료됩니다.