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 13 kB

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