Tensors
1. Tensors
简单来说,张量是在Tensorflow中使用的多维数组
我们做如下的定义:
- Rank:表示的是向量所拥有的维数
下面,我们将定义不同种类的张量并使用 tf.rank 函数显示它们的Rank
tensor = tf.constant(0)
print("Print constant tensor {} of rank {}".format(tensor, tf.rank(tensor)))
print("Show full tensor:", tensor)
# Output:
# Print constant tensor 0 of rank 0
# Show full tensor: tf.Tensor(0, shape=(), dtype=int32)
tf.constant相当于创建了一个张量,但此时张量是一个常数0,因此显然此时的维度是0
# NOTE: We use .numpy() to transform tf.tensor to numpy
tensor = tf.constant([1,2,3])
print("Tensor:", tensor)
print("Rank:", tf.rank(tensor).numpy())
# Output:
# Tensor: tf.Tensor([1 2 3], shape=(3,), dtype=int32)
# Rank: 1
此时是创建了一个一维数组,包含了三个元素,因此rank值为1
2. Tensor Operations
x = tf.constant([[1, 1],
[1, 1]])
y = tf.constant([[2, 4],
[6, 8]])
# 矩阵相加
print(tf.add(x, y), "\n")
# 矩阵相乘
print(tf.matmul(x, y), "\n")
# Output
"""
tf.Tensor(
[[3 5]
[7 9]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[ 8 12]
[ 8 12]], shape=(2, 2), dtype=int32)
"""
3. Muti-dimentional Tensors
与我们目前所学的相比,这部分没有太大的不同。但是,尝试从多维张量中提取尽可能多的信息会很好。
让我们在这里使用 tf.ones。它创建了一个所有值都是1的张量。
# We set the shape of the tensor and the desired data type.
tensor = tf.ones(shape = [2, 3, 6], dtype = tf.float32)
print('Tensor:', tensor)
# Output
'''
Tensor: tf.Tensor(
[[[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]]
[[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]]], shape=(2, 3, 6), dtype=float32)
'''
print("Tensor Rank: ", tf.rank(tensor).numpy())
print("Shape: ", tensor.shape)
print("Elements' type", tensor.dtype)
print("The size of the second axis:", tensor.shape[1])
print("The size of the last axis:", tensor.shape[-1])
print("Total number of elements: ", tf.size(tensor).numpy())
print("How many dimensions? ", tensor.ndim)
# Output
"""
Tensor Rank: 3
Shape: (2, 3, 6)
Elements' type <dtype: 'float32'>
The size of the second axis: 3
The size of the last axis: 6
Total number of elements: 36
How many dimensions? 3
"""
4. Indexing
TensorFlow 索引与 Python 索引一致。请参阅以下示例
x = tf.constant([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# All elements
print(x[:].numpy())
# Output
'''
[[1 2 3]
[4 5 6]
[7 8 9]]
'''
# All elements of the first row
print(x[0,:].numpy())
# Output
'''
[1 2 3]
'''
5. Data types
您可以根据需要更改 tesnorflow 张量的数据类型。这将通过 tf.cast 轻松完成。
original_tensor = tf.constant([1, 2, 3, 4], dtype=tf.int32)
print('Original tensor: ', original_tensor)
print("Tensor type before casting: ", original_tensor.dtype)
# Casting to change dtype
casted_tensor = tf.cast(original_tensor, dtype=tf.float32)
print('New tensor: ', casted_tensor)
print("Tensor type after casting: ", casted_tensor.dtype)
# Output
"""
Original tensor: tf.Tensor([1 2 3 4], shape=(4,), dtype=int32)
Tensor type before casting: <dtype: 'int32'>
New tensor: tf.Tensor([1. 2. 3. 4.], shape=(4,), dtype=float32)
Tensor type after casting: <dtype: 'float32'>
"""