/// <summary> /// 基础矩阵运算 /// </summary> public static void BasicMatrixOperation() { using (var s = new TFSession()) { var g = s.Graph; //1x2矩阵 var matrix1 = g.Const(new double[, ] { { 1, 2 } }); //2x1矩阵 var matrix2 = g.Const(new double[, ] { { 3 }, { 4 } }); var product = g.MatMul(matrix1, matrix2); var result = s.GetRunner().Run(product); Console.WriteLine("矩阵相乘的值:" + ((double[, ])result.GetValue())[0, 0]); // 矩阵相乘的值:11 }; }
public bool Init(string filename, Dictionary <int, string> classes) { bool success = true; try { m_modelFile = filename; m_classes = classes; m_graph = new TFGraph(); byte[] model = File.ReadAllBytes(m_modelFile); m_graph.Import(new TFBuffer(model)); m_session = new TFSession(m_graph); } catch (Exception ex) { m_lastErrorMsg = ex.Message; success = false; } return(success); }
public void nShould_Transpose(double [,] x) { using (var graph = new TFGraph()) using (var session = new TFSession(graph)) { TFOutput a = graph.Placeholder(TFDataType.Double, new TFShape(2)); TFOutput r = graph.Transpose(a); TFTensor [] result = session.Run(new [] { a }, new TFTensor [] { x }, new [] { r }); double [,] actual = (double [, ])result [0].GetValue(); double [,] expected = new double [x.GetLength(1), x.GetLength(0)]; for (int i = 0; i < expected.GetLength(0); i++) { for (int j = 0; j < expected.GetLength(1); j++) { expected [i, j] = x [j, i]; } } TestUtils.MatrixEqual(expected, actual, precision: 10); } }
//to remove //private bool fond = false; //private string[] labels2; //private TFSession session2; //private TFGraph graph2; //public static Color32[] img32; //public TextAsset labelMap2; //public TextAsset model2; //private Thread modelThread2; // Use this for initialization void Start() { #if UNITY_ANDROID TensorFlowSharp.Android.NativeBinding.Init(); #endif //load labels into string array labels = labelMap.ToString().Split('\n'); //load graph graph = new TFGraph(); graph.Import(model.bytes); session = new TFSession(graph); string[] lines = dictMap.text.Split("\n"[0]); d = new Dictionary <string, string>(); foreach (string line in lines) { String[] strlist = line.Split(spearator); d.Add(strlist[0].ToLower().Trim(), strlist[1].Trim()); } hc = new HelloClient(); }
public bool LoadModelFromPath(string modelPath) { if (_bModelLoaded) return true; Logger.Print("Load TF model from '{0}'", modelPath); byte[] bytes = File.ReadAllBytes(modelPath); if (bytes == null || bytes.Length == 0) { Logger.Error("TFModel.LoadModelFromPath - failed to load tf model from '{0}'", modelPath); return false; } try { _tfGraph.Import(bytes); _session = new TFSession(_tfGraph); } catch (Exception ex) { Logger.Exception(ex); return false; } return true; }
public static TFTensor CreateTensorFromMemoryJpg(Byte[] jpeg, TFDataType destinationDataType = TFDataType.Float) { // DecodeJpeg uses a scalar String-valued tensor as input. var tensor = TFTensor.CreateString(jpeg); TFOutput input; TFOutput output; // Construct a graph to normalize the image using (var graph = ConstructGraphToNormalizeImage2(out input, out output, destinationDataType)) { // Execute that graph to normalize this one image using (var session = new TFSession(graph)) { var normalized = session.Run( inputs: new[] { input }, inputValues: new[] { tensor }, outputs: new[] { output }); return(normalized[0]); } } }
// Convert the image in filename to a Tensor suitable as input to the Inception model. static TFTensor CreateTensorFromImageFile(string file) { var contents = File.ReadAllBytes(file); // DecodeJpeg uses a scalar String-valued tensor as input. var tensor = TFTensor.CreateString(contents); TFGraph graph; TFOutput input, output; // Construct a graph to normalize the image ConstructGraphToNormalizeImage(out graph, out input, out output); // Execute that graph to normalize this one image using (var session = new TFSession(graph)) { var normalized = session.Run(null, inputs: new [] { input }, inputValues: new [] { tensor }, outputs: new [] { output }); return(normalized [0]); } }
//初始化 private static void InitVariable(TFGraph g, TFSession sess) { Console.WriteLine("。。。。。。。。。。。。。。。。。初始化。。。。。。。。。。。。。。。。。。"); TFStatus status = new TFStatus(); var a = g.VariableV2(TFShape.Scalar, TFDataType.Double); var initA = g.Assign(a, g.Const(1.5)); var b = g.VariableV2(new TFShape(99), TFDataType.Int32); //var initB = g.Assign(b, g.Range(g.Const(1),g.Const(5))); var initB = g.Assign(b, g.Range(g.Const(1), g.Const(100))); var run = sess.GetRunner(); run.AddTarget(initA.Operation, initB.Operation).Run(status); Console.WriteLine(status.StatusCode); var res = run.Fetch(a, b).Run(); Console.WriteLine(res[0].GetValue()); Console.WriteLine(string.Join(",", (int[])res[1].GetValue())); }
//基础常量运算,演示了常量的使用 static void BasicOperation() { using (var s = new TFSession()) { var g = s.Graph; //建立两个TFOutput,都是常数 var v1 = g.Const(1.5); var v2 = g.Const(0.5); //建立一个相加的运算 var add = g.Add(v1, v2); //获得runner var runner = s.GetRunner(); //相加 var result = runner.Run(add); //获得result的值2 Console.WriteLine($"相加的结果:{result.GetValue()}"); } }
public void StringTestWithMultiDimStringTensorAsInputAndScalarStringAsOutput() { using (var graph = new TFGraph()) using (var session = new TFSession(graph)) { var X = graph.Placeholder(TFDataType.String, new TFShape(-1)); var delimiter = graph.Const(TFTensor.CreateString(Encoding.UTF8.GetBytes("/"))); var indices = graph.Const(0); var Y = graph.ReduceJoin(graph.StringSplit(X, delimiter).values, indices, separator: " "); var dataX = new string[] { "Thank/you/very/much!.", "I/am/grateful/to/you.", "So/nice/of/you." }; var bytes = new byte[dataX.Length][]; bytes[0] = Encoding.UTF8.GetBytes(dataX[0]); bytes[1] = Encoding.UTF8.GetBytes(dataX[1]); bytes[2] = Encoding.UTF8.GetBytes(dataX[2]); var tensorX = TFTensor.CreateString(bytes, new TFShape(3)); var outputTensors = session.Run(new TFOutput[] { X }, new TFTensor[] { tensorX }, new[] { Y }); var outputY = Encoding.UTF8.GetString(TFTensor.DecodeString(outputTensors[0])); Assert.Equal(string.Join(" ", dataX).Replace("/", " "), outputY); } }
// Convert the image in filename to a Tensor suitable as input to the Inception model. public static TFTensor CreateTensorFromImageFile(string file, TFDataType destinationDataType = TFDataType.Float) { var contents = File.ReadAllBytes(file); // DecodeJpeg uses a scalar String-valued tensor as input. var tensor = TFTensor.CreateString(contents); // Construct a graph to normalize the image using (var graph = ConstructGraphToNormalizeImage(out TFOutput input, out TFOutput output, destinationDataType)) { // Execute that graph to normalize this one image using (var session = new TFSession(graph)) { var normalized = session.Run( inputs: new[] { input }, inputValues: new[] { tensor }, outputs: new[] { output }); return(normalized[0]); } } }
public void ComputeGradientMSE() { using (var graph = new TFGraph()) using (var session = new TFSession(graph)) { var X = graph.Const(5.5f); var Y = graph.Const(2.09f); var W = graph.Const(0.1078f); var b = graph.Const(0.1021f); var pred = graph.Add(graph.Mul(X, W, "x_w"), b); var cost = graph.Div(graph.ReduceSum(graph.Pow(graph.Sub(pred, Y), graph.Const(2f))), graph.Mul(graph.Const(2f), graph.Const((float)17), "2_n_samples")); var g = graph.AddGradients(new TFOutput[] { cost }, new[] { W }); var r = session.Run(new TFOutput[] { }, new TFTensor[] { }, new TFOutput[] { cost, g[0] }); var d = (float)r[0].GetValue(); Assert.InRange(d, 0.057236027 - _tolerance, 0.057236027 + _tolerance); d = (float)r[1].GetValue(); Assert.InRange(d, -0.4513235 - _tolerance, -0.4513235 + _tolerance); } }
// // Port of https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/linear_regression.py // void LinearRegression() { Console.WriteLine("Linear regression"); // Parameters var learning_rate = 0.01; var training_epochs = 1000; var display_step = 50; // Training data var train_x = new double [] { 3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167, 7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1 }; var train_y = new double [] { 1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221, 2.827, 3.465, 1.65, 2.904, 2.42, 2.94, 1.3 }; var n_samples = train_x.Length; using (var g = new TFGraph()) { var s = new TFSession(g); var rng = new Random(); // tf Graph Input var X = g.Placeholder(TFDataType.Float); var Y = g.Placeholder(TFDataType.Float); var W = g.Variable(g.Const(rng.Next()), operName: "weight"); var b = g.Variable(g.Const(rng.Next()), operName: "bias"); var pred = g.Add(g.Mul(X, W), b); var cost = g.Div(g.ReduceSum(g.Pow(g.Sub(pred, Y), g.Const(2))), g.Mul(g.Const(2), g.Const(n_samples))); // STuck here: TensorFlow bindings need to surface gradient support // waiting on Google for this // https://github.com/migueldeicaza/TensorFlowSharp/issues/25 } }
public float Detect(Color32[] data) { using (var session = new TFSession(this.graph)) { using (var tensor_input_image = TransformInput(data, inputSize, inputSize)) { var runner = session.GetRunner(); runner.AddInput(this.graph[INPUT_NODE_NAME][0], tensor_input_image) .Fetch(graph[OUTPUT_NODE_NAME][0]); UnityEngine.Debug.Log("runner.Run()"); var output = runner.Run(); // change tensor output to float array // netout shape is [1, NUM_CLASSES] var tmp = (float[, ])output[0].GetValue(jagged: false); List <float> netout = new List <float>() { }; for (int i = 0; i < NUM_CLASSES; i++) { netout.Add(tmp[0, i]); } var sorted = netout.Select((x, i) => new KeyValuePair <float, int>(x, i)) .OrderBy(x => - x.Key) .ToList(); List <int> sorted_idx = sorted.Select(x => x.Value).ToList(); var first_idx = sorted_idx[0]; var second_idx = sorted_idx[1]; var third_idx = sorted_idx[2]; return((second_idx * 10 * netout[second_idx]) + (third_idx * 10 * netout[third_idx]) + (first_idx * 10 * (1 - netout[second_idx] - netout[third_idx]))); } } }
public 图片转换成张量类() { graph1 = new TFGraph(); input = graph1.Placeholder(TFDataType.String); //output = graph1.ResizeBilinear( // images: graph1.ExpandDims( // input: graph1.Cast( // graph1.DecodeJpeg(contents: input, channels: 3), DstT: TFDataType.Float), // dim: graph1.Const(0, "make_batch")), // size: graph1.Const(new int[] { 208, 208 }, "size")); //ResizeBilinear: 图像缩放,双线性插值 - 图像中心对齐 //ExpandDims: 想要维度增加一维 //Cast:tf.cast 类型转换 函数 //DecodeJpeg:预处理 尺寸调整 decode_jpeg函数 output = graph1.ResizeBilinear( images: graph1.ExpandDims( input: graph1.Div( x: graph1.Cast( x: graph1.DecodeJpeg( contents: input, channels: 3), DstT: TFDataType.Float), y: graph1.Const((float)255, "div")), dim: graph1.Const(0, "make_batch")), size: graph1.Const(new int[] { 208, 208 }, "size")); session = new TFSession(graph1); //runner = session.GetRunner(); //runner.Fetch(output); }
public void TestParametersWithIndexes() { Console.WriteLine("Testing Parameters with indexes"); var status = new TFStatus(); using (var g = new TFGraph()) { var s = new TFSession(g, status); var split = new TFOperationDesc(g, "Split", "Split") .AddInput(ScalarConst(0, g, status)[0]) .AddInput(ScalarConst(new TFTensor(new int[] { 1, 2, 3, 4 }), g, status, "array")[0]) .SetAttr("num_split", 2) .FinishOperation(); var add = new TFOperationDesc(g, "Add", "Add") .AddInput(split[0]).AddInput(split[1]).FinishOperation()[0]; // fetch using colon separated names var fetched = s.GetRunner().Fetch("Split:1").Run()[0]; var vals = fetched.GetValue() as int[]; if (vals[0] != 3 || vals[1] != 4) { throw new Exception("Expected the values 3 and 4"); } // Add inputs using colon separated names. var t = new TFTensor(new int[] { 4, 3, 2, 1 }); var ret = (s.GetRunner().AddInput("Split:0", t).AddInput("Split:1", t).Fetch("Add").Run()).GetValue(0) as TFTensor; var val = ret.GetValue() as int[]; if (val[0] != 8 || val[1] != 6 || val[2] != 4 || val[3] != 2) { throw new Exception("Expected 8, 6, 4, 2"); } } Console.WriteLine("success"); }
void Start() { TextAsset graphModel = Resources.Load("frozen_model") as TextAsset; var graph = new TFGraph(); graph.Import(graphModel.bytes); var session = new TFSession(graph); Texture2D image = Resources.Load(imageName) as Texture2D; image = scaled(image, ImageSize, ImageSize); var tensor = TransformInput(image.GetPixels32(), ImageSize, ImageSize); var runner = session.GetRunner(); runner.AddInput(graph ["image"] [0], tensor); runner.Fetch( graph ["heatmap"] [0], graph ["offset_2"] [0], graph ["displacement_fwd_2"] [0], graph ["displacement_bwd_2"] [0] ); var result = runner.Run(); var heatmap = (float [, , , ])result [0].GetValue(jagged: false); var offsets = (float [, , , ])result [1].GetValue(jagged: false); var displacementsFwd = (float [, , , ])result [2].GetValue(jagged: false); var displacementsBwd = (float [, , , ])result [3].GetValue(jagged: false); //Debug.Log(mean(heatmap)); poses = posenet.DecodeMultiplePoses( heatmap, offsets, displacementsFwd, displacementsBwd, outputStride: 16, maxPoseDetections: 15, scoreThreshold: 0.5f, nmsRadius: 20); }
public static TFTensor CreateTensorFromBGR(Byte[] rgb, TFDataType destinationDataType = TFDataType.Float) { // DecodeJpeg uses a scalar String-valued tensor as input. //var tensor = TFTensor.CreateString(bgr); /* * byte[] floatValues = new byte[640 * 480 * 3]; * int j = 0; * for (int i = 0; i < rgb.Length/4; i++) * { * floatValues[j * 3 + 0] = (rgb[i * 4 + 0]) ; * floatValues[j * 3 + 1] = (rgb[i * 4 + 1]) ; * floatValues[j * 3 + 2] = (rgb[i * 4 + 2]) ; * j++; * }*/ TFShape shape = new TFShape(480, 640, 3); var tensor = TFTensor.FromBuffer(shape, rgb, 0, rgb.Length); TFOutput input; TFOutput output; // Construct a graph to normalize the image using (var graph = ConstructGraphToNormalizeImage(out input, out output, destinationDataType)) { // Execute that graph to normalize this one image using (var session = new TFSession(graph)) { var normalized = session.Run( inputs: new[] { input }, inputValues: new[] { tensor }, outputs: new[] { output }); return(normalized[0]); } } }
public void BasicConstantOps() { using (TFGraph g = new TFGraph()) using (TFSession s = new TFSession(g)) { var a = g.Const(2); Assert.NotNull(a); Assert.Equal(TFDataType.Int32, a.OutputType); var b = g.Const(3); Assert.NotNull(b); Assert.Equal(TFDataType.Int32, b.OutputType); // Add two constants var results = s.GetRunner().Run(g.Add(a, b)); Assert.NotNull(results); Assert.IsType <TFTensor>(results); Assert.Equal(TFDataType.Int32, results.TensorType); Assert.Equal(0, results.NumDims); Assert.Equal(0, results.Shape.Length); var val = results.GetValue(); Assert.NotNull(val); Assert.Equal(5, val); // Multiply two constants results = s.GetRunner().Run(g.Mul(a, b)); Assert.NotNull(results); Assert.IsType <TFTensor>(results); Assert.Equal(TFDataType.Int32, results.TensorType); Assert.Equal(0, results.NumDims); Assert.Equal(0, results.Shape.Length); Assert.NotNull(results.GetValue()); Assert.Equal(6, results.GetValue()); } }
static void Main(string[] args) { // 创建图 var g = new TFGraph(); // 定义操作,用于初始化变量 TFOperation init; // 定义值,用于保存变量的值 TFOutput value; // 定义一个变量,初始值为1.5 var a = g.Variable(g.Const(1.5), out init, out value); // 定义一个常量,表示每次循环变量增加值 var inc = g.Const(0.5); // 定义一个操作,将变量a的值value加上inc,然后赋值给a var update = g.AssignVariableOp(a, g.Add(value, inc)); // 会话 var sess = new TFSession(g); // 变量使用前一定要初始化 sess.GetRunner().AddTarget(init).Run(); for (var i = 0; i < 5; i++) { // 每次执行更新操作,都取出value的值存放到result中 // Fetch可以一次取出多个值 var result = sess.GetRunner().Fetch(value).AddTarget(update).Run(); // 输出每次循环变量的值 Console.WriteLine("result {0}:{1}", i, result[0].GetValue()); } }
static void Main(string[] args) { 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); Console.WriteLine("All Setup"); Console.ReadKey(); } }
void BasicMatrix() { Console.WriteLine("Basic matrix"); using (var g = new TFGraph()) { var s = new TFSession(g); // 1x2 matrix var matrix1 = g.Const(new double [, ] { { 3, 3 } }); // 2x1 matrix var matrix2 = g.Const(new double [, ] { { 2 }, { 2 } }); // multiply var product = g.MatMul(matrix1, matrix2); var result = s.GetRunner().Run(product); Console.WriteLine("Tensor ToString=" + result); Console.WriteLine("Value [0,0]=" + ((double[, ])result.GetValue())[0, 0]); }; }
void BasicMultidimensionalArray() { Console.WriteLine("Basic multidimensional array"); using (var g = new TFGraph()) { var s = new TFSession(g); var var_a = g.Placeholder(TFDataType.Int32); var mul = g.Mul(var_a, g.Const(2)); var a = new int[, , ] { { { 0, 1 }, { 2, 3 } }, { { 4, 5 }, { 6, 7 } } }; var result = s.GetRunner().AddInput(var_a, a).Fetch(mul).Run() [0]; var actual = (int[, , ])result.GetValue(); var expected = new int[, , ] { { { 0, 2 }, { 4, 6 } }, { { 8, 10 }, { 12, 14 } } }; Console.WriteLine("Actual: " + RowOrderJoin(actual)); Console.WriteLine("Expected: " + RowOrderJoin(expected)); Assert(expected.Cast <int> ().SequenceEqual(actual.Cast <int> ())); }; }
public void Should_ClipByAverageNorm(double[,] m, double norm, int axis, double[,] expected) { using (var graph = new TFGraph()) using (var session = new TFSession(graph)) { var matrix = graph.Placeholder(TFDataType.Double); var clip_norm = graph.Placeholder(TFDataType.Double); var a = graph.Const(new TFTensor(axis)); TFOutput y = graph.ClipByNorm(matrix, clip_norm, a); if (expected != null) { TFTensor[] result = session.Run(new[] { matrix, clip_norm }, new TFTensor[] { m, norm }, new[] { y }); double[,] actual = (double[, ])result[0].GetValue(); TestUtils.MatrixEqual(expected, actual, precision: 10); } else { Assert.Throws <TFException>(() => session.Run(new[] { matrix, clip_norm }, new TFTensor[] { m, norm }, new[] { y })); } } }
/// Loads the tensorflow graph model to generate a TFGraph object public void InitializeCoreBrain() { #if ENABLE_TENSORFLOW #if UNITY_ANDROID // This needs to ba called only once and will raise an exception if // there are multiple internal brains try{ TensorFlowSharp.Android.NativeBinding.Init(); } catch { } #endif if (graphModel != null) { graph = new TFGraph(); graph.Import(graphModel.bytes); session = new TFSession(graph); if (graph[graphScope + BatchSizePlaceholderName] != null) { hasBatchSize = true; } if ((graph[graphScope + RecurrentInPlaceholderName] != null) && (graph[graphScope + RecurrentOutPlaceholderName] != null)) { hasRecurrent = true; } if (graph[graphScope + StatePlacholderName] != null) { hasState = true; } } #endif }
public Result Run(byte[] image) { var result = new Result(); using (var session = new TFSession(_graph)) { var tensor = ImageUtil.CreateTensorFromImage(image); var runner = session.GetRunner(); runner.AddInput(_graph["Placeholder"][0], tensor).Fetch(_graph["loss"][0]); var output = runner.Run(); var allResults = output[0]; var probabilities = ((float[][])allResults.GetValue(jagged: true))[0]; for (var i = 0; i < probabilities.Length; i++) { if (probabilities[i] > result.Idx) { result.Label = _labels[i]; result.Idx = probabilities[i]; } } } return(result); }
static void Main(string[] args) { // 创建图 var g = new TFGraph(); // 创建一些变量 var x = g.Const(3.0); // x=3 var y1 = g.Square(x); // x^2=9 var y2 = g.Square(y1); // x^4=81 var y3 = g.Square(y2); // x^8=6561 // 计算倾斜度d(y1+y3)=d(x^2 + x^8)=2*x+8*x^7=17502 var a = g.AddGradients(new[] { y1, y3 }, new[] { x }); // 创建会话 var sess = new TFSession(g); // 计算结果 var result = sess.Run(new TFOutput[] { }, new TFTensor[] { }, a); // 输出计算结果 Console.WriteLine((double)result[0].GetValue()); // 17502 }
public static TFTensor CreateTensorFromBuffer(byte[] data, int imageWidth, int imageHeight, int numChannels, int resizeWidth, int resizeHeight, TFDataType destinationDataType = TFDataType.Float) { var tensor = TFTensor.FromBuffer(new TFShape(imageHeight, imageWidth, numChannels), data, 0, imageWidth * imageHeight * numChannels); TFOutput input, output; // Construct a graph to normalize the image using (var graph = ConstructGraphToNormalizeRawImage(out input, out output, resizeWidth, resizeHeight, destinationDataType)) { // Execute that graph to normalize this one image using (var session = new TFSession(graph)) { var normalized = session.Run( inputs: new[] { input }, inputValues: new[] { tensor }, outputs: new[] { output }); return(normalized[0]); } } }
/// <summary> /// 基础占位符运算 /// </summary> public static void BasicPlaceholderOperation() { using (var s = new TFSession()) { var g = s.Graph; //占位符 - 一种不需要初始化,在运算时再提供值的对象 //1*2的占位符 var v1 = g.Placeholder(TFDataType.Double, new TFShape(2)); var v2 = g.Placeholder(TFDataType.Double, new TFShape(2)); //建立一个相乘的运算 var add = g.Mul(v1, v2); //获得runner var runner = s.GetRunner(); //相加 //在这里给占位符提供值 var data1 = new double[] { 0.3, 0.5 }; var data2 = new double[] { 0.4, 0.8 }; var result = runner .Fetch(add) .AddInput(v1, new TFTensor(data1)) .AddInput(v2, new TFTensor(data2)) .Run(); var dataResult = (double[])result[0].GetValue(); //获得result的值 Console.WriteLine($"相乘的结果: [{dataResult[0]}, {dataResult[1]}]"); // 相乘的结果: [0.12, 0.4] } }
public static void TestMethod2() { string model_file = $@"E:\PythonSrc\Py.Watermelon\Tensorflow\grf.pb"; var graph = new TFGraph(); // 重点是下面的这句,把训练好的pb文件给读出来字节,然后导入 var model = File.ReadAllBytes(model_file); graph.Import(model); Console.WriteLine("请输入一个图片的地址"); var src = Console.ReadLine(); var tensor = ImageUtil.CreateTensorFromImageFile(src); using (var sess = new TFSession(graph)) { var runner = sess.GetRunner(); runner.AddInput(graph["Cast_1"][0], tensor); var r = runner.Run(graph.Softmax(graph["softmax_linear/softmax_linear"][0])); var v = (float[, ])r.GetValue(); Console.WriteLine(v[0, 0]); Console.WriteLine(v[0, 1]); } }