예제 #1
0
        private static async Task runTextSentimentAnalysisAsync()
        {
            var modelInput = new List <SentimentAnalysis.ModelInput>
            {
                new SentimentAnalysis.ModelInput
                {
                    TextForAnalysis = getTextInputStringValue()
                }
            };

            var runnerRequest = new SentimentAnalysis.RunnerRequest
            {
                ModelInput = modelInput
            };

            var runnerResponse = await SentimentAnalysis.ModelRunner.Instance.RunClassificationAsync(runnerRequest);

            if (!runnerResponse.Success)
            {
                Console.WriteLine($"Text sentiment analysis failed: {runnerResponse.Message}");
            }
        }
        /// <summary>
        /// Uses ML.NET to predict positive or negative sentiment based on input and trained model.
        /// </summary>
        /// <param name="runnerRequest">Request with input needed for text sentiment analysis.</param>
        /// <returns>Text sentiment prediction result.</returns>
        public async Task <RunnerResponse> RunClassificationAsync(RunnerRequest runnerRequest)
        {
            try
            {
                var modelBuilder = new ModelBuilder();
                var trainedModel = await modelBuilder.TrainAsync();

                var modelMetrics = modelBuilder.Evaluate(trainedModel);

                var modelInput = runnerRequest.ModelInput
                                 .Select(p => new DataModel
                {
                    SentimentText = p.TextForAnalysis
                })
                                 .ToList();
                var modelOutput = modelBuilder.Predict(trainedModel, modelInput)
                                  .Select(p => new ModelOutput
                {
                    PredictedSentiment = p.Sentiment
                })
                                  .ToList();

                return(new RunnerResponse
                {
                    Success = true,
                    ModelOutput = modelOutput
                });
            }
            catch (Exception ex)
            {
                return(new RunnerResponse
                {
                    Success = false,
                    Message = ex.ToExceptionMessage()
                });
            }
        }