Skip to content

Instantly share code, notes, and snippets.

@DejanMilicic
Last active January 20, 2021 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DejanMilicic/8e504cc4e5202783aff896c3456974f4 to your computer and use it in GitHub Desktop.
Save DejanMilicic/8e504cc4e5202783aff896c3456974f4 to your computer and use it in GitHub Desktop.
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