57、TensorFlow 2 基础与应用全解析

TensorFlow 2核心功能详解

TensorFlow 2 基础与应用全解析

1. TF 2 基础函数与输出差异

在 TensorFlow 2 里,我们可以借助 @tf.function 装饰器来定义函数。下面是一个简单示例:

import tensorflow as tf
@tf.function
def compute_values():
    a = tf.add(tf.constant(4), tf.constant(2))
    return a
result = compute_values()
print("result:", result)

这里要注意,Python 的 print() 函数会把输出发送到 “标准输出”(文件描述符值为 1),而 tf.print() 函数则会把输出发送到 “标准错误”(文件描述符值为 2)。在像 C 这样的编程语言中,只有错误信息才会被发送到标准错误,因此 tf.print() 的行为和标准输出、标准错误的常规用法有所不同。下面的代码片段展示了这种差异:

python3 file_with_print.py    1>print_output
python3 file_with_tf.print.py 2>tf.print_output

要是你的 Python 文件里同时包含 print() tf.print() ,可以按如下方式捕获输出:

python3 both_prints.py 1>prnt_output 2>tf.print_output

不过要留意,上述代码片段可能会把真正的错误信息重定向到 tf.print_output 文件中。

2. @tf.function 的使用示例
2.1 无 @tf.function 的示例

下面的代码展示了如何用 TF 2 代码定义一个 Python 函数:

import tensorflow as tf
def func():
    a = tf.constant([[10,10],[11.,1.]])
    b = tf.constant([[1.,0.],[0.,1.]])
    c = tf.matmul(a, b)
    return c
print(func().numpy())

由于 TF 2 默认以即时执行模式运行,所以 Python 函数 func() 会被当作 “普通” 函数处理。运行这段代码,会得到如下输出:

[[20. 30.]
 [22. 3.]]
2.2 有 @tf.function 的示例
import tensorflow as tf
@tf.function
def func():
    a = tf.constant([[10,10],[11.,1.]])
    b = tf.constant([[1.,0.],[0.,1.]])
    c = tf.matmul(a, b)
    return c
print(func().numpy())

这里定义了一个带有装饰器的 Python 函数。因为有 @tf.function 注解,Python 的 func() 函数会被封装在一个 tensorflow.python.eager.def_function.Function 对象中,Python 函数会被赋值给该对象的 .python_function 属性。当调用 func() 时,图构建过程就会启动,只有 Python 代码会被执行,函数的行为会被追踪,这样 TF 2 就能收集构建图所需的数据。输出如下:

[[20. 30.]
 [22.  3.]]
3. @tf.function 函数重载

函数重载指的是一个函数可以用不同的数据类型来调用。例如,我们可以定义一个重载的 “add” 函数,它既能对两个数字进行相加,也能对两个字符串进行拼接。下面的代码展示了如何定义一个可以用不同数据类型调用的装饰 Python 函数:

import tensorflow as tf
@tf.function
def add(a):
    return a + a 
print("Add 1:            ", add(1))
print("Add 2.3:          ", add(2.3))
print("Add string tensor:", add(tf.constant("abc")))
c = add.get_concrete_function(tf.TensorSpec(shape=None, 
dtype=tf.string))
c(a=tf.constant("a"))  

运行这段代码,会得到如下输出:

Add 1:             tf.Tensor(2, shape=(), dtype=int32)
Add 2.3:           tf.Tensor(4.6, shape=(), dtype=float32)
Add string tensor: tf.Tensor(b'abcabc', shape=(), dtype=string)
c: <tensorflow.python.eager.function.ConcreteFunction object at 
0x1209576a0>
4. TF 2 中的 AutoGraph

AutoGraph 是指将 Python 代码转换为图表示,这是 TF 2 中的一项重要新特性。实际上,AutoGraph 会自动应用于带有 @tf.function 装饰器的函数,这个装饰器能从 Python 函数创建可调用的图。AutoGraph 会把一部分 Python 语法转换为可移植、高性能且与语言无关的图表示,从而弥合 TF 1.x 和 TF 2.0 之间的差距。例如,若定义了一个名为 my_product() 的 Python 函数,可以用以下代码片段查看其自动生成的代码:

print(tf.autograph.to_code(my_product))

在 TF 2 中,Python 的 for/while 结构通过 tf.while_loop 实现( break continue 也支持), if 结构通过 tf.cond 实现, for _ in dataset 通过 dataset.reduce 实现。AutoGraph 对循环转换有一些规则:如果循环中的可迭代对象是张量, for 循环会被转换;如果 while 条件依赖于张量, while 循环会被转换。如果循环被转换,会用 tf.while_loop 动态 “展开”;对于 for x in tf.data.Dataset 这种特殊情况,会转换为 tf.data.Dataset.reduce 。如果循环未被转换,则会静态展开。

5. TF 2 中的算术运算
5.1 基本算术运算示例

下面的代码展示了如何在 TF 2 中执行算术运算:

import tensorflow as tf 
@tf.function # replace print() with tf.print()
def compute_values():
    a = tf.add(4, 2)
    b = tf.subtract(8, 6)
    c = tf.multiply(a, 3)
    d = tf.math.divide(a, 6)
    print(a) # 6
    print(b) # 2
    print(c) # 18
    print(d) # 1
compute_values()

运行这段代码,会得到如下输出:

tf.Tensor(6,   shape=(), dtype=int32)
tf.Tensor(2,   shape=(), dtype=int32)
tf.Tensor(18,  shape=(), dtype=int32)
tf.Tensor(1.0, shape=(), dtype=float64)
5.2 常量与变量的算术运算

下面的代码展示了如何执行涉及 TF 2 常量和变量的算术运算:

import tensorflow as tf 
v1 = tf.Variable([4.0, 4.0])
c1 = tf.constant([1.0, 2.0])
diff = tf.subtract(v1,c1)
print("diff:",diff)

运行这段代码,会得到如下输出:

diff: tf.Tensor([3. 2.], shape=(2,), dtype=float32)

不过,如果更新 v1 的值后再打印 diff 的值, diff 不会改变。你必须重新设置 diff 的值,就像在其他命令式编程语言中一样。下面的代码展示了这一点:

import tensorflow as tf 
v1 = tf.Variable([4.0, 4.0])
c1 = tf.constant([1.0, 2.0])
diff = tf.subtract(v1,c1)
print("diff1:",diff.numpy())
# diff is NOT updated:
v1.assign([10.0, 20.0])
print("diff2:",diff.numpy())
# diff is updated correctly:
diff = tf.subtract(v1,c1)
print("diff3:",diff.numpy())

运行这段代码,会得到如下输出:

diff1: [3. 2.]
diff2: [3. 2.]
diff3: [9. 18.]
6. TF 2 中的内置函数运算
6.1 基本数学运算示例

下面的代码展示了如何在 TF 图中执行额外的算术运算:

import tensorflow as tf 
PI = 3.141592
@tf.function # replace print() with tf.print()
def math_values():
    print(tf.math.divide(12,8))
    print(tf.math.floordiv(20.0,8.0))
    print(tf.sin(PI))
    print(tf.cos(PI))
    print(tf.math.divide(tf.sin(PI/4.), tf.cos(PI/4.)))
math_values()

运行这段代码,会得到如下输出:

1.5
tf.Tensor(2.0,            shape=(), dtype=float32)
tf.Tensor(6.2783295e-07,  shape=(), dtype=float32)
tf.Tensor(-1.0,           shape=(), dtype=float32)
tf.Tensor(0.99999964,     shape=(), dtype=float32)
6.2 使用更精确的 PI 值

下面的代码使用了更精确的 PI 值:

import tensorflow as tf 
import math as m
PI = tf.constant(m.pi)
@tf.function # replace print() with tf.print()
def math_values():
    print(tf.math.divide(12,8))
    print(tf.math.floordiv(20.0,8.0))
    print(tf.sin(PI))
    print(tf.cos(PI))
    print(tf.math.divide(tf.sin(PI/4.), tf.cos(PI/4.)))
math_values()

运行这段代码,会得到如下输出:

1.5
tf.Tensor(2.0,           shape=(), dtype=float32)
tf.Tensor(-8.742278e-08, shape=(), dtype=float32)
tf.Tensor(-1.0,          shape=(), dtype=float32)
tf.Tensor(1.0,           shape=(), dtype=float32)
7. TF 2 中的三角函数与指数函数计算
7.1 三角函数计算示例

下面的代码展示了如何在 TF 2 中计算三角函数值:

import tensorflow as tf
import math as m
PI = tf.constant(m.pi)
a = tf.cos(PI/3.)
b = tf.sin(PI/3.)
c = 1.0/a # sec(60)
d = 1.0/tf.tan(PI/3.) # cot(60)
@tf.function # this decorator is okay
def math_values():
    print("a:",a)
    print("b:",b)
    print("c:",c)
    print("d:",d)
math_values()

运行这段代码,会得到如下输出:

a: tf.Tensor(0.49999997, shape=(), dtype=float32)
b: tf.Tensor(0.86602545, shape=(), dtype=float32)
c: tf.Tensor(2.0000002,  shape=(), dtype=float32)
d: tf.Tensor(0.57735026, shape=(), dtype=float32)
7.2 指数函数计算示例

下面的代码展示了如何在 TF 2 中计算指数函数值:

import tensorflow as tf
a  = tf.exp(1.0)
b  = tf.exp(-2.0)
s1 = tf.sigmoid(2.0)
s2 = 1.0/(1.0 + b)
t2 = tf.tanh(2.0)
@tf.function # this decorator is okay
def math_values():
    print('a: ', a)
    print('b: ', b)
    print('s1:', s1)
    print('s2:', s2)
    print('t2:', t2)
math_values()

运行这段代码,会得到如下输出:

a:  tf.Tensor(2.7182817,  shape=(), dtype=float32)
b:  tf.Tensor(0.13533528, shape=(), dtype=float32)
s1: tf.Tensor(0.880797,   shape=(), dtype=float32)
s2: tf.Tensor(0.880797,   shape=(), dtype=float32)
t2: tf.Tensor(0.9640276,  shape=(), dtype=float32)
8. TF 2 中字符串的处理

下面的代码展示了如何在 TF 2 中处理字符串:

import tensorflow as tf
x1 = tf.constant("café")
print("x1:",x1)
tf.strings.length(x1)
print("")
len1 = tf.strings.length(x1, unit="UTF8_CHAR")
len2 = tf.strings.unicode_decode(x1, "UTF8")
print("len1:",len1.numpy())
print("len2:",len2.numpy())
print("")
# String arrays
x2 = tf.constant(["Café", "Coffee", "caffè", "咖啡"])
print("x2:",x2)
print("")
len3 = tf.strings.length(x2, unit="UTF8_CHAR")
print("len2:",len3.numpy())
print("")
r = tf.strings.unicode_decode(x2, "UTF8")
print("r:",r)

运行这段代码,会得到如下输出:

x1: tf.Tensor(b'caf\xc3\xa9', shape=(), dtype=string)
len1: 4
len2: [ 99  97 102 233]
x2: tf.Tensor([b'Caf\xc3\xa9' b'Coffee' b'caff\xc3\xa8' b'\
xe5\x92\x96\xe5\x95\xa1'], shape=(4,), dtype=string)
len2: [4 6 5 2]
r: <tf.RaggedTensor [[67, 97, 102, 233], [67, 111, 102, 102, 
101, 101], [99, 97, 102, 102, 232], [21654, 21857]]>
9. TF 2 中张量的操作

下面的代码展示了如何在 TF 2 中使用各种运算符处理张量:

import tensorflow as tf
x = tf.constant([[1., 2., 3.], [4., 5., 6.]])
print("x:", x)
print("")
print("x.shape:", x.shape)
print("")
print("x.dtype:", x.dtype)
print("")
print("x[:, 1:]:", x[:, 1:])
print("")
print("x[..., 1, tf.newaxis]:", x[..., 1, tf.newaxis])
print("")
print("x + 10:", x + 10)
print("")
print("tf.square(x):", tf.square(x))
print("")
print("x @ tf.transpose(x):", x @ tf.transpose(x))
m1 = tf.constant([[1., 2., 4.], [3., 6., 12.]])
print("m1:              ", m1 + 50)
print("m1 + 50:         ", m1 + 50)
print("m1 * 2:          ", m1 * 2)
print("tf.square(m1):   ", tf.square(m1))

运行这段代码,会得到如下输出:

x: tf.Tensor(
[[1. 2. 3.]
 [4. 5. 6.]], shape=(2, 3), dtype=float32)
x.shape: (2, 3)
x.dtype: <dtype: 'float32'>
x[:, 1:]: tf.Tensor(
[[2. 3.]
 [5. 6.]], shape=(2, 2), dtype=float32)
x[..., 1, tf.newaxis]: tf.Tensor(
[[2.]
 [5.]], shape=(2, 1), dtype=float32)
x + 10: tf.Tensor(
[[11. 12. 13.]
 [14. 15. 16.]], shape=(2, 3), dtype=float32)
tf.square(x): tf.Tensor(
[[ 1.  4.  9.]
 [16. 25. 36.]], shape=(2, 3), dtype=float32)
x @ tf.transpose(x): tf.Tensor(
[[14. 32.]
 [32. 77.]], shape=(2, 2), dtype=float32)
m1:               tf.Tensor(
[[51. 52. 54.]
 [53. 56. 62.]], shape=(2, 3), dtype=float32)
m1 + 50:          tf.Tensor(
[[51. 52. 54.]
 [53. 56. 62.]], shape=(2, 3), dtype=float32)
m1 * 2:           tf.Tensor(
[[ 2.  4.  8.]
 [ 6. 12. 24.]], shape=(2, 3), dtype=float32)
tf.square(m1):    tf.Tensor(
[[  1.   4.  16.]
 [  9.  36. 144.]], shape=(2, 3), dtype=float32)
10. TF 2 中二阶张量的操作
10.1 简单二阶张量操作示例

下面的代码展示了如何定义一个二阶 TF 张量并访问其中的元素:

import tensorflow as tf
arr2 = tf.constant([[1,2],[2,3]])
@tf.function
def compute_values():
    print('arr2: ',arr2)
    print('[0]:  ',arr2[0])
    print('[1]:  ',arr2[1])
compute_values()

运行这段代码,会得到如下输出:

arr2:   tf.Tensor(
[[1 2]
 [2 3]], shape=(2, 2), dtype=int32)
[0]:   tf.Tensor([1 2], shape=(2,), dtype=int32)
[1]:   tf.Tensor([2 3], shape=(2,), dtype=int32)
10.2 复杂二阶张量操作示例

下面的代码展示了如何定义一个更复杂的二阶 TF 2 张量并访问其中的元素:

import tensorflow as tf
arr3 = tf.constant([[[1,2],[2,3]],[[3,4],[5,6]]])
@tf.function # replace print() with tf.print()
def compute_values():
    print('arr3:   ',arr3)
    print('[1]:    ',arr3[1])
    print('[1,1]:  ',arr3[1,1])
    print('[1,1,0]:',arr3[1,1,0])
compute_values()

运行这段代码,会得到如下输出:

arr3:    tf.Tensor(
[[[1 2]
  [2 3]]
 [[3 4]
  [5 6]]], shape=(2, 2, 2), dtype=int32)
[1]:     tf.Tensor(
[[3 4]
 [5 6]], shape=(2, 2), dtype=int32)
[1,1]:   tf.Tensor([5 6], shape=(2,), dtype=int32)
[1,1,0]: tf.Tensor(5, shape=(), dtype=int32)
10.3 二阶张量乘法示例

下面的代码展示了如何在 TF 2 中对二阶张量进行乘法运算:

import tensorflow as tf
m1 = tf.constant([[3., 3.]])  # 1x2
m2 = tf.constant([[2.],[2.]]) # 2x1
p1 = tf.matmul(m1, m2)        # 1x1
@tf.function
def compute_values():
    print('m1:',m1)
    print('m2:',m2)
    print('p1:',p1)
compute_values()

通过以上这些示例,我们可以全面了解 TensorFlow 2 在函数定义、输出处理、张量操作、数学运算等方面的基本用法和特性。在实际应用中,我们可以根据具体需求灵活运用这些知识来构建和训练机器学习模型。

TensorFlow 2 基础与应用全解析

11. 总结与操作要点回顾

为了更清晰地理解和掌握前面所介绍的 TensorFlow 2 的各项操作,下面以表格形式总结关键操作及其要点:
| 操作类型 | 代码示例 | 要点说明 |
| — | — | — |
| 基础函数定义 | python @tf.function def compute_values(): a = tf.add(tf.constant(4), tf.constant(2)) return a result = compute_values() print("result:", result) | 使用 @tf.function 装饰器可将函数转换为图模式,提高执行效率;注意 print() tf.print() 输出的目标不同 |
| 函数重载 | python @tf.function def add(a): return a + a print("Add 1: ", add(1)) print("Add 2.3: ", add(2.3)) print("Add string tensor:", add(tf.constant("abc"))) | 一个函数可接受不同数据类型的参数,实现函数重载功能 |
| 算术运算 | python @tf.function def compute_values(): a = tf.add(4, 2) b = tf.subtract(8, 6) c = tf.multiply(a, 3) d = tf.math.divide(a, 6) print(a) print(b) print(c) print(d) compute_values() | 利用 tf.add tf.subtract tf.multiply tf.math.divide 等函数进行基本算术运算 |
| 常量与变量运算 | python v1 = tf.Variable([4.0, 4.0]) c1 = tf.constant([1.0, 2.0]) diff = tf.subtract(v1,c1) print("diff:",diff) | 变量更新后,相关运算结果需重新计算,否则结果不会改变 |
| 内置函数运算 | python PI = tf.constant(m.pi) @tf.function def math_values(): print(tf.math.divide(12,8)) print(tf.math.floordiv(20.0,8.0)) print(tf.sin(PI)) print(tf.cos(PI)) print(tf.math.divide(tf.sin(PI/4.), tf.cos(PI/4.))) math_values() | 可使用 tf.sin tf.cos 等内置函数进行数学运算,使用更精确的常量可提高计算精度 |
| 三角函数与指数函数计算 | python PI = tf.constant(m.pi) a = tf.cos(PI/3.) b = tf.sin(PI/3.) c = 1.0/a d = 1.0/tf.tan(PI/3.) @tf.function def math_values(): print("a:",a) print("b:",b) print("c:",c) print("d:",d) math_values() | 利用 tf.cos tf.sin tf.tan tf.exp 等函数进行三角函数和指数函数计算 |
| 字符串处理 | python x1 = tf.constant("café") len1 = tf.strings.length(x1, unit="UTF8_CHAR") len2 = tf.strings.unicode_decode(x1, "UTF8") print("len1:",len1.numpy()) print("len2:",len2.numpy()) | 使用 tf.strings.length tf.strings.unicode_decode 等函数处理字符串,注意字符编码和长度计算的单位 |
| 张量操作 | python x = tf.constant([[1., 2., 3.], [4., 5., 6.]]) print("x.shape:", x.shape) print("x.dtype:", x.dtype) print("x + 10:", x + 10) print("tf.square(x):", tf.square(x)) | 可通过 x.shape x.dtype 查看张量属性,使用 + tf.square 等进行张量运算 |
| 二阶张量操作 | python arr2 = tf.constant([[1,2],[2,3]]) print('arr2: ',arr2) print('[0]: ',arr2[0]) print('[1]: ',arr2[1]) | 定义二阶张量后,可通过索引访问其中的元素 |

12. 操作流程与注意事项

以下是使用 TensorFlow 2 进行常见操作的一般流程:
1. 导入必要的库

import tensorflow as tf
import math as m
  1. 定义常量和变量
# 定义常量
c1 = tf.constant([1.0, 2.0])
# 定义变量
v1 = tf.Variable([4.0, 4.0])
  1. 定义函数并进行运算
@tf.function
def compute_values():
    a = tf.add(4, 2)
    b = tf.subtract(8, 6)
    c = tf.multiply(a, 3)
    d = tf.math.divide(a, 6)
    return a, b, c, d

result_a, result_b, result_c, result_d = compute_values()
  1. 输出结果
print("a:", result_a)
print("b:", result_b)
print("c:", result_c)
print("d:", result_d)

在操作过程中,还需要注意以下几点:
- 图模式与即时执行模式 :使用 @tf.function 装饰器可将函数转换为图模式,提高执行效率,但在调试时可能需要暂时去掉装饰器,使用即时执行模式方便查看中间结果。
- 变量更新 :变量更新后,相关运算结果需重新计算,否则结果不会改变。
- 数据类型 :在进行运算时,要注意数据类型的一致性,避免出现类型不匹配的错误。

13. 流程图展示

下面是一个使用 Mermaid 绘制的流程图,展示了使用 TensorFlow 2 进行基本运算的流程:

graph TD;
    A[导入库] --> B[定义常量和变量];
    B --> C[定义函数];
    C --> D[进行运算];
    D --> E[输出结果];

这个流程图清晰地展示了从导入库开始,到定义常量和变量,再到定义函数进行运算,最后输出结果的整个过程。

14. 实际应用中的思考

在实际应用中,我们可以根据具体需求灵活运用 TensorFlow 2 的这些功能。例如,在构建机器学习模型时,我们可以利用张量操作来处理输入数据,使用数学运算进行模型的训练和优化,通过函数重载实现不同类型数据的处理。同时,要注意代码的性能优化,合理使用图模式和即时执行模式,以及正确处理变量和常量的更新。

通过对 TensorFlow 2 基础操作的学习和掌握,我们可以为进一步深入研究和应用机器学习打下坚实的基础。希望以上内容能帮助你更好地理解和使用 TensorFlow 2。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值