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

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