2018-09-11 03:35:33 +00:00
|
|
|
|
using BotSharp.NLP.Tokenize;
|
|
|
|
|
|
using System;
|
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
using System.Linq;
|
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
|
|
namespace BotSharp.NLP.Txt2Vec
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// A one hot encoding is a representation of categorical variables as binary vectors.
|
|
|
|
|
|
/// Each integer value is represented as a binary vector that is all zero values except the index of the integer, which is marked with a 1.
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public class OneHotEncoder
|
|
|
|
|
|
{
|
|
|
|
|
|
public List<Sentence> Sentences { get; set; }
|
|
|
|
|
|
|
2018-09-12 20:31:20 +00:00
|
|
|
|
public List<string> Words { get; set; }
|
2018-09-11 03:35:33 +00:00
|
|
|
|
|
|
|
|
|
|
public void Encode(Sentence sentence)
|
|
|
|
|
|
{
|
|
|
|
|
|
InitDictionary();
|
|
|
|
|
|
|
2018-09-12 20:31:20 +00:00
|
|
|
|
var vector = Words.Select(x => 0D).ToArray();
|
2018-09-11 03:35:33 +00:00
|
|
|
|
|
|
|
|
|
|
sentence.Words.ForEach(w =>
|
|
|
|
|
|
{
|
2018-09-13 20:01:40 +00:00
|
|
|
|
int index = Words.IndexOf(w.Lemma);
|
2018-09-11 03:35:33 +00:00
|
|
|
|
if(index > 0)
|
|
|
|
|
|
{
|
|
|
|
|
|
vector[index] = 1;
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
sentence.Vector = vector;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2018-09-12 20:31:20 +00:00
|
|
|
|
public List<string> EncodeAll()
|
2018-09-11 03:35:33 +00:00
|
|
|
|
{
|
|
|
|
|
|
InitDictionary();
|
2018-09-12 20:31:20 +00:00
|
|
|
|
|
2018-09-11 21:17:12 +00:00
|
|
|
|
Sentences.ForEach(sent => Encode(sent));
|
|
|
|
|
|
//Parallel.ForEach(Sentences, sent => Encode(sent));
|
2018-09-12 20:31:20 +00:00
|
|
|
|
|
|
|
|
|
|
return Words;
|
2018-09-11 03:35:33 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2018-09-12 20:31:20 +00:00
|
|
|
|
private List<string> InitDictionary()
|
2018-09-11 03:35:33 +00:00
|
|
|
|
{
|
2018-09-12 20:31:20 +00:00
|
|
|
|
if (Words == null)
|
2018-09-11 03:35:33 +00:00
|
|
|
|
{
|
2018-09-13 20:01:40 +00:00
|
|
|
|
Words = new List<string>();
|
|
|
|
|
|
Sentences.ForEach(x =>
|
|
|
|
|
|
{
|
|
|
|
|
|
Words.AddRange(x.Words.Where(w => w.IsAlpha).Select(w => w.Lemma));
|
|
|
|
|
|
});
|
|
|
|
|
|
Words = Words.Distinct().OrderBy(x => x).ToList();
|
2018-09-11 03:35:33 +00:00
|
|
|
|
}
|
2018-09-12 20:31:20 +00:00
|
|
|
|
|
|
|
|
|
|
return Words;
|
2018-09-11 03:35:33 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|