Last active
January 20, 2021 18:08
-
-
Save DejanMilicic/8e504cc4e5202783aff896c3456974f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.ML; | |
using Microsoft.ML.Data; | |
public class SentimentIssue | |
{ | |
[LoadColumn(0)] | |
public bool Label { get; set; } | |
[LoadColumn(2)] | |
public string Text { get; set; } | |
} | |
public class SentimentPrediction | |
{ | |
[ColumnName("PredictedLabel")] | |
public bool Prediction { get; set; } | |
public float Probability { get; set; } | |
public float Score { get; set; } | |
} | |
public static class SentimentAnalysis | |
{ | |
private const string ModelZipPath = @"SentimentModel.zip"; | |
[ThreadStatic] | |
private static PredictionEngine<SentimentIssue, SentimentPrediction> _engine; | |
private static void Init() | |
{ | |
if (_engine != null) | |
return; | |
MLContext mlContext = new MLContext(); | |
var model = mlContext.Model.Load(ModelZipPath, out var _); | |
_engine = mlContext.Model.CreatePredictionEngine<SentimentIssue, SentimentPrediction>(model); | |
} | |
public static dynamic Analyze(string text) | |
{ | |
Init(); | |
var sentiment = _engine.Predict(new SentimentIssue { Text = text }); | |
return new { Sentiment = sentiment.Prediction ? "toxic" : "nontoxic", Score = sentiment.Probability }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment