简介
TensorFlowSharp - 用于 .NET 语言的 TensorFlow API。TensorFlowSharp 是运行现有模型的良好运行时,并且主要是与底层 TensorFlow 运行时的直接绑定
.安装
最简单的入门方法是使用 TensorFlowSharp 的 NuGet 包,其中包含 .NET API 以及使用 CPU 后端的 64 位 Linux、Mac 和 Windows 的本机库。
nuget install TensorFlowSharp
使用
这个 API 绑定在设计上更接近于使用显式 TensorFlow 图和会话的 Java 和 Go 绑定。您的应用程序通常会创建一个图 (TFGraph) 并在那里设置操作,然后从中创建一个会话 (TFSession),然后使用会话运行器设置输入和输出并执行管道。代码如下
using (var graph = new TFGraph ())
{
// Load the model
graph.Import (File.ReadAllBytes ("MySavedModel"));
using (var session = new TFSession (graph))
{
// Setup the runner
var runner = session.GetRunner ();
runner.AddInput (graph ["input"] [0], tensor);
runner.Fetch (graph ["output"] [0]);
// Run the model
var output = runner.Run ();
// Fetch the results from output:
TFTensor result = output [0];
}
}
如果您的应用程序对 GC 周期很敏感,您可以按如下方式运行您的模型。然后,该Run方法将仅在第一次调用时分配托管内存,并在以后重用它。请注意,这要求您重用Runner实例而不是更改输入数据的形状:
// Some input matrices
var inputs = new float[][,] {
new float[,] { { 1, 2 }, { 3, 4 } },
new float[,] { { 2, 4 }, { 6, 8 } }
};
// Assumes all input matrices have identical shape
var shape = new long[] { inputs[0].GetLongLength(0), inputs[0].GetLongLength(1) };
var size = inputs[0].Length * sizeof(float);
// Empty input and output tensors
var input = new TFTensor(TFDataType.Float, shape, size);
var output = new TFTensor[1];
// Result array for a single run
var result = new float[1, 1];
using (var graph = new TFGraph())
{
// Load the model
graph.Import(File.ReadAllBytes("MySavedModel"));
using (var session = new TFSession(graph))
{
// Setup the runner
var runner = session.GetRunner();
runner.AddInput(graph["input"][0], input);
runner.Fetch(graph["output"][0]);
// Run the model on each input matrix
for (int i = 0; i < inputs.Length; i++)
{
// Mutate the input tensor
input.SetValue(inputs[i]);
// Run the model
runner.Run(output);
// Fetch the result from output into `result`
output[0].GetValue(result);
}
}
}
在您不需要单独设置图表的情况下,会话将为您创建一个。以下示例展示了如何使用 TensorFlow 来计算两个数字的相加
using (var session = new TFSession())
{
var graph = session.Graph;
var a = graph.Const(2);
var b = graph.Const(3);
Console.WriteLine("a=2 b=3");
// Add two constants
var addingResults = session.GetRunner().Run(graph.Add(a, b));
var addingResultValue = addingResults.GetValue();
Console.WriteLine("a+b={0}", addingResultValue);
// Multiply two constants
var multiplyResults = session.GetRunner().Run(graph.Mul(a, b));
var multiplyResultValue = multiplyResults.GetValue();
Console.WriteLine("a*b={0}", multiplyResultValue);
}
Github地址
https://github.com/migueldeicaza/TensorFlowSharp