You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Session.cs 2.5 kB

6 years ago
6 years ago
6 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Tensorflow
  5. {
  6. public class Session : BaseSession, IPython
  7. {
  8. private IntPtr _handle;
  9. public Status Status = new Status();
  10. public SessionOptions Options { get; }
  11. public Graph graph;
  12. public Session(string target = "", Graph graph = null):base(target,graph,null)
  13. {
  14. if(graph == null)
  15. {
  16. graph = tf.get_default_graph();
  17. }
  18. this.graph = graph;
  19. Options = new SessionOptions();
  20. _handle = c_api.TF_NewSession(graph, Options, Status);
  21. //why create session again. already created session in BaseSession.
  22. Status.Check();
  23. }
  24. public Session(IntPtr handle):base("",null,null)
  25. {
  26. _handle = handle;
  27. }
  28. public Session(Graph g, SessionOptions opts = null, Status s = null)
  29. :base(string.Empty,g,opts)
  30. {
  31. s = s ?? Status;
  32. graph = g;
  33. Options = opts ?? new SessionOptions();
  34. _handle = c_api.TF_NewSession(graph, Options, s);
  35. Status.Check(true);
  36. }
  37. public Session as_default()
  38. {
  39. tf.defaultSession = this;
  40. return this;
  41. }
  42. public static Session LoadFromSavedModel(string path)
  43. {
  44. var graph = c_api.TF_NewGraph();
  45. var status = new Status();
  46. var opt = c_api.TF_NewSessionOptions();
  47. var buffer = new TF_Buffer();
  48. var sess = c_api.TF_LoadSessionFromSavedModel(opt, IntPtr.Zero, path, new string[0], 0, graph, ref buffer, status);
  49. //var bytes = new Buffer(buffer.data).Data;
  50. //var meta_graph = MetaGraphDef.Parser.ParseFrom(bytes);
  51. status.Check();
  52. new Graph(graph).as_default();
  53. return sess;
  54. }
  55. public static implicit operator IntPtr(Session session) => session._handle;
  56. public static implicit operator Session(IntPtr handle) => new Session(handle);
  57. public void close()
  58. {
  59. Dispose();
  60. }
  61. public void Dispose()
  62. {
  63. Options.Dispose();
  64. c_api.TF_DeleteSession(_handle, Status);
  65. Status.Dispose();
  66. }
  67. public void __enter__()
  68. {
  69. }
  70. public void __exit__()
  71. {
  72. }
  73. }
  74. }