Skip to content

Instantly share code, notes, and snippets.

@tondrej
Last active April 16, 2018 07:53
Show Gist options
  • Save tondrej/0a7031638c5b944bbc7e73b1d82be81b to your computer and use it in GitHub Desktop.
Save tondrej/0a7031638c5b944bbc7e73b1d82be81b to your computer and use it in GitHub Desktop.
FastText library C# usage
class Program
{
static bool NearestNeighborsCallback(string word, Single score)
{
Console.WriteLine($"\"{word}\": {score}");
return false;
}
static void NearestNeighbors(string modelFileName)
{
using (FastText ft = new FastText())
{
Console.Write($"Loading file \"{modelFileName}\"...");
ft.LoadModel(modelFileName);
Console.WriteLine("done.");
Console.Write("Computing vectors...");
IntPtr vectors = ft.PrecomputeVectors();
try
{
Console.WriteLine("done.");
while (true)
{
Console.WriteLine("positive words:");
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
break;
input = input + "\t";
string[] positive = input.Split(new char[] { ' ', '\t' });
Console.WriteLine("negative words:");
input = Console.ReadLine() + "\t";
string[] negative = input.Split(new char[] { ' ', '\t' });
ft.NN2(vectors, positive, negative, 5, new WordCallback(NearestNeighborsCallback));
Console.WriteLine();
}
}
finally
{
ft.ReleaseVectors(vectors);
}
}
}
static void Main(string[] args)
{
NearestNeighbors(@"C:\Data\fasttext\wiki\enwik9.bin");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment