常量与变量

Python 中的 TensorFlow 入门

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

什么是 TensorFlow?

  • 基于计算图的开源数值计算库
    • 由 Google Brain 团队开发
  • 高低阶 API
    • 加法、乘法、求导
    • 机器学习模型
  • TensorFlow 2.0 的重要变化
    • 默认即时执行
    • 使用 Keras 和 Estimators 构建模型
Python 中的 TensorFlow 入门

什么是张量?

  • 向量和矩阵的泛化
  • 数值的集合
  • 具有特定形状
Python 中的 TensorFlow 入门

什么是张量?

图片显示一片面包、被切成 9 块的面包片,以及一条面包。 来源:Public Domain Vectors

Python 中的 TensorFlow 入门

在 TensorFlow 中定义张量

import tensorflow as tf

# 0D 张量
d0 = tf.ones((1,))
# 1D 张量
d1 = tf.ones((2,))
# 2D 张量
d2 = tf.ones((2, 2))
# 3D 张量
d3 = tf.ones((2, 2, 2))
Python 中的 TensorFlow 入门

在 TensorFlow 中定义张量

# 打印 3D 张量
print(d3.numpy())
[[[1. 1.]
  [1. 1.]]

 [[1. 1.]
  [1. 1.]]]
Python 中的 TensorFlow 入门

在 TensorFlow 中定义常量

  • 常量是最简单的张量类型
    • 不可训练
    • 维度任意
from tensorflow import constant

# 定义 2x3 常量。
a = constant(3, shape=[2, 3])
# 定义 2x2 常量。
b = constant([1, 2, 3, 4], shape=[2, 2])
Python 中的 TensorFlow 入门

用便捷函数定义常量

操作 示例
tf.constant() constant([1, 2, 3])
tf.zeros() zeros([2, 2])
tf.zeros_like() zeros_like(input_tensor)
tf.ones() ones([2, 2])
tf.ones_like() ones_like(input_tensor)
tf.fill() fill([3, 3], 7)
Python 中的 TensorFlow 入门

定义并初始化变量

import tensorflow as tf

# 定义变量
a0 = tf.Variable([1, 2, 3, 4, 5, 6], dtype=tf.float32)
a1 = tf.Variable([1, 2, 3, 4, 5, 6], dtype=tf.int16)
# 定义常量
b = tf.constant(2, tf.float32)
# 计算它们的乘积
c0 = tf.multiply(a0, b)
c1 = a0*b
Python 中的 TensorFlow 入门

Passons à la pratique !

Python 中的 TensorFlow 入门

Preparing Video For Download...