TensorFlow2常用函数

声明

声明:本系列博客是我在学习人工智能实践:TensorFlow笔记(曹健,北京大学,软件与微电子学院)所做的笔记。所以,其中的绝大部分内容引自这系列视频,博客中的代码也是视频配套所附带的代码,其中部分代码可能会因需要而改动。侵删。在本系列博客中,其中包含视频中的引用,也包括我自己对知识的理解,思考和总结。本系列博客的目的主要有两个,一个是可以作为我自己的学习笔记,时常复习巩固。第二个是可以为想学习TensorFlow 2 相关知识的朋友提供一些参考。

正文

1.强制tensor转换为该数据类型

tf.cast(张量名,dtype=数据类型)

2.计算张量维度上元素的最小值

tf.reduce_min(张量名)

3.计算张量维度上元素的最大值

tf.reduce_max(张量名)

x1 = tf.constant([1., 2., 3.], dtype=tf.float64)
print("x1:", x1)
x2 = tf.cast(x1, tf.int32)
print("x2", x2)
print("minimum of x2:", tf.reduce_min(x2))
print("maxmum of x2:", tf.reduce_max(x2))

运行结果:

x1: tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
x2 tf.Tensor([1 2 3], shape=(3,), dtype=int32)
minimum of x2: tf.Tensor(1, shape=(), dtype=int32)
maxmum of x2: tf.Tensor(3, shape=(), dtype=int32)

4. 理解axis

在一个二维张量或数组中,可以通过调整axis等于0或1控制执行维度。
axis=0代表跨行,而axis=1代表跨列。
如果不指定axis,则所有元素参与计算。
在这里插入图片描述

5.计算张量沿着指定维度的平均值

tf.reduce_mean(张量名,axis=操作轴)

6.计算张量沿着指定维度的和

tf.reduce_sum(张量名,axis=操作轴)

x = tf.constant([[1., 2., 3.], [2., 2., 3.]])
print("x:", x)
print("mean of x:", tf.reduce_mean(x))  # 求x中所有数的均值
print("sum of x:", tf.reduce_sum(x, axis=1))  # 求每一行的和

运行结果:

x: tf.Tensor(
[[1 2 3]
 [2 2 3]], shape=(2, 3), dtype=int32)
mean of x: tf.Tensor(2, shape=(), dtype=int32)
sum of x: tf.Tensor([6 7], shape=(2,), dtype=int32)

7. tf.Variable

tf.Variable()将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用该函数标记待训练参数。
tf.Variable(初始值)

8.对应元素的四则运算

功能函数
tf.add(张量1,张量2)
tf.subtract(张量1,张量2)
tf.multiply(张量1,张量2)
tf.divide(张量1,张量2)

注意:只有维度相同的张量才可以做四则运算。

import tensorflow as tf
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)

9.平方、次方与开方

功能函数
计算某个张量的平方tf.square(张量名)
计算某个张量的n次方tf.pow(张量名,n次方数)
计算某个张量的开方tf.sqrt(张量名)
import tensorflow as tf
a = tf.fill([1, 2], 3.)
print("a:", a)
print("a的立方:", tf.pow(a, 3))
print("a的平方:", tf.square(a))
print("a的开方:", tf.sqrt(a))

运行结果:

a: tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
a的立方: tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
a的平方: tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
a的开方: tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)

10.矩阵乘tf.matmul

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

import tensorflow as tf
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)

11.tf.data.Dataset.from_tensor_slices

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

import tensorflow as tf
features = tf.constant([12, 23, 10, 17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
for element in dataset:
    print(element)

运行结果:

(<tf.Tensor: id=1601, shape=(), dtype=int32, numpy=12>, <tf.Tensor: id=1602, shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: id=1603, shape=(), dtype=int32, numpy=23>, <tf.Tensor: id=1604, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=1605, shape=(), dtype=int32, numpy=10>, <tf.Tensor: id=1606, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=1607, shape=(), dtype=int32, numpy=17>, <tf.Tensor: id=1608, shape=(), dtype=int32, numpy=0>)

12.tf.GradientTape

with结构记录计算过程,gradient求出张量的梯度。

with tf.GradientTape() as tape:
若干个计算过程
grad=tape.gradient(函数,对谁求导)

import tensorflow as tf
with tf.GradientTape() as tape:
    x = tf.Variable(tf.constant(3.0))
    y = tf.pow(x, 2)
grad = tape.gradient(y, x)
print(grad)

运行结果:

tf.Tensor(6.0, shape=(), dtype=float32)

13.enumerate

enumerate 是python的内建函数,它可遍历每个元素(如列表、元组或字符串),组合为:索引 元素,常在for循环中使用。

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

运行结果:

0 one
1 two
2 three

14.tf.one_hot

独热编码(one-hot encoding):在分类问题中,常用独热编码做标签,标记类别:1表示是,0表示非。
tf.one_hot(待转换数据,depth=几分类)

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)

15.tf.nn.softmax

S o f t m a x ( y i ) = e y i ∑ j = 0 n e y i Softmax(y_i)={e^{y_i}\over \sum_{j=0}^ne^{y_i}} Softmax(yi)=j=0neyieyi

tf.nn.softmax(x)使输出符合概率分布
当n个分类的n个输出( y 0 y_0 y0, y 1 y_1 y1,… y n − 1 y_{n-1} yn1)通过softmax()函数,便符合概率分布了。

y = tf.constant([1.01, 2.01, -0.66])
y_pro = tf.nn.softmax(y)
print("After softmax, y_pro is:", y_pro)  # y_pro 符合概率分布
print("The sum of y_pro:", tf.reduce_sum(y_pro))  # 通过softmax后,所有概率加起来和为1

运行结果:

After softmax, y_pro is: tf.Tensor([0.25598174 0.69583046 0.0481878 ], shape=(3,), dtype=float32)
The sum of y_pro: tf.Tensor(1.0, shape=(), dtype=float32)

16.assign_sub

  • 赋值操作,更新参数的值并返回
  • 调用assign_sub前,先用tf.Variable定义变量w为可训练(可自更新)

w.assign_sub(w要自减的内容)

x = tf.Variable(4)
x.assign_sub(1)
print("x:", x)  # 4-1=3

运行结果:

x: <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>

17.tf.argmax

返回张量沿指定维度最大值的索引
tf.argmax(张量名,axis=操作轴)

test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
print("test:\n", test)
print("每一列的最大值的索引:", tf.argmax(test, axis=0))  # 返回每一列最大值的索引
print("每一行的最大值的索引", tf.argmax(test, axis=1))  # 返回每一行最大值的索引

运行结果:

test:
 [[1 2 3]
 [2 3 4]
 [5 4 3]
 [8 7 2]]
每一列的最大值的索引: tf.Tensor([3 3 1], shape=(3,), dtype=int64)
每一行的最大值的索引 tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)

感谢观看!

如有错误,欢迎批评指正!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值