本文共 1730 字,大约阅读时间需要 5 分钟。
张量(Tensor)是TensorFlow中最基本的数据结构,类似于numpy中的数组。它是一个n维数组,数据类型为tf.Tensor。张量在TensorFlow中具有两个关键属性:【type和shape】。
张量的阶数(rank)从0开始计算,如0阶为标量,1阶为1维数组(列表形式),2阶为矩阵形式等。
创建张量可以分为几种类型:
固定值张量(Constant Tensor):
import tensorflow as tf# 创建常数张量tensor1 = tf.constant(4.0)tensor2 = tf.constant([1, 2, 3, 4])linear_squares = tf.constant([[4], [9], [16], [25]], dtype=tf.int32)# 打印张量信息print(tensor1(shape))
零张量(Zero Tensor):
import osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'import tensorflow as tfzeros = tf.zeros([3, 5])zeros_like = tf.zeros_like(zeros)
一张量(One Tensor):
one = tf.ones([3, 4])ones_like = tf.ones_like(zeros)
随机值张量(Random Tensor):
random_tensor = tf.random_normal([3, 5])
特殊张量创建操作( 其他操作):
通过使用tf.cast函数可以将张量的数据类型转换。例如,将浮点数张量转换为整数型:
import osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'import tensorflow as tfone = tf.ones([3, 4])cast_one = tf.cast(one, tf.int32)print(cast_one)
张量可以进行静态形状或动态形状的改变。
tf.reshape(tensor, new_shape)
tf.reshape(tensor, new_shape)
a = tf.constant(3.0)b = tf.constant(2.0)c = a + bprint(c)
import numpy as npmatrix_a = np.array([[1, 2], [3, 4]])matrix_b = np.array([[5, 6], [7, 8]])tf.matmul(matrix_a, matrix_b)
a = tf.constant([1, 2, 3, 4])b = tf.reduce_sum(a)print(b)
这些操作为张量提供了丰富的运算能力,使其在深度学习和数据处理中极为灵活。
转载地址:http://bnekk.baihongyu.com/