1.4TensorFlow常用函数

TensorFlow常用函数
  • 强制Tensor转换为该数据类型
    tf.cast(张量名, dtype=数据类型)
import tensorflow as tf

# tf.cast(张量名, dtype=数据类型)  强制tensor转换为该数据类型

x1 = tf.constant([1.1, 2.2, 3.3], dtype=tf.float64)    # 构建一个1维张量x1,数据类型是tf.float64
print("x1:", x1)
x2 = tf.cast(x1, tf.int32)      # 将张量x1的数据类型强制转换为tf.int32
print("x2:", x2)
x1: tf.Tensor([1.1 2.2 3.3], shape=(3,), dtype=float64)
x2: tf.Tensor([1 2 3], shape=(3,), dtype=int32)
  • 计算张量维度上元素的最小值
    tf.reduce_min(张量名)
import tensorflow as tf

# tf.reduce_min(张量名)   计算张量维度上元素的最小值

x2 = tf.constant([1, 2, 3], dtype=tf.int32)
print("minimum of x2:", tf.reduce_min(x2))      # 输出张量x2的最小值
minimum of x2: tf.Tensor(1, shape=(), dtype=int32)
  • 计算张量维度上元素的最大值
    tf.reduce_max(张量名)
import tensorflow as tf

# tf.reduce_max(张量名)   计算张量维度上元素的最大值

x3 = tf.constant([1, 2, 3], dtype=tf.int32)
print("minimum of x3:", tf.reduce_max(x3))      # 输出张量x3的最大值
maxmum of x3: tf.Tensor(3, shape=(), dtype=int32)
理解axis
  • 在一个二维张量或数组中,可以通过调整axis等于0或者1控制执行维度。
  • axis=0表示跨行(经度,down),而axis=1代表跨列(纬度,across)
  • 如果不指定axis,则所有元素参与计算
  • 计算张量沿着指定维度的平均值
    tf.reduce_mean(张量名, axis=操作轴)
import tensorflow as tf

# 在一个2维张量或数组中,可以通过调整axis=0 or axis=1控制执行维度。axis=0代表纵向跨行,axis=1代表横向跨列。如果不指定axis,则所有元素参与计算。

# tf.reduce_mean(张量名, axis=操作轴) 计算张量沿着指定维度的平均值
x = tf.constant([[1, 2, 3], [2, 2, 3]])
print("x:", x)
print("mean of x:", tf.reduce_mean(x))  # 计算张量x中所有数的均值
x: tf.Tensor([[1 2 3] [2 2 3]], shape=(2, 3), dtype=int32)
mean of x: tf.Tensor(2, shape=(), dtype=int32)
  • 计算张量沿着指定维度的和
    tf.reduce_sum(张量名, axis=操作轴)
import tensorflow as tf

# 在一个2维张量或数组中,可以通过调整axis=0 or axis=1控制执行维度。axis=0代表纵向跨行,axis=1代表横向跨列。如果不指定axis,则所有元素参与计算。
# tf.reduce_sum(张量名, axis=操作轴)  计算张量沿着指定维度的和
x = tf.constant([[1, 2, 3], [2, 2, 3]])
print("x:", x)
print("sum of x:", tf.reduce_sum(x, axis=1))  # 计算张量x每一行的和
x: tf.Tensor([[1 2 3] [2 2 3]], shape=(2, 3), dtype=int32)
sum of x: tf.Tensor([6 7], shape=(2,), dtype=int32)
  • tf.Variable()将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用该函数标记待训练参数。
    tf.Variable(初始值)
    w = tf.Variable(tf.random.normal([2, 2], mean=0, stddev=1))
TensorFlow中的数学运算
  • 对应元素的四则运算:tf.addtf.subtracttf.multiplytf.divide
  • 平方、次方与开方:tf.squaretf.powtf.sqrt
  • 矩阵乘法:tf.matmul
对应元素的四则运算
  • 实现两个张量的对应元素相加
    tf.add(张量1, 张量2)
  • 实现两个张量的对应元素相减
    tf.subtract(张量1, 张量2)
  • 实现两个张量的对应元素相乘
    tf.multiply(张量1, 张量2)
  • 实现两个张量的对应元素相除
    tf.divide(张量1, 张量2)
import tensorflow as tf

# 对应元素的四则运算:tf.add, tf.subtract, tf.multiply, tf.divide
# 平方、次方与开方:tf.square, tf.pow, tf.sqrt
# 矩阵乘:tf.matmul

# tf.add(张量1, 张量2)  实现2个张量的对应元素相加
# tf.subtract(张量1, 张量2) 实现2个张量的对应元素相减
# tf.multiply(张量1, 张量2) 实现2个张量的对应元素相乘
# tf.divide(张量1, 张量2)   实现2个张量的对应元素相除
# 只有维度相同的张量才可以做四则运算

a = tf.ones([1, 3])
b = tf.fill([1, 3], 3.)
print("a:", a)
print("b:", b)
print("a+b:", tf.add(a, b))
print("a-b:", tf.subtract(a, b))
print("a*b:", tf.multiply(a, b))
print("b/a:", tf.divide(b, a))
a: tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
b: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
a+b: tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32)
a-b: tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32)
a*b: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
b/a: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
平方、次方与开方
  • 计算某个张量的平方
    tf.square(张量名)
  • 计算某个张量的n次方
    tf.pow(张量名, n次方数)
  • 计算某个张量的开方
    tf.sqrt(张量名)
import tensorflow as tf

# tf.square(张量名)    计算某个张量的平方
# tf.pow(张量名, n次方数) 计算某个张量的n次方
# tf.sqrt(张量名)  计算某个张量的开方

a = tf.fill([1, 2], 4.0)
print("a:", a)
print("a的平方:", tf.square(a))
print("a的次方:", tf.pow(a, 3))
print("a的开方:", tf.sqrt(a))
a: tf.Tensor([[4. 4.]], shape=(1, 2), dtype=float32)
a的平方: tf.Tensor([[16. 16.]], shape=(1, 2), dtype=float32)
a的次方: tf.Tensor([[64. 64.]], shape=(1, 2), dtype=float32)
a的开方: tf.Tensor([[2. 2.]], shape=(1, 2), dtype=float32)
矩阵乘法tf.matmul
  • 实现两个矩阵的相乘
    tf.matmul(矩阵1, 矩阵2)
import tensorflow as tf

# tf.matmul(矩阵1, 矩阵2)   实现两个矩阵的相乘

a = tf.ones([3, 2])
b = tf.fill([2, 3], 3.)
print("a:", a)
print("b:", b)
print("a*b:", tf.matmul(a, b))
a: tf.Tensor(
[[1. 1.]
 [1. 1.]
 [1. 1.]], shape=(3, 2), dtype=float32)
b: tf.Tensor(
[[3. 3. 3.]
 [3. 3. 3.]], shape=(2, 3), dtype=float32)
a*b: tf.Tensor(
[[6. 6. 6.]
 [6. 6. 6.]
 [6. 6. 6.]], shape=(3, 3), dtype=float32)
tf.data.Dataset.from_tensor_slices
  • 切分传入张量的第一维度,生成输入特征/标签对,构建数据集data=tf.data.Dataset.from_tensor_slices((输入特征, 标签))。Numpy和Tensor格式都可用该语句读入数据。
import tensorflow as tf

# tf.data.Dataset.from_tensor_slices    切分传入张量的第一维度,生成输入特征/标签对,构建数据集。Numpy和Tensor格式都可用该语句读入数据。

features = tf.constant([12, 23, 10, 17])    #收集的特征是12 23 10 17
labels = tf.constant([0, 1, 1, 0])          #每个特征对应的标签是0 1 1 0
dataset = tf.data.Dataset.from_tensor_slices((features, labels))    #用from_tensor_slices()把特征和标签配对上
for element in dataset:
    print(element)
(<tf.Tensor: id=9, shape=(), dtype=int32, numpy=12>, <tf.Tensor: id=10, shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: id=11, shape=(), dtype=int32, numpy=23>, <tf.Tensor: id=12, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=13, shape=(), dtype=int32, numpy=10>, <tf.Tensor: id=14, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=15, shape=(), dtype=int32, numpy=17>, <tf.Tensor: id=16, shape=(), dtype=int32, numpy=0>)
tf.GradientTape
  • with结构记录计算过程,gradient求出张量的梯度
    wiht tf.GradientTape() as tape:
        若干计算过程
    grad=tape.gradient(函数, 对谁求导)
    ∂ w 2 ∂ w = 2 w = 2 ∗ 3.0 = 6.0 \frac{\partial w^{2}}{\partial w}=2 w=2^{*} 3.0=6.0 ww2=2w=23.0=6.0
import tensorflow as tf

# with tf.GradientTape() as tape:
#   若干计算过程
# grad=tape.gradient(函数, 对谁求导)  with结构记录计算过程,gradient求出张量的梯度

with tf.GradientTape() as tape:
    w = tf.Variable(tf.constant(3.0))  # w初始值为3.0
    loss = tf.pow(w, 2)                # loss = w^2
grad = tape.gradient(loss, w)          # loss对w求导,结果是2*w,将w=3.0初始值代入,结果grad=6.0
print(grad)
tf.Tensor(6.0, shape=(), dtype=float32)
enumerate
  • enumerate是Python的内建函数,它可以遍历每个元素(如列表、元组、或字符串),组合为:索引 元素,常在for循环中使用。
    enumerate(列表名)
# enumerate是Python中的内建函数,它可遍历每个元素(如列表、元组或字符串),组合为:索引 元素,常在for循环中使用。
# enumerate(列表名)

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
    print(i, element)
0 one
1 two
2 three

tf.one_hot

  • 独热编码(ont-hot encoding):在分类问题中,常用独热码做标签,类别标签:1表示是,0表示非。
            (0狗尾鸢尾     1杂色鸢尾    2弗吉尼亚鸢尾)
    标签:    1
    独热码:(0.                1.                0                  )
    • 0%的可能是0狗尾鸢尾,100%的可能是1杂色鸢尾0%的可能是2弗吉尼亚鸢尾
tf.one_hot
  • tf.one_hot()函数将待转换数据,转换为one-hot形式的数据输出。
    tf.one_hot(待转换数据, depth=几分类)
import tensorflow as tf

# tf.one_hot(待转换数据,depth=几分类)   tf.one_hot()函数将待转换数据,转换为one_hot形式的数据输出。

classes = 3
labels = tf.constant([1, 0, 2])  # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels, depth=classes)
print("result of labels1:", output)
print("\n")
result of labels1: tf.Tensor(
[[0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]], shape=(3, 3), dtype=float32)

你可能感兴趣的:(TensorFlow)