BotSharp/BotSharp.Algorithm/Bayes/NaiveBayes.cs

63 lines
1.9 KiB
C#
Raw Normal View History

2018-09-10 03:56:32 +00:00
using BotSharp.Algorithm.Estimators;
using BotSharp.Algorithm.Features;
using BotSharp.Algorithm.Statistics;
2018-09-09 14:36:22 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BotSharp.Algorithm.Bayes
{
/// <summary>
/// https://en.wikipedia.org/wiki/Bayes%27_theorem
/// </summary>
2018-09-10 03:56:32 +00:00
public class NaiveBayes<Estimator> where Estimator : IEstimator, new()
2018-09-09 14:36:22 +00:00
{
/// <summary>
/// smoothing function
/// </summary>
2018-09-10 03:56:32 +00:00
private Estimator estomator;
2018-09-09 14:36:22 +00:00
public List<FeaturesDistribution> FeaturesDist { get; set; }
2018-09-09 14:36:22 +00:00
public List<Probability> LabelDist { get; set; }
public NaiveBayes()
{
2018-09-10 03:56:32 +00:00
estomator = new Estimator();
2018-09-09 14:36:22 +00:00
}
/// <summary>
/// calculate posterior probability P(Y|X)
/// X is feature set, Y is label
/// P(X1,...,Xn|Y) = Sum(P(X1|Y) +...+ P(Xn|Y)
/// P(X, Y) = P(Y|X)P(X) = P(X|Y)P(Y) => P(Y|X) = P(Y)P(X|Y)/P(X)
/// </summary>
/// <param name="Y">label</param>
/// <param name="featureSet"></param>
/// <returns></returns>
public double PosteriorProb(string Y, List<Feature> features)
2018-09-09 14:36:22 +00:00
{
double prob = 0;
// prior probability
2018-09-10 03:56:32 +00:00
prob = Math.Log(estomator.Prob(LabelDist, Y), 2);
2018-09-09 14:36:22 +00:00
// posterior probability P(X1,...,Xn|Y) = Sum(P(X1|Y) +...+ P(Xn|Y)
var featuresIfY = FeaturesDist.Where(fd => fd.Label == Y).ToList();
// loop features
for (int x = 0; x < features.Count; x++)
2018-09-09 14:36:22 +00:00
{
var Xn = features[x];
var fv = featuresIfY.First(fd => fd.FeatureName == Xn.Name).FeatureValues;
// features are independent, so calculate every feature prob and sum them
2018-09-10 03:56:32 +00:00
prob += Math.Log(estomator.Prob(fv, Xn.Value), 2);
}
2018-09-09 14:36:22 +00:00
return prob;
}
}
}