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.

PythonTest.cs 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;
  7. using Newtonsoft.Json.Linq;
  8. using NumSharp;
  9. using Tensorflow;
  10. using Tensorflow.Util;
  11. namespace TensorFlowNET.UnitTest
  12. {
  13. /// <summary>
  14. /// Use as base class for test classes to get additional assertions
  15. /// </summary>
  16. public class PythonTest : Python
  17. {
  18. #region python compatibility layer
  19. protected PythonTest self { get => this; }
  20. protected object None
  21. {
  22. get { return null; }
  23. }
  24. #endregion
  25. #region pytest assertions
  26. public void assertItemsEqual(ICollection given, ICollection expected)
  27. {
  28. if (given is Hashtable && expected is Hashtable)
  29. {
  30. Assert.AreEqual(JObject.FromObject(expected).ToString(), JObject.FromObject(given).ToString());
  31. return;
  32. }
  33. Assert.IsNotNull(expected);
  34. Assert.IsNotNull(given);
  35. var e = expected.OfType<object>().ToArray();
  36. var g = given.OfType<object>().ToArray();
  37. Assert.AreEqual(e.Length, g.Length, $"The collections differ in length expected {e.Length} but got {g.Length}");
  38. for (int i = 0; i < e.Length; i++)
  39. {
  40. if (g[i] is NDArray && e[i] is NDArray)
  41. assertItemsEqual((g[i] as NDArray).Array, (e[i] as NDArray).Array);
  42. else if (e[i] is ICollection && g[i] is ICollection)
  43. assertEqual(g[i], e[i]);
  44. else
  45. Assert.AreEqual(e[i], g[i], $"Items differ at index {i}, expected {e[i]} but got {g[i]}");
  46. }
  47. }
  48. public void assertAllEqual(ICollection given, ICollection expected)
  49. {
  50. assertItemsEqual(given, expected);
  51. }
  52. public void assertEqual(object given, object expected)
  53. {
  54. if (given is NDArray && expected is NDArray)
  55. {
  56. assertItemsEqual((given as NDArray).Array, (expected as NDArray).Array);
  57. return;
  58. }
  59. if (given is Hashtable && expected is Hashtable)
  60. {
  61. Assert.AreEqual(JObject.FromObject(expected).ToString(), JObject.FromObject(given).ToString());
  62. return;
  63. }
  64. if (given is ICollection && expected is ICollection)
  65. {
  66. assertItemsEqual(given as ICollection, expected as ICollection);
  67. return;
  68. }
  69. Assert.AreEqual(expected, given);
  70. }
  71. public void assertEquals(object given, object expected)
  72. {
  73. assertEqual(given, expected);
  74. }
  75. public void assertIsNotNone(object given)
  76. {
  77. Assert.IsNotNull(given);
  78. }
  79. public void assertFalse(bool cond)
  80. {
  81. Assert.IsFalse(cond);
  82. }
  83. public void assertTrue(bool cond)
  84. {
  85. Assert.IsTrue(cond);
  86. }
  87. #endregion
  88. #region tensor evaluation
  89. protected object _eval_helper(Tensor[] tensors)
  90. {
  91. if (tensors == null)
  92. return null;
  93. return nest.map_structure(self._eval_tensor, tensors);
  94. return null;
  95. }
  96. protected object _eval_tensor(object tensor)
  97. {
  98. if (tensor == None)
  99. return None;
  100. //else if (callable(tensor))
  101. // return self._eval_helper(tensor())
  102. else
  103. {
  104. try
  105. {
  106. //TODO:
  107. // if sparse_tensor.is_sparse(tensor):
  108. // return sparse_tensor.SparseTensorValue(tensor.indices, tensor.values,
  109. // tensor.dense_shape)
  110. //return (tensor as Tensor).numpy();
  111. }
  112. catch (Exception e)
  113. {
  114. throw new ValueError("Unsupported type: " + tensor.GetType());
  115. }
  116. return null;
  117. }
  118. }
  119. /// <summary>
  120. /// Evaluates tensors and returns a dictionary of {name:result, ...}.
  121. /// <param name="tensors">A Tensor or a nested list/tuple of Tensors.</param>
  122. /// </summary>
  123. public Dictionary<string, NDArray> evaluate(params Tensor[] tensors)
  124. {
  125. var results = new Dictionary<string, NDArray>();
  126. // if context.executing_eagerly():
  127. // return self._eval_helper(tensors)
  128. // else:
  129. {
  130. var sess = ops.get_default_session();
  131. if (sess == null)
  132. sess = self.session();
  133. with<Session>(sess, s =>
  134. {
  135. foreach (var t in tensors)
  136. results[t.name] = t.eval();
  137. });
  138. return results;
  139. }
  140. }
  141. public NDArray evaluate(Tensor tensor)
  142. {
  143. NDArray result = null;
  144. // if context.executing_eagerly():
  145. // return self._eval_helper(tensors)
  146. // else:
  147. {
  148. var sess = ops.get_default_session();
  149. if (sess == null)
  150. sess = self.session();
  151. with<Session>(sess, s =>
  152. {
  153. result = tensor.eval();
  154. });
  155. return result;
  156. }
  157. }
  158. public object eval_scalar(Tensor tensor)
  159. {
  160. NDArray result = null;
  161. // if context.executing_eagerly():
  162. // return self._eval_helper(tensors)
  163. // else:
  164. {
  165. var sess = ops.get_default_session();
  166. if (sess == null)
  167. sess = self.session();
  168. with<Session>(sess, s =>
  169. {
  170. result = tensor.eval();
  171. });
  172. return result.Array.GetValue(0);
  173. }
  174. }
  175. //Returns a TensorFlow Session for use in executing tests.
  176. public Session session(Graph graph = null, object config = null, bool use_gpu = false, bool force_gpu = false)
  177. {
  178. //Note that this will set this session and the graph as global defaults.
  179. //Use the `use_gpu` and `force_gpu` options to control where ops are run.If
  180. //`force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if
  181. //`use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
  182. //possible.If both `force_gpu and `use_gpu` are False, all ops are pinned to
  183. //the CPU.
  184. //Example:
  185. //```python
  186. //class MyOperatorTest(test_util.TensorFlowTestCase):
  187. // def testMyOperator(self):
  188. // with self.session(use_gpu= True):
  189. // valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
  190. // result = MyOperator(valid_input).eval()
  191. // self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
  192. // invalid_input = [-1.0, 2.0, 7.0]
  193. // with self.assertRaisesOpError("negative input not supported"):
  194. // MyOperator(invalid_input).eval()
  195. //```
  196. //Args:
  197. // graph: Optional graph to use during the returned session.
  198. // config: An optional config_pb2.ConfigProto to use to configure the
  199. // session.
  200. // use_gpu: If True, attempt to run as many ops as possible on GPU.
  201. // force_gpu: If True, pin all ops to `/device:GPU:0`.
  202. //Yields:
  203. // A Session object that should be used as a context manager to surround
  204. // the graph building and execution code in a test case.
  205. Session s = null;
  206. //if (context.executing_eagerly())
  207. // yield None
  208. //else
  209. //{
  210. s = self._create_session(graph, config, force_gpu);
  211. self._constrain_devices_and_set_default(s, use_gpu, force_gpu);
  212. //}
  213. return s.as_default();
  214. }
  215. private IPython _constrain_devices_and_set_default(Session sess, bool useGpu, bool forceGpu)
  216. {
  217. //def _constrain_devices_and_set_default(self, sess, use_gpu, force_gpu):
  218. //"""Set the session and its graph to global default and constrain devices."""
  219. //if context.executing_eagerly():
  220. // yield None
  221. //else:
  222. // with sess.graph.as_default(), sess.as_default():
  223. // if force_gpu:
  224. // # Use the name of an actual device if one is detected, or
  225. // # '/device:GPU:0' otherwise
  226. // gpu_name = gpu_device_name()
  227. // if not gpu_name:
  228. // gpu_name = "/device:GPU:0"
  229. // with sess.graph.device(gpu_name):
  230. // yield sess
  231. // elif use_gpu:
  232. // yield sess
  233. // else:
  234. // with sess.graph.device("/device:CPU:0"):
  235. // yield sess
  236. return sess;
  237. }
  238. // See session() for details.
  239. private Session _create_session(Graph graph, object cfg, bool forceGpu)
  240. {
  241. var prepare_config = new Func<object, object>((config) =>
  242. {
  243. // """Returns a config for sessions.
  244. // Args:
  245. // config: An optional config_pb2.ConfigProto to use to configure the
  246. // session.
  247. // Returns:
  248. // A config_pb2.ConfigProto object.
  249. //TODO: config
  250. // # use_gpu=False. Currently many tests rely on the fact that any device
  251. // # will be used even when a specific device is supposed to be used.
  252. // allow_soft_placement = not force_gpu
  253. // if config is None:
  254. // config = config_pb2.ConfigProto()
  255. // config.allow_soft_placement = allow_soft_placement
  256. // config.gpu_options.per_process_gpu_memory_fraction = 0.3
  257. // elif not allow_soft_placement and config.allow_soft_placement:
  258. // config_copy = config_pb2.ConfigProto()
  259. // config_copy.CopyFrom(config)
  260. // config = config_copy
  261. // config.allow_soft_placement = False
  262. // # Don't perform optimizations for tests so we don't inadvertently run
  263. // # gpu ops on cpu
  264. // config.graph_options.optimizer_options.opt_level = -1
  265. // # Disable Grappler constant folding since some tests & benchmarks
  266. // # use constant input and become meaningless after constant folding.
  267. // # DO NOT DISABLE GRAPPLER OPTIMIZERS WITHOUT CONSULTING WITH THE
  268. // # GRAPPLER TEAM.
  269. // config.graph_options.rewrite_options.constant_folding = (
  270. // rewriter_config_pb2.RewriterConfig.OFF)
  271. // config.graph_options.rewrite_options.pin_to_host_optimization = (
  272. // rewriter_config_pb2.RewriterConfig.OFF)
  273. return config;
  274. });
  275. //TODO: use this instead of normal session
  276. //return new ErrorLoggingSession(graph = graph, config = prepare_config(config))
  277. return new Session(graph: graph);//, config = prepare_config(config))
  278. }
  279. #endregion
  280. }
  281. }

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