見出し画像

ML.netでModel Builderを使ってみる その9 例外処理が不足しています

前回のソースコード、当たり前ですが例外エラーが発生して内容が記録されました。
例外エラーが発生しても、異常終了せずにロギングしてクラスライブラリーの処理は終了できます。

これなら実用的と言えそうですが、とても重要な問題が残されています。
クラスライブラリー側で例外エラーが発生して処理できたとしても、呼び出し側のVB.netには何も情報が伝わらないのです。

プログラムを使う人の立場で考えてみましょう。
何かしら画像の判定を行い、判定結果が表示されることを待っています。

処理が終わったようですが、判定結果が何も表示されません。
判定が終わったのかも分からないため、何度も画像の判定を行うでしょう。

VB.net側でプログラムを使う立場の人に対して、何かしらのエラーが発生したことを伝える必要があります。
エラーが発生したから、何が問題なのか調べることが可能になります。

こういう処理、Pythonの時にも書きましたが、プログラムの基本になります。
私の場合、自作する関数は、VB.netならboolean型、C#ならbool型にしています。

例外エラーが発生したらfalse、正常な処理ならばtrueを返すようにしています。
この方法を全ての関数で統一して使っています。

Pythonのコードを書いた時も、確か同じ様な話をしたような気がします。
それから、ConsumeModel.csのロギングや例外エラー処理、自分で挑戦してみると楽しいと思います。

このコード、以下のWebアドレスに掲載されているものを基本にしています。
https://docs.microsoft.com/ja-jp/dotnet/machine-learning/

印刷して学びたい場合もPDFファイルがあるので参考になります。
https://docs.microsoft.com/ja-jp/dotnet/opbuildpdf/machine-learning/toc.pdf?branch=live


#学習 #勉強 #AI #機械学習 #プログラミング #Visual #CSharp #BASIC #ソースコード #Windows #自動判定
#画像 #判定 #検査


VB.netのソースコードです。


Imports System.Reflection
Imports System.Windows.Forms
Imports System.IO
Imports System.Text
Imports Microsoft.VisualBasic.FileIO
Imports System.Globalization


Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


'クラスライブラリーを使う宣言
Dim ClassLibraryObject As Object = New ClassLibrary1.Class1

'写真を入力するファイルの指定
'このフォルダ指定は自分の環境にあったものにしてください。
Dim SpecifyFileToInputPhoto As String = "C:\Users\dws57\source\repos\MlTest\ClassLibrary1\data\assets\CD\7001-115.jpg"

'判別結果の格納
Dim JudgmentResult As String = ""

'判断結果の割合
Dim Probability As Single = 0

'学習データを保存している場所の指示
Dim LocationOfLearningData As String = System.AppDomain.CurrentDomain.BaseDirectory + "MLModel.zip"


'C#のクラスライブラリーで画像の判定を行わせる
Dim BooleanReturn As Boolean = ClassLibraryObject.SampleMachineLearning(SpecifyFileToInputPhoto, JudgmentResult, Probability, LocationOfLearningData)

'例外エラーが発生したか確認する
If BooleanReturn = False Then
'例外処理を行ったと通知する
MsgBox("例外エラーが発生しました")
End If


End Sub

End Class

C#側クラスライブラリのソースコードです。

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.ML;
using static Microsoft.ML.DataOperationsCatalog;
using Microsoft.ML.Vision;
using System.Reflection;
using log4net;

namespace ClassLibrary1
{

public class Class1
{

public bool SampleMachineLearning(string SpecifyFileToInputPhoto,ref string JudgmentResult, ref float Probability,string LocationOfLearningData)
{
//ロギングを開始する
var logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

//関数の起動時の引数を保存する
logger.Info("起動時引数一覧");
logger.Info("SpecifyFileToInputPhoto:" + SpecifyFileToInputPhoto);
logger.Info("LocationOfLearningData:" + LocationOfLearningData);

try
{
//例外エラー発生します
int abc = 0;
abc = 10 / abc;


// Create single instance of sample data from first line of dataset for model input
MlTestML.Model.ModelInput sampleData = new MlTestML.Model.ModelInput()
{
ImageSource = SpecifyFileToInputPhoto,
};

//学習データの位置を指定する
MlTestML.Model.ConsumeModel.modelPath = LocationOfLearningData;


// Make a single prediction on the sample data and print results
var predictionResult = MlTestML.Model.ConsumeModel.Predict(sampleData);

Console.WriteLine("Using model to make single prediction -- Comparing actual Label with predicted Label from sample data...\n\n");
Console.WriteLine($"ImageSource: {sampleData.ImageSource}");
Console.WriteLine($"\n\nPredicted Label value {predictionResult.Prediction} \nPredicted Label scores: [{String.Join(",", predictionResult.Score)}]\n\n");
Console.WriteLine("=============== End of process, hit any key to finish ===============");
//Console.ReadKey();

JudgmentResult = predictionResult.Prediction;

Probability = 0;

for (int i = 0; i < predictionResult.Score.Length; i++)
{
if (Probability < predictionResult.Score[i])
{
Probability = predictionResult.Score[i];
}

}

//関数の終了時の戻り値を保存する
logger.Info("終了時引数一覧");
logger.Info("JudgmentResult:" + JudgmentResult);
logger.Info("Probability:" + Probability);

}
catch (System.Exception ex)
{
logger.Error("HResult:" + ex.HResult);
logger.Error("Exception:"+ex.Message);
return false;
}

//正常終了
return true;

}


}
}


この記事が気に入ったらサポートをしてみませんか?