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

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