Tensorflow 中的 tensor 及 shape

当我们使用 Tensorflow 来创建数据时,我们需要了解 tensor的数据结构,以便我们对于数据有直观的认识。下面我们来介绍一下 tensor 数据有哪些属性。

Tensor

Tensor 本质是多维数组,并且数组里只能包含一种类型的数据,比如全部是 float或者全部是int,并且 tensor是不能更改的,因此创建后,只能在此基础上再创建新的 tensor

Rank

rank表示维度的数量,因为 tensor是多维度的,维度可以简单理解成坐标系,所以 tensor 可以有多个坐标系。让我们来看一下 rank 为 0-2 的 tensor

rank_0_tensor = tf.constant(4);

rank 为 0 的 tensor 可以理解为一个 scalar,在我们线性代数里常见的 scalar

rank_1_tensor = tf.constant([1.0, 2.0, 3.0]);

rank 为 1 的 tensor 可以理解为一个向量。

rank_2_tensor = tf.constant([[1,2], [3,4], [5,6]]);

rank 为 2 的 tensor 可以理解为一个矩阵。

Shape

每个维度所含元素的数量,其中 Shape返回的是一个 listlist的长度就等于 Rank,其中 list的数据顺序是有一个特定的数据。

Shape 返回值的数据顺序

tensor 中,tensor.shape 返回的 list 值是有特定顺序的;以 tensor_4_rank 举例,Shape 对应的第一个值是 batch size,第二个值是 height,第三个值是 width,第四个值是 feature。(Shape 可以被理解成不同的形状结构,但无论是哪种结构,所有的数据顺序依然保持一致,比如第一个数组是永远是在结构的第一个位置,以此类推)

tensor 元素数量

Shape 返回的 lisrt 的所有值相乘,就是tensor所有值的数量。比如我们通过 tensor.shape 得到一个 list 为 [1,2,3],则该 tensor 的所有数据个数为 1 * 2 * 3 = 6。

要使用 TensorFlow 创建指定形状的张量,可以使用 `tf.zeros`、`tf.ones`、`tf.fill` 或者直接使用 Python 的列表或 NumPy 数组来创建。 以下是几种常见的创建张量的方法示例: 1. 使用 `tf.zeros` 创建全零张量: ```python import tensorflow as tf shape = (2, 3) # 指定形状为 (2, 3) zeros_tensor = tf.zeros(shape) print(zeros_tensor) ``` 输出结果: ``` <tf.Tensor: shape=(2, 3), dtype=float32, numpy= array([[0., 0., 0.], [0., 0., 0.]], dtype=float32)> ``` 2. 使用 `tf.ones` 创建全一张量: ```python import tensorflow as tf shape = (2, 3) # 指定形状为 (2, 3) ones_tensor = tf.ones(shape) print(ones_tensor) ``` 输出结果: ``` <tf.Tensor: shape=(2, 3), dtype=float32, numpy= array([[1., 1., 1.], [1., 1., 1.]], dtype=float32)> ``` 3. 使用 `tf.fill` 创建指定值的张量: ```python import tensorflow as tf shape = (2, 3) # 指定形状为 (2, 3) value = 5 # 指定值为 5 filled_tensor = tf.fill(shape, value) print(filled_tensor) ``` 输出结果: ``` <tf.Tensor: shape=(2, 3), dtype=int32, numpy= array([[5, 5, 5], [5, 5, 5]], dtype=int32)> ``` 4. 使用 Python 列表或 NumPy 数组创建张量: ```python import tensorflow as tf import numpy as np list_data = [[1, 2, 3], [4, 5, 6]] # 使用 Python 列表 numpy_data = np.array([[1, 2, 3], [4, 5, 6]]) # 使用 NumPy 数组 list_tensor = tf.convert_to_tensor(list_data) numpy_tensor = tf.convert_to_tensor(numpy_data) print(list_tensor) print(numpy_tensor) ``` 输出结果: ``` <tf.Tensor: shape=(2, 3), dtype=int32, numpy= array([[1, 2, 3], [4, 5, 6]], dtype=int32)> <tf.Tensor: shape=(2, 3), dtype=int64, numpy= array([[1, 2, 3], [4, 5, 6]])> ``` 希望这些示例能帮助你创建指定形状的张量。如果你有任何进一步的问题,请随时提问!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值