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 11 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using NumSharp;
  3. using System;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. using FluentAssertions;
  8. using Tensorflow;
  9. using static Tensorflow.Binding;
  10. using Tensorflow.Framework;
  11. namespace TensorFlowNET.UnitTest.NativeAPI
  12. {
  13. [Ignore]
  14. [TestClass]
  15. public class TensorTest : CApiTest
  16. {
  17. [TestMethod]
  18. public unsafe void TensorFromFixed()
  19. {
  20. var array = new float[1000];
  21. var span = new Span<float>(array, 100, 500);
  22. fixed (float* ptr = &MemoryMarshal.GetReference(span))
  23. {
  24. using (var t = new Tensor((IntPtr) ptr, new long[] {span.Length}, tf.float32, 4 * span.Length))
  25. {
  26. Assert.IsFalse(t.IsDisposed);
  27. Assert.AreEqual(2000, (int) t.bytesize);
  28. }
  29. }
  30. fixed (float* ptr = &array[0])
  31. {
  32. using (var t = new Tensor((IntPtr) ptr, new long[] {array.Length}, tf.float32, 4 * array.Length))
  33. {
  34. Assert.IsFalse(t.IsDisposed);
  35. Assert.AreEqual(4000, (int) t.bytesize);
  36. }
  37. }
  38. }
  39. [TestMethod]
  40. public unsafe void TensorFromArray()
  41. {
  42. var array = new float[1000];
  43. using (var t = new Tensor(array, new long[] {array.Length}, tf.float32))
  44. {
  45. Assert.IsFalse(t.IsDisposed);
  46. Assert.AreEqual(1000 * sizeof(float), (int) t.bytesize);
  47. }
  48. using (var t = new Tensor(new float[] {1}, new long[] {1}, tf.float32))
  49. {
  50. Assert.IsFalse(t.IsDisposed);
  51. Assert.AreEqual(1 * sizeof(float), (int) t.bytesize);
  52. }
  53. using (var t = new Tensor(new float[] {1}, null, tf.float32))
  54. {
  55. Assert.IsFalse(t.IsDisposed);
  56. Assert.AreEqual(1 * sizeof(float), (int) t.bytesize);
  57. t.shape.Should().BeEmpty();
  58. }
  59. }
  60. [TestMethod]
  61. public void AllocateTensor()
  62. {
  63. ulong num_bytes = 6 * sizeof(float);
  64. long[] dims = {2, 3};
  65. Tensor t = c_api.TF_AllocateTensor(TF_DataType.TF_FLOAT, dims, 2, num_bytes);
  66. EXPECT_EQ(TF_DataType.TF_FLOAT, t.dtype);
  67. EXPECT_EQ(2, t.NDims);
  68. EXPECT_EQ((int) dims[0], t.shape[0]);
  69. EXPECT_EQ(num_bytes, t.bytesize);
  70. t.Dispose();
  71. }
  72. /// <summary>
  73. /// Port from c_api_test.cc
  74. /// `TEST(CAPI, MaybeMove)`
  75. /// </summary>
  76. [TestMethod]
  77. public void MaybeMove()
  78. {
  79. NDArray nd = np.array(2, 3);
  80. Tensor t = new Tensor(nd);
  81. Tensor o = t.MaybeMove();
  82. ASSERT_TRUE(o == IntPtr.Zero); // It is unsafe to move memory TF might not own.
  83. t.Dispose();
  84. }
  85. /// <summary>
  86. /// Port from c_api_test.cc
  87. /// `TEST(CAPI, Tensor)`
  88. /// </summary>
  89. [TestMethod]
  90. public void Tensor()
  91. {
  92. var nd = np.array(1f, 2f, 3f, 4f, 5f, 6f).reshape(2, 3);
  93. var tensor = new Tensor(nd);
  94. var array = tensor.ToArray<float>();
  95. EXPECT_EQ(tensor.dtype, TF_DataType.TF_FLOAT);
  96. EXPECT_EQ(tensor.rank, nd.ndim);
  97. EXPECT_EQ((int) tensor.shape[0], nd.shape[0]);
  98. EXPECT_EQ((int) tensor.shape[1], nd.shape[1]);
  99. EXPECT_EQ(tensor.bytesize, (ulong) nd.size * sizeof(float));
  100. Assert.IsTrue(Enumerable.SequenceEqual(nd.Data<float>(), new float[] {1, 2, 3, 4, 5, 6}));
  101. }
  102. /// <summary>
  103. /// Port from tensorflow\c\c_api_test.cc
  104. /// `TEST(CAPI, SetShape)`
  105. /// </summary>
  106. [TestMethod]
  107. public void SetShape()
  108. {
  109. var s = new Status();
  110. var graph = new Graph().as_default();
  111. var feed = c_test_util.Placeholder(graph, s);
  112. var feed_out_0 = new TF_Output(feed, 0);
  113. // Fetch the shape, it should be completely unknown.
  114. int num_dims = c_api.TF_GraphGetTensorNumDims(graph, feed_out_0, s);
  115. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  116. EXPECT_EQ(-1, num_dims);
  117. // Set the shape to be unknown, expect no change.
  118. c_api.TF_GraphSetTensorShape(graph, feed_out_0, null, -1, s);
  119. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  120. num_dims = c_api.TF_GraphGetTensorNumDims(graph, feed_out_0, s);
  121. EXPECT_EQ(-1, num_dims);
  122. // Set the shape to be 2 x Unknown
  123. long[] dims = {2, -1};
  124. c_api.TF_GraphSetTensorShape(graph, feed_out_0, dims, dims.Length, s);
  125. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  126. num_dims = c_api.TF_GraphGetTensorNumDims(graph, feed_out_0, s);
  127. EXPECT_EQ(2, num_dims);
  128. // Get the dimension vector appropriately.
  129. var returned_dims = new long[dims.Length];
  130. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, num_dims, s);
  131. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  132. Assert.IsTrue(Enumerable.SequenceEqual(dims, returned_dims));
  133. // Set to a new valid shape: [2, 3]
  134. dims[1] = 3;
  135. c_api.TF_GraphSetTensorShape(graph, feed_out_0, dims, dims.Length, s);
  136. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  137. // Fetch and see that the new value is returned.
  138. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, num_dims, s);
  139. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  140. Assert.IsTrue(Enumerable.SequenceEqual(dims, returned_dims));
  141. // Try to set 'unknown' with unknown rank on the shape and see that
  142. // it doesn't change.
  143. c_api.TF_GraphSetTensorShape(graph, feed_out_0, null, -1, s);
  144. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  145. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, num_dims, s);
  146. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  147. EXPECT_EQ(2, num_dims);
  148. EXPECT_EQ(2, (int) returned_dims[0]);
  149. EXPECT_EQ(3, (int) returned_dims[1]);
  150. // Try to set 'unknown' with same rank on the shape and see that
  151. // it doesn't change.
  152. dims[0] = -1;
  153. dims[1] = -1;
  154. c_api.TF_GraphSetTensorShape(graph, feed_out_0, dims, 2, s);
  155. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  156. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, num_dims, s);
  157. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  158. EXPECT_EQ(2, num_dims);
  159. EXPECT_EQ(2, (int) returned_dims[0]);
  160. EXPECT_EQ(3, (int) returned_dims[1]);
  161. // Try to fetch a shape with the wrong num_dims
  162. c_api.TF_GraphGetTensorShape(graph, feed_out_0, returned_dims, 5, s);
  163. Assert.IsTrue(s.Code == TF_Code.TF_INVALID_ARGUMENT);
  164. // Try to set an invalid shape (cannot change 2x3 to a 2x5).
  165. dims[1] = 5;
  166. c_api.TF_GraphSetTensorShape(graph, feed_out_0, dims, 2, s);
  167. Assert.IsTrue(s.Code == TF_Code.TF_INVALID_ARGUMENT);
  168. // Test for a scalar.
  169. var three = c_test_util.ScalarConst(3, graph, s);
  170. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  171. var three_out_0 = new TF_Output(three, 0);
  172. num_dims = c_api.TF_GraphGetTensorNumDims(graph, three_out_0, s);
  173. Assert.IsTrue(s.Code == TF_Code.TF_OK);
  174. EXPECT_EQ(0, num_dims);
  175. c_api.TF_GraphGetTensorShape(graph, feed_out_0, null, num_dims, s);
  176. //Assert.IsTrue(s.Code == TF_Code.TF_OK);
  177. // graph.Dispose();
  178. s.Dispose();
  179. }
  180. [TestMethod]
  181. public void sparse_to_dense()
  182. {
  183. var indices = tf.reshape(tf.range(0, 5), new int[] { 5, 1 });
  184. var labels = tf.expand_dims(tf.constant(new[] { 0, 1, 2, 3, 4 }),1);
  185. var st = tf.concat(values: new[] { indices, labels }, axis: 1);
  186. var onehot = tf.sparse_to_dense(st, (5, 5), 1);
  187. using (var sess = tf.Session())
  188. {
  189. var result = sess.run(onehot);
  190. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 1, 0, 0, 0, 0 }, result[0].ToArray<int>()));
  191. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 1, 0, 0, 0 }, result[1].ToArray<int>()));
  192. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 1, 0, 0 }, result[2].ToArray<int>()));
  193. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 0, 1, 0 }, result[3].ToArray<int>()));
  194. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 0, 0, 1 }, result[4].ToArray<int>()));
  195. };
  196. }
  197. [TestMethod]
  198. public void sparse_tensor_to_dense()
  199. {
  200. var decoded_list = tf.SparseTensor(new[,]
  201. {
  202. { 0L, 0L },
  203. { 1L, 2L }
  204. },
  205. new int[] { 1, 2 },
  206. new[] { 3L, 4L });
  207. var onehot = tf.sparse_tensor_to_dense(decoded_list);
  208. using (var sess = tf.Session())
  209. {
  210. var result = sess.run(onehot);
  211. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 1, 0, 0, 0 }, result[0].ToArray<int>()));
  212. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 2, 0 }, result[1].ToArray<int>()));
  213. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 0, 0, 0 }, result[2].ToArray<int>()));
  214. }
  215. }
  216. [TestMethod]
  217. public void batch_to_space_nd()
  218. {
  219. var inputs = np.arange(24).reshape(4, 2, 3);
  220. var block_shape = new[] { 2, 2 };
  221. int[,] crops = { { 0, 0 }, { 0, 0 } };
  222. var tensor = tf.batch_to_space_nd(inputs, block_shape, crops);
  223. using (var sess = tf.Session())
  224. {
  225. var result = sess.run(tensor);
  226. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 6, 1, 7, 2, 8 }, result[0, 0].ToArray<int>()));
  227. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 12, 18, 13, 19, 14, 20 }, result[0, 1].ToArray<int>()));
  228. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 3, 9, 4, 10, 5, 11 }, result[0, 2].ToArray<int>()));
  229. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 15, 21, 16, 22, 17, 23 }, result[0, 3].ToArray<int>()));
  230. }
  231. }
  232. [TestMethod]
  233. public void boolean_mask()
  234. {
  235. var tensor = new[] { 0, 1, 2, 3 };
  236. var mask = np.array(new[] { true, false, true, false });
  237. var masked = tf.boolean_mask(tensor, mask);
  238. Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 0, 2 }, masked.ToArray<int>()));
  239. }
  240. }
  241. }