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