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