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.

TensorTest.cs 12 kB

Performance optimization, refactoring and revamping. (#362) * Refactored DisposableObject * Added different build directory for TensorflowNET.Examples.GPU * _FetchHandler: Switched to NPTypeCode * gfile.cs, Walk(...): Handle case when directory top doesn't exist. * Tensor.Creation: Perf-opted when creating tensor from NDArray of string * Graph.cs: refactor and added docs * Tensor.Creation.cs: perf-ops * Tensor.Explicit.cs: perf-ops * Copied globals.regen from NumSharp - Added supported_numericals_TF_DataType * Tensor perf-ops and cleanup, Revamped dtypes.cs, some renames. - Cleanup and docs to all Tensor.cs files - Changed all uses of System.Convert to NumSharp.Utilities.Converts - Added all missing types in dtypes.cs - Renamed tensor.Data<T> to tensor.ToArray<T>, added obsolete message - Renamed tensor.Data() to tensor.BufferToArray(), added obsolete message - Made GraphKeys to use const string instead allocating strings at every use of GraphKeys. * Tensor: Added guards for explicit casts. * Tensor: Added explicit cast to string * Tensor.ToArray<T>(): Added support for cases when tensor is scalar. * Tensor.BufferToArray(): Fixed to use long instead of int. * TensorShape: Revamped and documented. * BaseSession: Added Session.run(ITensorOrOperation fetche, params FeedItem[] feed_dict) * Tensor: renamed _dtype to _override_dtype - Fixed all locations _dtype is used incorrectly. * Fixed unit tests * Tensor.Operations: Reverted commit * DisposableObject: sorted internal_dispose to properly handle Dispose() calls * Tensor.DisposeUnmanagedResources: Nullify _handle after delete. * TensorShape.this[...]: fixed guard check. * DisposableObject #362
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. using FluentAssertions;
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;
  3. using NumSharp;
  4. using System;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using Tensorflow;
  8. using static Tensorflow.Binding;
  9. namespace TensorFlowNET.UnitTest.NativeAPI
  10. {
  11. [TestClass]
  12. public class TensorTest : CApiTest
  13. {
  14. [TestMethod]
  15. public unsafe void TensorFromFixed()
  16. {
  17. var array = new float[1000];
  18. var span = new Span<float>(array, 100, 500);
  19. fixed (float* ptr = &MemoryMarshal.GetReference(span))
  20. {
  21. using (var t = new Tensor((IntPtr)ptr, new long[] { span.Length }, tf.float32, 4 * span.Length))
  22. {
  23. Assert.IsFalse(t.IsDisposed);
  24. Assert.AreEqual(2000, (int)t.bytesize);
  25. }
  26. }
  27. fixed (float* ptr = &array[0])
  28. {
  29. using (var t = new Tensor((IntPtr)ptr, new long[] { array.Length }, tf.float32, 4 * array.Length))
  30. {
  31. Assert.IsFalse(t.IsDisposed);
  32. Assert.AreEqual(4000, (int)t.bytesize);
  33. }
  34. }
  35. }
  36. [TestMethod]
  37. public unsafe void TensorFromArray()
  38. {
  39. var array = new float[1000];
  40. using (var t = new Tensor(array, new long[] { array.Length }, tf.float32))
  41. {
  42. Assert.IsFalse(t.IsDisposed);
  43. Assert.AreEqual(1000 * sizeof(float), (int)t.bytesize);
  44. }
  45. using (var t = new Tensor(new float[] { 1 }, new long[] { 1 }, tf.float32))
  46. {
  47. Assert.IsFalse(t.IsDisposed);
  48. Assert.AreEqual(1 * sizeof(float), (int)t.bytesize);
  49. }
  50. using (var t = new Tensor(new float[] { 1 }, null, tf.float32))
  51. {
  52. Assert.IsFalse(t.IsDisposed);
  53. Assert.AreEqual(1 * sizeof(float), (int)t.bytesize);
  54. t.shape.Should().BeEmpty();
  55. }
  56. }
  57. [TestMethod]
  58. public void AllocateTensor()
  59. {
  60. ulong num_bytes = 6 * sizeof(float);
  61. long[] dims = { 2, 3 };
  62. Tensor t = c_api.TF_AllocateTensor(TF_DataType.TF_FLOAT, dims, 2, num_bytes);
  63. EXPECT_EQ(TF_DataType.TF_FLOAT, t.dtype);
  64. EXPECT_EQ(2, t.NDims);
  65. EXPECT_EQ((int)dims[0], t.shape[0]);
  66. EXPECT_EQ(num_bytes, t.bytesize);
  67. t.Dispose();
  68. }
  69. /// <summary>
  70. /// Port from c_api_test.cc
  71. /// `TEST(CAPI, MaybeMove)`
  72. /// </summary>
  73. [TestMethod, Ignore]
  74. public void MaybeMove()
  75. {
  76. NDArray nd = np.array(2, 3);
  77. Tensor t = new Tensor(nd);
  78. Tensor o = t.MaybeMove();
  79. ASSERT_TRUE(o == IntPtr.Zero); // It is unsafe to move memory TF might not own.
  80. t.Dispose();
  81. }
  82. /// <summary>
  83. /// Port from c_api_test.cc
  84. /// `TEST(CAPI, Tensor)`
  85. /// </summary>
  86. [TestMethod]
  87. public void Tensor()
  88. {
  89. var nd = np.array(1f, 2f, 3f, 4f, 5f, 6f).reshape(2, 3);
  90. var tensor = new Tensor(nd);
  91. var array = tensor.ToArray<float>();
  92. EXPECT_EQ(tensor.dtype, TF_DataType.TF_FLOAT);
  93. EXPECT_EQ(tensor.rank, nd.ndim);
  94. EXPECT_EQ((int)tensor.shape[0], nd.shape[0]);
  95. EXPECT_EQ((int)tensor.shape[1], nd.shape[1]);
  96. EXPECT_EQ(tensor.bytesize, (ulong)nd.size * sizeof(float));
  97. Assert.IsTrue(Enumerable.SequenceEqual(nd.Data<float>(), new float[] { 1, 2, 3, 4, 5, 6 }));
  98. }
  99. /// <summary>
  100. /// Port from tensorflow\c\c_api_test.cc
  101. /// `TEST(CAPI, SetShape)`
  102. /// </summary>
  103. [TestMethod]
  104. public void SetShape()
  105. {
  106. var s = new Status();
  107. var graph = new Graph().as_default();
  108. var feed = c_test_util.Placeholder(graph, s);
  109. var feed_out_0 = new TF_Output(feed, 0);
  110. // Fetch the shape, it should be completely unknown.
  111. int num_dims = c_api.TF_GraphGetTensorNumDims(graph, feed_out_0, s.Handle);
  112. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  113. EXPECT_EQ(-1, num_dims);
  114. // Set the shape to be unknown, expect no change.
  115. c_api.TF_GraphSetTensorShape(graph, feed_out_0, null, -1, s.Handle);
  116. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  117. num_dims = c_api.TF_GraphGetTensorNumDims(graph, feed_out_0, s.Handle);
  118. EXPECT_EQ(-1, num_dims);
  119. // Set the shape to be 2 x Unknown
  120. long[] dims = { 2, -1 };
  121. c_api.TF_GraphSetTensorShape(graph, feed_out_0, dims, dims.Length, s.Handle);
  122. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  123. num_dims = c_api.TF_GraphGetTensorNumDims(graph, feed_out_0, s.Handle);
  124. EXPECT_EQ(2, num_dims);
  125. // Get the dimension vector appropriately.
  126. var returned_dims = new long[dims.Length];
  127. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, num_dims, s.Handle);
  128. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  129. Assert.IsTrue(Enumerable.SequenceEqual(dims, returned_dims));
  130. // Set to a new valid shape: [2, 3]
  131. dims[1] = 3;
  132. c_api.TF_GraphSetTensorShape(graph, feed_out_0, dims, dims.Length, s.Handle);
  133. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  134. // Fetch and see that the new value is returned.
  135. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, num_dims, s.Handle);
  136. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  137. Assert.IsTrue(Enumerable.SequenceEqual(dims, returned_dims));
  138. // Try to set 'unknown' with unknown rank on the shape and see that
  139. // it doesn't change.
  140. c_api.TF_GraphSetTensorShape(graph, feed_out_0, null, -1, s.Handle);
  141. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  142. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, num_dims, s.Handle);
  143. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  144. EXPECT_EQ(2, num_dims);
  145. EXPECT_EQ(2, (int)returned_dims[0]);
  146. EXPECT_EQ(3, (int)returned_dims[1]);
  147. // Try to set 'unknown' with same rank on the shape and see that
  148. // it doesn't change.
  149. dims[0] = -1;
  150. dims[1] = -1;
  151. c_api.TF_GraphSetTensorShape(graph, feed_out_0, dims, 2, s.Handle);
  152. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  153. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, num_dims, s.Handle);
  154. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  155. EXPECT_EQ(2, num_dims);
  156. EXPECT_EQ(2, (int)returned_dims[0]);
  157. EXPECT_EQ(3, (int)returned_dims[1]);
  158. // Try to fetch a shape with the wrong num_dims
  159. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, 5, s.Handle);
  160. Assert.IsTrue(s.Code == TF_Code.TF_INVALID_ARGUMENT);
  161. // Try to set an invalid shape (cannot change 2x3 to a 2x5).
  162. dims[1] = 5;
  163. c_api.TF_GraphSetTensorShape(graph, feed_out_0, dims, 2, s.Handle);
  164. Assert.IsTrue(s.Code == TF_Code.TF_INVALID_ARGUMENT);
  165. // Test for a scalar.
  166. var three = c_test_util.ScalarConst(3, graph, s);
  167. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  168. var three_out_0 = new TF_Output(three, 0);
  169. num_dims = c_api.TF_GraphGetTensorNumDims(graph, three_out_0, s.Handle);
  170. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  171. EXPECT_EQ(0, num_dims);
  172. c_api.TF_GraphGetTensorShape(graph, feed_out_0, null, num_dims, s.Handle);
  173. //Assert.IsTrue(s.Code == TF_Code.TF_OK);
  174. // graph.Dispose();
  175. s.Dispose();
  176. }
  177. [TestMethod]
  178. public void sparse_to_dense()
  179. {
  180. var indices = tf.reshape(tf.range(0, 5), new int[] { 5, 1 });
  181. var labels = tf.expand_dims(tf.constant(new[] { 0, 1, 2, 3, 4 }), 1);
  182. var st = tf.concat(values: new[] { indices, labels }, axis: 1);
  183. var onehot = tf.sparse_to_dense(st, (5, 5), 1);
  184. using (var sess = tf.Session())
  185. {
  186. var result = sess.run(onehot);
  187. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 1, 0, 0, 0, 0 }, result[0].ToArray<int>()));
  188. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 1, 0, 0, 0 }, result[1].ToArray<int>()));
  189. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 1, 0, 0 }, result[2].ToArray<int>()));
  190. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 0, 1, 0 }, result[3].ToArray<int>()));
  191. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 0, 0, 1 }, result[4].ToArray<int>()));
  192. };
  193. }
  194. [TestMethod]
  195. public void sparse_tensor_to_dense()
  196. {
  197. var decoded_list = tf.SparseTensor(new[,]
  198. {
  199. { 0L, 0L },
  200. { 1L, 2L }
  201. },
  202. new int[] { 1, 2 },
  203. new[] { 3L, 4L });
  204. var onehot = tf.sparse_tensor_to_dense(decoded_list);
  205. using (var sess = tf.Session())
  206. {
  207. var result = sess.run(onehot);
  208. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 1, 0, 0, 0 }, result[0].ToArray<int>()));
  209. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 2, 0 }, result[1].ToArray<int>()));
  210. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 0, 0 }, result[2].ToArray<int>()));
  211. }
  212. }
  213. [TestMethod]
  214. public void batch_to_space_nd()
  215. {
  216. var inputs = np.arange(24).reshape(4, 2, 3);
  217. var block_shape = new[] { 2, 2 };
  218. int[,] crops = { { 0, 0 }, { 0, 0 } };
  219. var tensor = tf.batch_to_space_nd(inputs, block_shape, crops);
  220. using (var sess = tf.Session())
  221. {
  222. var result = sess.run(tensor);
  223. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 6, 1, 7, 2, 8 }, result[0, 0].ToArray<int>()));
  224. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 12, 18, 13, 19, 14, 20 }, result[0, 1].ToArray<int>()));
  225. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 3, 9, 4, 10, 5, 11 }, result[0, 2].ToArray<int>()));
  226. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 15, 21, 16, 22, 17, 23 }, result[0, 3].ToArray<int>()));
  227. }
  228. }
  229. [TestMethod, Ignore]
  230. public void boolean_mask()
  231. {
  232. var tensor = new[] { 0, 1, 2, 3 };
  233. var mask = np.array(new[] { true, false, true, false });
  234. var masked = tf.boolean_mask(tensor, mask);
  235. using (var sess = tf.Session())
  236. {
  237. var result = sess.run(masked);
  238. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 2 }, masked.ToArray<int>()));
  239. }
  240. }
  241. /// <summary>
  242. /// Creates a tensor from an image of 256x256x3 and resizes it to 100x100x3
  243. /// </summary>
  244. [TestMethod]
  245. public unsafe void tensor_resize()
  246. {
  247. tf.enable_eager_execution();
  248. var imageArray = new float[256 * 256 * 3];
  249. using var newSize = tf.convert_to_tensor(new int[] { 100, 100 });
  250. using (var t = tf.constant(imageArray, tf.float32, (1, 256, 256, 3)))
  251. {
  252. Assert.IsFalse(t.IsDisposed);
  253. Assert.AreEqual(256 * 256 * 3 * sizeof(float), (int)t.bytesize);
  254. using var resized = tf.image.resize_bilinear(t, newSize);
  255. EXPECT_EQ(resized.shape[0], 1);
  256. EXPECT_EQ(resized.shape[1], 100);
  257. EXPECT_EQ(resized.shape[2], 100);
  258. EXPECT_EQ(resized.shape[3], 3);
  259. }
  260. tf.compat.v1.disable_eager_execution();
  261. }
  262. }
  263. }