Xamarin.iOS'ta Core ML 2
Core ML, iOS, macOS, tvOS ve watchOS'ta kullanılabilen bir makine öğrenmesi teknolojisidir. Uygulamaların makine öğrenmesi modellerini temel alarak tahminlerde bulunmasına olanak tanır.
iOS 12'de Core ML bir toplu işlem API'sini içerir. Bu API, Core ML'yi daha verimli hale getirir ve modelin tahmin dizisi yapmak için kullanıldığı senaryolarda performans geliştirmeleri sağlar.
Örnek veri oluşturma
içinde ViewController
, örnek uygulamanın ViewDidLoad
yöntemi, dahil edilen Core ML modelini yükleyen öğesini çağırır LoadMLModel
:
void LoadMLModel()
{
var assetPath = NSBundle.MainBundle.GetUrlForResource("CoreMLModel/MarsHabitatPricer", "mlmodelc");
model = MLModel.Create(assetPath, out NSError mlErr);
}
Ardından örnek uygulama sıralı Core ML tahminleri için giriş olarak kullanılacak 100.000 MarsHabitatPricerInput
nesne oluşturur. Oluşturulan her örnek, güneş paneli sayısı, sera sayısı ve dönüm sayısı için rastgele bir değer kümesine sahiptir:
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);
}
});
// ...
}
Uygulamanın üç düğmesinden birine dokunduğunuzda iki tahmin dizisi yürütülür: biri döngü kullanarak for
, diğeri ise iOS 12'de sunulan yeni toplu iş GetPredictions
yöntemini kullanarak:
async void RunTest(int num)
{
// ...
await FetchNonBatchResults(num);
// ...
await FetchBatchResults(num);
// ...
}
döngü için
Testin for
döngü sürümü, belirtilen sayıda giriş üzerinde naively yinelenir, her biri için çağrır GetPrediction
ve sonucu atar. yöntemi, tahminde bulunmanın ne kadar sürdüğünü çarpımlı hale getirir:
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 (yeni toplu iş API'si)
Testin toplu sürümü giriş dizisinden bir MLArrayBatchProvider
nesne oluşturur (yöntem için GetPredictions
gerekli bir giriş parametresi olduğundan), bir MLPredictionOptions
tahmin hesaplamalarının CPU ile kısıtlanmasını engelleyen ve tahminleri getirmek için API'yi kullanarak GetPredictions
sonucu tekrar atan nesne:
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;
}
Sonuçlar
Hem simülatörde hem de cihazda döngü GetPredictions
tabanlı Core ML tahminlerinden daha hızlı tamamlar.