<jupyter_start><jupyter_text>Copyright 2020 The TensorFlow Authors.<jupyter_code>#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.<jupyter_output><empty_output><jupyter_text>Introduction to Tensors       View on TensorFlow.org        Run in Google Colab        View source on GitHub        Download notebook<jupyter_code>import tensorflow as tf
import numpy as np<jupyter_output><empty_output><jupyter_text>Tensors are multi-dimensional arrays with a uniform type (called a `dtype`).  You can see all supported `dtypes` at `tf.dtypes.DType`.If you're familiar with [NumPy](https://numpy.org/devdocs/user/quickstart.html), tensors are (kind of) like `np.arrays`.All tensors are immutable like Python numbers and strings: you can never update the contents of a tensor, only create a new one.  BasicsLet's create some basic tensors. Here is a "scalar" or "rank-0" tensor . A scalar contains a single value, and no "axes".<jupyter_code># This will be an int32 tensor by default; see "dtypes" below.
rank_0_t = tf.constant(10)

# this would be a float tensor since "10." is given as default value
# rank_0_t = tf.constant(10.)

print(rank_0_t)
print(rank_0_t.numpy())
print(type(rank_0_t.numpy()))

rank_0_t<jupyter_output>tf.Tensor(10, shape=(), dtype=int32)
10
<class 'numpy.int32'><jupyter_text>A "vector" or "rank-1" tensor is like a list of values. A vector has one axis:<jupyter_code># Let's make this a float tensor.
rank_1_t = tf.constant( [1.,2.,3.] )

print(rank_1_t)
print(rank_1_t.numpy())
print(type(rank_1_t.numpy()))
rank_1_t<jupyter_output>tf.Tensor([1. 2. 3.], shape=(3,), dtype=float32)
[1. 2. 3.]
<class 'numpy.ndarray'><jupyter_text>A "matrix" or "rank-2" tensor has two axes:<jupyter_code>rank_2_t =  tf.constant( [[1,2]
                        , [3,4]
                        , [5, 6]], dtype= tf.float16
                       )
print(rank_2_t)
print(rank_2_t.numpy())
print(type(rank_2_t.numpy()))
rank_2_t<jupyter_output>tf.Tensor(
[[1. 2.]
 [3. 4.]
 [5. 6.]], shape=(3, 2), dtype=float16)
[[1. 2.]
 [3. 4.]
 [5. 6.]]
<class 'numpy.ndarray'><jupyter_text>A scalar, shape: []  A vector, shape: [3]  A matrix, shape: [3, 2]                      Tensors may have more axes; here is a tensor with three axes:<jupyter_code># There can be an arbitrary number of
# axes (sometimes called "dimensions")
rank_3_tensor = tf.constant([
  [[0, 1, 2, 3, 4],
   [5, 6, 7, 8, 9]],
  [[10, 11, 12, 13, 14],
   [15, 16, 17, 18, 19]],
  [[20, 21, 22, 23, 24],
   [25, 26, 27, 28, 29]],])

print(rank_3_tensor)
# There can be an arbitrary number of
# axes (sometimes called "dimensions")
rank_3_t = tf.constant( 
    [
      [[1,2,3,4,5]
    , [6,7,8,9,10]
    , [26,27,28,29,30]
      ]
    ,
        [
        [11,12,13,14,15]
        , [16,17,18,19,20]
        , [36,37,38,39,40]
        ]
    ], dtype=tf.int32)
print(rank_3_t)
print(rank_3_t.numpy())
print(type(rank_3_t.numpy()))
rank_3_t<jupyter_output>tf.Tensor(
[[[ 1  2  3  4  5]
  [ 6  7  8  9 10]
  [26 27 28 29 30]]

 [[11 12 13 14 15]
  [16 17 18 19 20]
  [36 37 38 39 40]]], shape=(2, 3, 5), dtype=int32)
[[[ 1  2  3  4  5]
  [ 6  7  8  9 10]
  [26 27 28 29 30]]

 [[11 12 13 14 15]
  [16 17 18 19 20]
  [36 37 38 39 40]]]
<class 'numpy.ndarray'><jupyter_text>There are many ways you might visualize a tensor with more than two axes.   A 3-axis tensor, shape: [3, 2, 5]                      You can convert a tensor to a NumPy array either using `np.array` or the `tensor.numpy` method:<jupyter_code>np.array(rank_2_t)
rank_2_t.numpy()<jupyter_output><empty_output><jupyter_text>Tensors often contain floats and ints, but have many other types, including:* complex numbers* stringsThe base `tf.Tensor` class requires tensors to be "rectangular"---that is, along each axis, every element is the same size.  However, there are specialized types of tensors that can handle different shapes:* Ragged tensors (see [RaggedTensor](ragged_tensors) below)* Sparse tensors (see [SparseTensor](sparse_tensors) below) You can do basic math on tensors, including addition, element-wise multiplication, and matrix multiplication.<jupyter_code>a = tf.constant([[1, 2],
                 [3, 4]])
b = tf.constant([[10, 100],
                 [1000, 10000]]) # Could have also said `tf.ones([2,2])`

print(tf.add(a, b), "\n")
print(tf.multiply(a, b), "\n")
print(tf.matmul(a, b), "\n")
a = tf.constant([[1, 2],
                 [3, 4]])
b = tf.constant([[10, 100],
                 [1000, 10000]])
print(tf.add(a, b), "\n")
# element-wise multiplication
print(tf.multiply(a, b), "\n")
# matrix multiplication
print(tf.matmul(a, b), "\n")
print(a + b, "\n") # element-wise addition
print(a * b, "\n") # element-wise multiplication
print(a @ b, "\n") # matrix multiplication<jupyter_output>tf.Tensor(
[[   11   102]
 [ 1003 10004]], shape=(2, 2), dtype=int32) 

tf.Tensor(
[[   10   200]
 [ 3000 40000]], shape=(2, 2), dtype=int32) 

tf.Tensor(
[[ 2010 20100]
 [ 4030 40300]], shape=(2, 2), dtype=int32)<jupyter_text>Tensors are used in all kinds of operations (ops).<jupyter_code>c = tf.constant([ [324, 627,53], [92, 770., 772]])

print(tf.reduce_mean(c))
print(tf.reduce_max(c))
print(tf.argmax(c,axis=0))
print(tf.argmax(c,axis=1))
print(tf.argmin(c))
print(tf.argsort(c))
print(tf.nn.softmax(c))<jupyter_output>tf.Tensor(439.66666, shape=(), dtype=float32)
tf.Tensor(772.0, shape=(), dtype=float32)
tf.Tensor([0 1 1], shape=(3,), dtype=int64)
tf.Tensor([1 2], shape=(2,), dtype=int64)
tf.Tensor([1 0 0], shape=(3,), dtype=int64)
tf.Tensor(
[[2 0 1]
 [0 1 2]], shape=(2, 3), dtype=int32)
tf.Tensor(
[[0.         1.         0.        ]
 [0.         0.11920292 0.880797  ]], shape=(2, 3), dtype=float32)<jupyter_text>About shapes Tensors have shapes.  Some vocabulary:* **Shape**: The length (number of elements) of each of the axes of a tensor.* **Rank**: Number of tensor axes.  A scalar has rank 0, a vector has rank 1, a matrix is rank 2.* **Axis** or **Dimension**: A particular dimension of a tensor.* **Size**: The total number of items in the tensor, the product shape vector. Note: Although you may see reference to a "tensor of two dimensions", a rank-2 tensor does not usually describe a 2D space. Tensors and `tf.TensorShape` objects have convenient properties for accessing these:<jupyter_code>rank_4_tensor = tf.zeros([3, 2, 4, 5])<jupyter_output><empty_output><jupyter_text>A rank-4 tensor, shape: [3, 2, 4, 5]<jupyter_code>print("Type of every element:", rank_4_tensor.dtype)
print("Number of axes:", rank_4_tensor.ndim)
print("Shape of tensor:", rank_4_tensor.shape)
print("Elements along axis 0 of tensor:", rank_4_tensor.shape[0])
print("Elements along the last axis of tensor:", rank_4_tensor.shape[-1])
print("Total number of elements (3*2*4*5): ", tf.size(rank_4_tensor).numpy())<jupyter_output>Type of every element: <dtype: 'float32'>
Number of axes: 4
Shape of tensor: (3, 2, 4, 5)
Elements along axis 0 of tensor: 3
Elements along the last axis of tensor: 5
Total number of elements (3*2*4*5):  120<jupyter_text>While axes are often referred to by their indices, you should always keep track of the meaning of each. Often axes are ordered from global to local: The batch axis first, followed by spatial dimensions, and features for each location last. This way feature vectors are contiguous regions of memory.Typical axis order        Indexing  Single-axis indexingTensorFlow follows standard Python indexing rules, similar to [indexing a list or a string in Python](https://docs.python.org/3/tutorial/introduction.htmlstrings), and the basic rules for NumPy indexing.* indexes start at `0`* negative indices count backwards from the end* colons, `:`, are used for slices: `start:stop:step`<jupyter_code>rank_1_tensor = tf.constant([0, 1, 1, 2, 3, 5, 8, 13, 21, 34])
print(rank_1_tensor.numpy())<jupyter_output>[ 0  1  1  2  3  5  8 13 21 34]<jupyter_text>Indexing with a scalar removes the axis:<jupyter_code>print("First:", rank_1_tensor[0].numpy())
print("Second:", rank_1_tensor[1].numpy())
print("Last:", rank_1_tensor[-1].numpy())<jupyter_output>First: 0
Second: 1
Last: 34<jupyter_text>Indexing with a `:` slice keeps the axis:<jupyter_code>print("Everything:", rank_1_tensor[:].numpy())
print("Before 4:", rank_1_tensor[:4].numpy())
print("From 4 to the end:", rank_1_tensor[4:].numpy())
print("From 2, before 7:", rank_1_tensor[2:7].numpy())
print("Every other item:", rank_1_tensor[::2].numpy())
print("Reversed:", rank_1_tensor[::-1].numpy())<jupyter_output>Everything: [ 0  1  1  2  3  5  8 13 21 34]
Before 4: [0 1 1 2]
From 4 to the end: [ 3  5  8 13 21 34]
From 2, before 7: [1 2 3 5 8]
Every other item: [ 0  1  3  8 21]
Reversed: [34 21 13  8  5  3  2  1  1  0]<jupyter_text>Multi-axis indexing Higher rank tensors are indexed by passing multiple indices.The exact same rules as in the single-axis case apply to each axis independently.<jupyter_code>rank_2_tensor = rank_2_t
print(rank_2_tensor.numpy())<jupyter_output>[[1. 2.]
 [3. 4.]
 [5. 6.]]<jupyter_text>Passing an integer for each index, the result is a scalar.<jupyter_code># Pull out a single value from a 2-rank tensor
print(rank_2_tensor[1, 1].numpy())<jupyter_output>4.0<jupyter_text>You can index using any combination of integers and slices:<jupyter_code># Get row and column tensors
print("Second row:", rank_2_tensor[1, :].numpy())
print("Second column:", rank_2_tensor[:, 1].numpy())
print("Last row:", rank_2_tensor[-1, :].numpy())
print("First item in last column:", rank_2_tensor[0, -1].numpy())
print("Skip the first row:")
print(rank_2_tensor[1:, :].numpy(), "\n")<jupyter_output>Second row: [3. 4.]
Second column: [2. 4. 6.]
Last row: [5. 6.]
First item in last column: 2.0
Skip the first row:
[[3. 4.]
 [5. 6.]]<jupyter_text>Here is an example with a 3-axis tensor:<jupyter_code>rank_3_tensor = rank_3_t
print(rank_3_tensor[:, :, 4])<jupyter_output>tf.Tensor(
[[ 5 10 30]
 [15 20 40]], shape=(2, 3), dtype=int32)<jupyter_text>Selecting the last feature across all locations in each example in the batch                Read the [tensor slicing guide](https://tensorflow.org/guide/tensor_slicing) to learn how you can apply indexing to manipulate individual elements in your tensors.  Manipulating ShapesReshaping a tensor is of great utility.<jupyter_code># Shape returns a `TensorShape` object that shows the size along each axis
x = tf.constant([[1], [2], [3]])
print(x.shape)
# You can convert this object into a Python list, too
x.shape.as_list()<jupyter_output><empty_output><jupyter_text>You can reshape a tensor into a new shape.  vvvImp - NOTE - The `tf.reshape` operation is fast and cheap as the underlying data does not need to be duplicated. @Comment by me- While reshaping, the elements are picked from the contiguous list of original data in the form prescribed in the output shape. Thus, one can ask for any shape break-up as long as the product of all dimensions is preserved for the input and output shapes.<jupyter_code># You can reshape a tensor to a new shape.
# Note that you're passing in a list
reshaped = tf.reshape(x, [1, 3])
# You can reshape a tensor to a new shape.
# Note that you're passing in a list
x_reshaped = tf.reshape(x, [1,3])
print(x.shape)
print(x_reshaped.shape)
x.numpy()
x_reshaped.numpy()<jupyter_output><empty_output><jupyter_text>The data maintains its layout in memory and a new tensor is created, with the requested shape, pointing to the same data. TensorFlow uses C-style "row-major" memory ordering, where incrementing the rightmost index corresponds to a single step in memory.<jupyter_code>print(rank_3_tensor)<jupyter_output>tf.Tensor(
[[[ 1  2  3  4  5]
  [ 6  7  8  9 10]
  [26 27 28 29 30]]

 [[11 12 13 14 15]
  [16 17 18 19 20]
  [36 37 38 39 40]]], shape=(2, 3, 5), dtype=int32)<jupyter_text>If you flatten a tensor you can see what order it is laid out in memory.<jupyter_code># A `-1` passed in the `shape` argument says "Whatever fits".
print(tf.reshape(rank_3_tensor, [-1]))<jupyter_output>tf.Tensor(
[ 1  2  3  4  5  6  7  8  9 10 26 27 28 29 30 11 12 13 14 15 16 17 18 19
 20 36 37 38 39 40], shape=(30,), dtype=int32)<jupyter_text>Typically the only reasonable use of `tf.reshape` is to combine or split adjacent axes (or add/remove `1`s).For this 3x2x5 tensor, reshaping to (3x2)x5 or 3x(2x5) are both reasonable things to do, as the slices do not mix: Note -the above rank_3_t or rank_3_tensor is created by me in (2,3,5) shape instead of the original (3,2,5) in the tutorial. Thus, the above description would not match.<jupyter_code>print(tf.reshape(rank_3_tensor, [3*2, 5]), "\n")
print(tf.reshape(rank_3_tensor, [3, -1]))
print(rank_3_t)
print(tf.reshape(rank_3_t, [3*2, 5]), '\n')
print(tf.reshape(rank_3_t, [2, -1]), '\n')
# not a sensible operation
print(tf.reshape(rank_3_t, [3, -1]))<jupyter_output>tf.Tensor(
[[[ 1  2  3  4  5]
  [ 6  7  8  9 10]
  [26 27 28 29 30]]

 [[11 12 13 14 15]
  [16 17 18 19 20]
  [36 37 38 39 40]]], shape=(2, 3, 5), dtype=int32)
tf.Tensor(
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [26 27 28 29 30]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [36 37 38 39 40]], shape=(6, 5), dtype=int32) 

tf.Tensor(
[[ 1  2  3  4  5  6  7  8  9 10 26 27 28 29 30]
 [11 12 13 14 15 16 17 18 19 20 36 37 38 39 40]], shape=(2, 15), dtype=int32) 

tf.Tensor(
[[ 1  2  3  4  5  6  7  8  9 10]
 [26 27 28 29 30 11 12 13 14 15]
 [16 17 18 19 20 36 37 38 39 40]], shape=(3, 10), dtype=int32)<jupyter_text>Note -the above rank_3_t or rank_3_tensor is created by me in (2,3,5) shape instead of the original (3,2,5) in the tutorial. Thus, the below figures would not match.  Some good reshapes.                vvvImp Reshaping will "work" for any new shape with the same total number of elements, but it will not do anything useful if you do not respect the order of the axes.Swapping axes in `tf.reshape` does not work; you need `tf.transpose` for that.<jupyter_code># Bad examples: don't do this

# You can't reorder axes with reshape.
print(tf.reshape( rank_3_t, [3,2,5]))

# This is a mess
# Data contiguously gets picked but is meaningless.
print(tf.reshape(rank_3_t, [5,6]) )

try:
    tf.reshape(rank_3_t, [7,-1])
except Exception as e:
    print(f"{type(e).__name__} :: {e}")
    print(f"{type(e)} :: {e}")<jupyter_output>tf.Tensor(
[[[ 1  2  3  4  5]
  [ 6  7  8  9 10]]

 [[26 27 28 29 30]
  [11 12 13 14 15]]

 [[16 17 18 19 20]
  [36 37 38 39 40]]], shape=(3, 2, 5), dtype=int32)
tf.Tensor(
[[ 1  2  3  4  5  6]
 [ 7  8  9 10 26 27]
 [28 29 30 11 12 13]
 [14 15 16 17 18 19]
 [20 36 37 38 39 40]], shape=(5, 6), dtype=int32)
InvalidArgumentError :: Input to reshape is a tensor with 30 values, but the requested shape requires a multiple of 7 [Op:Reshape]
<class 'tensorflow.python.framework.errors_impl.InvalidArgumentError'> :: Input to reshape is a tensor with 30 values, but the requested shape requires a multiple of 7 [Op:Reshape]<jupyter_text>Some bad reshapes.             You may run across not-fully-specified shapes. Either the shape contains a `None` (an axis-length is unknown) or the whole shape is `None` (the rank of the tensor is unknown).Except for [tf.RaggedTensor](ragged_tensors), such shapes will only occur in the context of TensorFlow's symbolic, graph-building  APIs:* [tf.function](function.ipynb) * The [keras functional API](keras/functional.ipynb).  More on `DTypes`To inspect a `tf.Tensor`'s data type use the `Tensor.dtype` property.When creating a `tf.Tensor` from a Python object you may optionally specify the datatype.If you don't, TensorFlow chooses a datatype that can represent your data. TensorFlow converts Python integers to `tf.int32` and Python floating point numbers to `tf.float32`. Otherwise TensorFlow uses the same rules NumPy uses when converting to arrays.You can cast from type to type.<jupyter_code>f64_t = tf.constant( [1.1, 2.2, 3.3], dtype=tf.float64)
print(f64_t)

f16_t = tf.cast( f64_t, dtype=tf.float16 )
print(f16_t)

# Now, cast to an uint8 and lose the decimal precision
u8_t = tf.cast(f16_t, dtype=tf.uint8)
print(u8_t)<jupyter_output>tf.Tensor([1.1 2.2 3.3], shape=(3,), dtype=float64)
tf.Tensor([1.1 2.2 3.3], shape=(3,), dtype=float16)
tf.Tensor([1 2 3], shape=(3,), dtype=uint8)<jupyter_text>BroadcastingBroadcasting is a concept borrowed from the [equivalent feature in NumPy](https://numpy.org/doc/stable/user/basics.html).  In short, under certain conditions, smaller tensors are "stretched" automatically to fit larger tensors when running combined operations on them.The simplest and most common case is when you attempt to multiply or add a tensor to a scalar.  In that case, the scalar is broadcast to be the same shape as the other argument.<jupyter_code>x = tf.constant([1, 2, 3])

y = tf.constant(2)
z = tf.constant([2, 2, 2])
# All of these are the same computation
print(tf.multiply(x, 2))
print(x * y)
print(x * z)
x = tf.constant([1,2,3])

y = tf.constant(2)
z = tf.constant([2,2,2])
# All of these are the same computation
print(x*2)
print(x*y)
print(x*z)

print(x.shape)
print(y.shape)<jupyter_output>(3,)
()<jupyter_text>Likewise, axes with length 1 can be stretched out to match the other arguments.  Both arguments can be stretched in the same computation.In this case a 3x1 matrix is element-wise multiplied by a 1x4 matrix to produce a 3x4 matrix. Note how the leading 1 is optional: The shape of y is `[4]`.<jupyter_code># These are the same computations
x = tf.reshape(x,[3,1])
y = tf.range(1, 5)
print(x, "\n")
print(y, "\n")
print(tf.multiply(x, y))<jupyter_output><empty_output><jupyter_text>These are the same computations<jupyter_code>x = tf.reshape(x, [3,1])
y = tf.range(1,5)
print(x)
print(y)
print(tf.multiply(x,y))<jupyter_output>tf.Tensor(
[[1]
 [2]
 [3]], shape=(3, 1), dtype=int32)
tf.Tensor([1 2 3 4], shape=(4,), dtype=int32)
tf.Tensor(
[[ 1  2  3  4]
 [ 2  4  6  8]
 [ 3  6  9 12]], shape=(3, 4), dtype=int32)<jupyter_text>A broadcasted add: a [3, 1] times a [1, 4] gives a [3,4]      Here is the same operation without broadcasting:<jupyter_code>x_stretch = tf.constant([[1, 1, 1, 1],
                         [2, 2, 2, 2],
                         [3, 3, 3, 3]])

y_stretch = tf.constant([[1, 2, 3, 4],
                         [1, 2, 3, 4],
                         [1, 2, 3, 4]])

print(x_stretch * y_stretch)  # Again, operator overloading
x_stretch = tf.constant([
    [1,1,1,1]
    , [2,2,2,2]
    , [3,3,3,3]
])

y_stretch = tf.constant([
    [1,2,3,4]
    , [1,2,3,4]
    , [1,2,3,4]
]
)
# Again, operator overloading
print(x_stretch * y_stretch)<jupyter_output>tf.Tensor(
[[ 1  2  3  4]
 [ 2  4  6  8]
 [ 3  6  9 12]], shape=(3, 4), dtype=int32)<jupyter_text>Most of the time, broadcasting is both time and space efficient, as the broadcast operation never materializes the expanded tensors in memory.  You see what broadcasting looks like using `tf.broadcast_to`.<jupyter_code>print(tf.broadcast_to(tf.constant([1, 2, 3]), [3, 3]))
print( tf.broadcast_to(tf.constant([1,2,3]), [3,3]))<jupyter_output>tf.Tensor(
[[1 2 3]
 [1 2 3]
 [1 2 3]], shape=(3, 3), dtype=int32)<jupyter_text>Unlike a mathematical op, for example, `broadcast_to` does nothing special to save memory.  Here, you are materializing the tensor.It can get even more complicated.  [This section](https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html) of Jake VanderPlas's book _Python Data Science Handbook_ shows more broadcasting tricks (again in NumPy).  tf.convert_to_tensorMost ops, like `tf.matmul` and `tf.reshape` take arguments of class `tf.Tensor`.  However, you'll notice in the above case, Python objects shaped like tensors are accepted.Most, but not all, ops call `convert_to_tensor` on non-tensor arguments.  There is a registry of conversions, and most object classes like NumPy's `ndarray`, `TensorShape`, Python lists, and `tf.Variable` will all convert automatically.See `tf.register_tensor_conversion_function` for more details, and if you have your own type you'd like to automatically convert to a tensor.  Ragged TensorsA tensor with variable numbers of elements along some axis is called "ragged". Use `tf.ragged.RaggedTensor` for ragged data.For example, This cannot be represented as a regular tensor:   A `tf.RaggedTensor`, shape: [4, None]<jupyter_code>ragged_list = [
    [0, 1, 2, 3],
    [4, 5],
    [6, 7, 8],
    [9]]
try:
  tensor = tf.constant(ragged_list)
except Exception as e:
  print(f"{type(e).__name__}: {e}")<jupyter_output>ValueError: Can't convert non-rectangular Python sequence to Tensor.<jupyter_text>Instead create a `tf.RaggedTensor` using `tf.ragged.constant`:<jupyter_code>ragged_tensor = tf.ragged.constant(ragged_list)
print(ragged_tensor)<jupyter_output><tf.RaggedTensor [[0, 1, 2, 3], [4, 5], [6, 7, 8], [9]]><jupyter_text>The shape of a `tf.RaggedTensor` will contain some axes with unknown lengths:<jupyter_code>print(ragged_tensor.shape)<jupyter_output>(4, None)<jupyter_text>String tensors`tf.string` is a `dtype`, which is to say you can represent data as strings (variable-length byte arrays) in tensors.The strings are atomic and cannot be indexed the way Python strings are. The length of the string is not one of the axes of the tensor. See `tf.strings` for functions to manipulate them. Here is a scalar string tensor:<jupyter_code># Tensors can be strings, too here is a scalar string.
scalar_string_tensor = tf.constant("Gray wolf")
print(scalar_string_tensor)<jupyter_output>tf.Tensor(b'Gray wolf', shape=(), dtype=string)<jupyter_text>And a vector of strings:   A vector of strings, shape: [3,]<jupyter_code># If you have three string tensors of different lengths, this is OK.
tensor_of_strings = tf.constant(["Gray wolf",
                                 "Quick brown fox",
                                 "Lazy dog"])
# Note that the shape is (3,). The string length is not included.
print(tensor_of_strings)<jupyter_output>tf.Tensor([b'Gray wolf' b'Quick brown fox' b'Lazy dog'], shape=(3,), dtype=string)<jupyter_text>In the above printout the `b` prefix indicates that `tf.string` dtype is not a unicode string, but a byte-string. See the [Unicode Tutorial](https://www.tensorflow.org/tutorials/load_data/unicode) for more about working with unicode text in TensorFlow. If you pass unicode characters they are utf-8 encoded.<jupyter_code>tf.constant("🥳👍")<jupyter_output><empty_output><jupyter_text>Some basic functions with strings can be found in `tf.strings`, including `tf.strings.split`.<jupyter_code># You can use split to split a string into a set of tensors
print(tf.strings.split(scalar_string_tensor, sep = ' '))
# ...but it turns into a `RaggedTensor` if you split up a tensor of strings,
# as each string might be split into a different number of parts.
print(tf.strings.split(tensor_of_strings))<jupyter_output><tf.RaggedTensor [[b'Gray', b'wolf'], [b'Quick', b'brown', b'fox'], [b'Lazy', b'dog']]><jupyter_text>Three strings split, shape: [3, None]     And `tf.string.to_number`:<jupyter_code>text = tf.constant('1 10 100')
print(tf.strings.to_number( tf.strings.split(text, ' ')))<jupyter_output>tf.Tensor([  1.  10. 100.], shape=(3,), dtype=float32)<jupyter_text>Although you can't use `tf.cast` to turn a string tensor into numbers, you can convert it into bytes, and then into numbers.<jupyter_code>byte_strings = tf.strings.bytes_split(tf.constant('Duck'))
byte_ints = tf.io.decode_raw(tf.constant('Duck'), tf.uint8)
print("Byte strings: ", byte_strings)
print("Bytes/Byte ints:", byte_ints)
# Or split it up as unicode and then decode it
unicode_bytes = tf.constant("アヒル 🦆")
unicode_char_bytes = tf.strings.unicode_split(unicode_bytes, "UTF-8")
unicode_values = tf.strings.unicode_decode(unicode_bytes, "UTF-8")

print("\nUnicode bytes:", unicode_bytes)
print("\nUnicode chars:", unicode_char_bytes)
print("\nUnicode values:", unicode_values)
unicode_bytes = tf.constant('アヒル 🦆')
unciode_char_bytes = tf.strings.unicode_split(unicode_bytes, 'UTF-8')
unicode_values = tf.strings.unicode_decode( unicode_bytes, 'UTF-8')

print("\nUnicode bytes:", unicode_bytes)
print("\nUnicode chars:", unicode_char_bytes)
print("\nUnicode values:", unicode_values)<jupyter_output>Unicode bytes: tf.Tensor(b'\xe3\x82\xa2\xe3\x83\x92\xe3\x83\xab \xf0\x9f\xa6\x86', shape=(), dtype=string)

Unicode chars: tf.Tensor([b'\xe3\x82\xa2' b'\xe3\x83\x92' b'\xe3\x83\xab' b' ' b'\xf0\x9f\xa6\x86'], shape=(5,), dtype=string)

Unicode values: tf.Tensor([ 12450  12498  12523     32 129414], shape=(5,), dtype=int32)<jupyter_text>The `tf.string` dtype is used for all raw bytes data in TensorFlow. The `tf.io` module contains functions for converting data to and from bytes, including decoding images and parsing csv.  Sparse tensorsSometimes, your data is sparse, like a very wide embedding space.  TensorFlow supports `tf.sparse.SparseTensor` and related operations to store sparse data efficiently.   A `tf.SparseTensor`, shape: [3, 4]<jupyter_code># Sparse tensors store values by index in a memory-efficient manner
sparse_t = tf.sparse.SparseTensor( indices=[ [0,1], [2,3]]
                                 , values=[97, 35]
                                 , dense_shape=[3,4])
# You can convert sparse tensors to dense
print(sparse_t)
print(tf.sparse.to_dense(sparse_t))<jupyter_output>SparseTensor(indices=tf.Tensor(
[[0 1]
 [2 3]], shape=(2, 2), dtype=int64), values=tf.Tensor([97 35], shape=(2,), dtype=int32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64))
tf.Tensor(
[[ 0 97  0  0]
 [ 0  0  0  0]
 [ 0  0  0 35]], shape=(3, 4), dtype=int32)
{'fraction_non_alphanumeric': 0.13271295080701212, 'fraction_numerical': 0.06139470229361341, 'mean_word_length': 4.334500514933059, 'pattern_counts': {'":': 0, '<': 137, '<?xml version=': 0, '>': 137, 'https://': 7, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '40', 'dir': 'jupyter-structured-clean-dedup', 'id': '592890', 'license': 'Apache-2.0', 'n_tokens_mistral': 10175, 'n_tokens_neox': 9021, 'n_words': 3135, 'path': 'site/en/guide/tensor_mine.ipynb', 'repo_name': 'kewlcoder/docs', 'size': '25898'}