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.

TrainSaverTest.cs 2.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using Tensorflow;
  6. namespace TensorFlowNET.UnitTest
  7. {
  8. [TestClass]
  9. public class TrainSaverTest : Python
  10. {
  11. [TestMethod]
  12. public void ExportGraph()
  13. {
  14. var v = tf.Variable(0, name: "my_variable");
  15. var sess = tf.Session();
  16. tf.train.write_graph(sess.graph, "/tmp/my-model", "train1.pbtxt");
  17. }
  18. [TestMethod]
  19. public void ImportGraph()
  20. {
  21. var v = tf.Variable(0, name: "my_variable");
  22. var sess = tf.Session();
  23. tf.train.write_graph(sess.graph, "/tmp/my-model", "train2.pbtxt");
  24. }
  25. [TestMethod]
  26. public void Save1()
  27. {
  28. var w1 = tf.Variable(0, name: "save1");
  29. var init_op = tf.global_variables_initializer();
  30. // Add ops to save and restore all the variables.
  31. var saver = tf.train.Saver();
  32. with<Session>(tf.Session(), sess =>
  33. {
  34. sess.run(init_op);
  35. // Save the variables to disk.
  36. var save_path = saver.save(sess, "/tmp/model1.ckpt");
  37. Console.WriteLine($"Model saved in path: {save_path}");
  38. });
  39. }
  40. public void Save2()
  41. {
  42. var v1 = tf.get_variable("v1", shape: new TensorShape(3), initializer: tf.zeros_initializer);
  43. var v2 = tf.get_variable("v2", shape: new TensorShape(5), initializer: tf.zeros_initializer);
  44. var inc_v1 = v1.assign(v1 + 1.0f);
  45. var dec_v2 = v2.assign(v2 - 1.0f);
  46. // Add an op to initialize the variables.
  47. var init_op = tf.global_variables_initializer();
  48. // Add ops to save and restore all the variables.
  49. var saver = tf.train.Saver();
  50. with<Session>(tf.Session(), sess =>
  51. {
  52. sess.run(init_op);
  53. // o some work with the model.
  54. inc_v1.op.run();
  55. dec_v2.op.run();
  56. // Save the variables to disk.
  57. var save_path = saver.save(sess, "/tmp/model2.ckpt");
  58. Console.WriteLine($"Model saved in path: {save_path}");
  59. });
  60. }
  61. }
  62. }

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。