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.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 WriteGraph()
  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", "train.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", "train.pbtxt");
  24. }
  25. [TestMethod]
  26. public void SaveSimple()
  27. {
  28. var w1 = tf.Variable(tf.random_normal(new int[] { 2 }), name: "w1");
  29. var w2 = tf.Variable(tf.random_normal(new int[] { 5 }), name: "w2");
  30. var init_op = tf.global_variables_initializer();
  31. // Add ops to save and restore all the variables.
  32. var saver = tf.train.Saver();
  33. with<Session>(tf.Session(), sess =>
  34. {
  35. sess.run(init_op);
  36. // Save the variables to disk.
  37. var save_path = saver.save(sess, "/tmp/model.ckpt");
  38. Console.WriteLine($"Model saved in path: {save_path}");
  39. });
  40. }
  41. [TestMethod]
  42. public void Save()
  43. {
  44. var v1 = tf.get_variable("v1", shape: new TensorShape(3), initializer: tf.zeros_initializer);
  45. var v2 = tf.get_variable("v2", shape: new TensorShape(5), initializer: tf.zeros_initializer);
  46. var inc_v1 = v1.assign(v1 + 1.0f);
  47. var dec_v2 = v2.assign(v2 - 1.0f);
  48. // Add an op to initialize the variables.
  49. var init_op = tf.global_variables_initializer();
  50. // Add ops to save and restore all the variables.
  51. var saver = tf.train.Saver();
  52. with<Session>(tf.Session(), sess =>
  53. {
  54. sess.run(init_op);
  55. // o some work with the model.
  56. inc_v1.op.run();
  57. dec_v2.op.run();
  58. // Save the variables to disk.
  59. var save_path = saver.save(sess, "/tmp/model.ckpt");
  60. Console.WriteLine($"Model saved in path: {save_path}");
  61. });
  62. }
  63. }
  64. }

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