■ 이진 클래스 분류 모델을 사용하는 방법을 보여준다.
▶ SentimentData.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using Microsoft.ML.Data; namespace TestProject { /// <summary> /// 감정 데이터 /// </summary> public class SentimentData { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 감정 텍스트 /// </summary> [LoadColumn(0)] public string SentimentText; /// <summary> /// 감정 /// </summary> [LoadColumn(1)] [ColumnName("Label")] public bool Sentiment; #endregion } } |
▶ SentimentPrediction.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using Microsoft.ML.Data; namespace TestProject { /// <summary> /// 감정 예측 /// </summary> public class SentimentPrediction : SentimentData { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 예측 - Prediction /// <summary> /// 예측 /// </summary> [ColumnName("PredictedLabel")] public bool Prediction { get; set; } #endregion #region 확률 - Probability /// <summary> /// 확률 /// </summary> public float Probability { get; set; } #endregion #region 점수 - Score /// <summary> /// 점수 /// </summary> public float Score { get; set; } #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
using System; using System.Collections.Generic; using System.IO; using Microsoft.ML; using Microsoft.ML.Data; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 레이블 파일 경로 /// </summary> private static readonly string _labelFilePath = Path.Combine(Environment.CurrentDirectory, "Data", "label.txt"); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { Console.WriteLine("BEGIN MAIN FUNCTION"); MLContext context = new MLContext(); DataOperationsCatalog.TrainTestData trainTestData = GetTrainTestData(context); ITransformer model = GetModel(context, trainTestData.TrainSet); Evaluate(context, model, trainTestData.TestSet); PredictSingleItem(context, model); Predict(context, model); Console.WriteLine("END MAIN FUNCTION"); } #endregion #region 훈련 테스트 데이터 구하기 - GetTrainTestData(context) /// <summary> /// 훈련 테스트 데이터 구하기 /// </summary> /// <param name="context">ML 컨텍스트</param> /// <returns>훈련 테스트 데이터</returns> public static DataOperationsCatalog.TrainTestData GetTrainTestData(MLContext context) { Console.WriteLine("BEGIN GET TRAIN TEST DATA"); IDataView dataView = context.Data.LoadFromTextFile<SentimentData>(_labelFilePath, hasHeader : false); DataOperationsCatalog.TrainTestData trainTestData = context.Data.TrainTestSplit(dataView, testFraction : 0.2); Console.WriteLine("END GET TRAIN TEST DATA"); return trainTestData; } #endregion #region 모델 구하기 - GetModel(context, trainingDataView) /// <summary> /// 모델 구하기 /// </summary> /// <param name="context">컨텍스트</param> /// <param name="trainingDataView">훈련 데이터 뷰</param> /// <returns>모델</returns> public static ITransformer GetModel(MLContext context, IDataView trainingDataView) { Console.WriteLine("BEGIN GET MODEL FUNCTION"); var estimator = context.Transforms.Text.FeaturizeText ( outputColumnName : "Features", inputColumnName : nameof(SentimentData.SentimentText) ) .Append ( context.BinaryClassification.Trainers.SdcaLogisticRegression ( labelColumnName : "Label", featureColumnName : "Features" ) ); Console.WriteLine("BEGIN CREATE AND TRAIN THE MODEL"); var model = estimator.Fit(trainingDataView); Console.WriteLine("END CREATE AND TRAIN THE MODEL"); Console.WriteLine("END GET MODEL FUNCTION"); return model; } #endregion #region 평가하기 - Evaluate(context, model, testDataView) /// <summary> /// 평가하기 /// </summary> /// <param name="context">ML 컨텍스트</param> /// <param name="model">모델</param> /// <param name="testDataView">테스트 데이터 뷰</param> public static void Evaluate(MLContext context, ITransformer model, IDataView testDataView) { Console.WriteLine("BEGIN EVALUATE FUNCTION"); IDataView predictions = model.Transform(testDataView); CalibratedBinaryClassificationMetrics metrics = context.BinaryClassification.Evaluate(predictions, "Label"); Console.WriteLine("MODEL QUALITY METRICS EVALUATION"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine($"ACCURACY : {metrics.Accuracy:P2}" ); Console.WriteLine($"AUC : {metrics.AreaUnderRocCurve:P2}"); Console.WriteLine($"F1SCORE : {metrics.F1Score:P2}" ); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("END EVALUATE FUNCTION"); } #endregion #region 단일 항목 예측하기 - PredictSingleItem(context, model) /// <summary> /// 단일 항목 예측하기 /// </summary> /// <param name="context">컨텍스트</param> /// <param name="model">모델</param> private static void PredictSingleItem(MLContext context, ITransformer model) { Console.WriteLine("BEGIN PREDICT SINGLE ITEM FUNCTION"); PredictionEngine<SentimentData, SentimentPrediction> predictionEngine = context.Model.CreatePredictionEngine<SentimentData, SentimentPrediction>(model); SentimentData sentimentData = new SentimentData { SentimentText = "This was a very bad steak" }; SentimentPrediction sentimentPrediction = predictionEngine.Predict(sentimentData); Console.WriteLine("--------------------------------------------------"); Console.WriteLine($"SENTIMENT : {sentimentPrediction.SentimentText}" ); Console.WriteLine($"PREDICTION : {(Convert.ToBoolean(sentimentPrediction.Prediction) ? "Positive" : "Negative")}"); Console.WriteLine($"PROBABILITY : {sentimentPrediction.Probability}" ); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("END PREDICT SINGLE ITEM FUNCTION"); } #endregion #region 예측하기 - Predict(context, model) /// <summary> /// 예측하기 /// </summary> /// <param name="context">ML 컨텍스트</param> /// <param name="model">모델</param> public static void Predict(MLContext context, ITransformer model) { Console.WriteLine("BEGIN PREDICT FUNCTION"); IEnumerable<SentimentData> sentimentDataEnumerable = new[] { new SentimentData { SentimentText = "This was a horrible meal" }, new SentimentData { SentimentText = "I love this spaghetti." } }; IDataView sentimentDataView = model.Transform(context.Data.LoadFromEnumerable(sentimentDataEnumerable)); IEnumerable<SentimentPrediction> sentimentPredictionEnumerable = context.Data.CreateEnumerable<SentimentPrediction>(sentimentDataView, reuseRowObject : false); Console.WriteLine("--------------------------------------------------"); foreach(SentimentPrediction sentimentPrediction in sentimentPredictionEnumerable) { Console.WriteLine($"SENTIMENT : {sentimentPrediction.SentimentText}"); Console.WriteLine($"PREDICTION : {(Convert.ToBoolean(sentimentPrediction.Prediction) ? "Positive" : "Negative")}"); Console.WriteLine($"PROBABILITY : {sentimentPrediction.Probability}"); Console.WriteLine("--------------------------------------------------"); } Console.WriteLine("END PREDICT FUNCTION"); } #endregion } } |