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.

Tensor.md 1.9 kB

6 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Chapter 1. Tensor
  2. ### Represents one of the outputs of an Operation
  3. ##### What is Tensor?
  4. Tensor holds a multi-dimensional array of elements of a single data type which is very similar with `NumPy`'s `ndarray`. When the dimension is zero, it can be called a scalar. When the dimension is 2, it can be called a matrix. When the dimension is greater than 2, it is usually called a tensor. If you are very familiar with `NumPy`, then understanding Tensor will be quite easy.
  5. <img src="_static\tensor-naming.png">
  6. ##### How to create a Tensor?
  7. There are many ways to initialize a Tensor object in TF.NET. It can be initialized from a scalar, string, matrix or tensor. But the best way to create a Tensor is using high level APIs like `tf.constant`, `tf.zeros` and `tf.ones`. We'll talk about constant more detail in next chapter.
  8. ```csharp
  9. // Create a tensor holds a scalar value
  10. var t1 = new Tensor(3);
  11. // Init from a string
  12. var t2 = new Tensor("Hello! TensorFlow.NET");
  13. // Tensor holds a ndarray
  14. var nd = new NDArray(new int[]{3, 1, 1, 2});
  15. var t3 = new Tensor(nd);
  16. Console.WriteLine($"t1: {t1}, t2: {t2}, t3: {t3}");
  17. ```
  18. ##### Data Structure of Tensor
  19. TF uses column major order. If we use NumSharp to generate a 2 x 3 matrix, if we access the data from 0 to 5 in order, we won't get a number of 1-6, but we get the order of 1, 4, 2, 5, 3, 6. a set of numbers.
  20. ```csharp
  21. // Generate a matrix:[[1, 2, 3], [4, 5, 6]]
  22. var nd = np.array(1f, 2f, 3f, 4f, 5f, 6f).reshape(2, 3);
  23. // The index will be 0 2 4 1 3 5, it's column-major order.
  24. ```
  25. ![column-major order](_static/column-major-order.png)
  26. ![row-major order](_static/row-major-order.png)
  27. ##### Index/ Slice of Tensor
  28. Tensor element can be accessed by `index` and `slice` related operations. Through some high level APIs, we can easily access specific dimension's data.