Tensorflow 2.0 基础用法(适合初入学习)


1. 数据类型

  • 整数,tf.int32,tf.int64
  • 浮点数,tf.float32,tf.float64
  • 布尔值,tf.bool
  • 字符串,tf.string

2. 张量创建

2.1 tf.constant

创建常量的张量

官方用法:

tf.constant(
    value, dtype=None, shape=None, name='Const'
) -> Union[tf.Operation, ops._EagerTensorBase]

示例:

# 创建常数张量a,0维张量
a = tf.constant(1, dtype=tf.int64)

# 创建常数张量b,1维张量
b = tf.constant([1, 5], dtype=tf.int64)

# 创建常数张量c,2维张量
c = tf.constant([[1, 5]], dtype=tf.int64)
print(a)
print(b)
print(c)

# 输出
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor([1 5], shape=(2,), dtype=int64)
tf.Tensor([[1 5]], shape=(1, 2), dtype=int64)
# 用 numpy 创建
a = np.array([[1, 2, 3], [4, 5, 6]])
b = tf.constant(a)
print(b)

# 输出
tf.Tensor(
[[1 2 3]
 [4 5 6]], shape=(2, 3), dtype=int64)

2.2 tf.zeros

创建全是0的张量

官方用法:

tf.zeros(
    shape,
    dtype=tf.dtypes.float32,
    name=None,
    layout=None
)

示例:

# 创建2维张量
a = tf.zeros([3, 4], tf.int32)
print(a)

# 输出
tf.Tensor(
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]], shape=(3, 4), dtype=int32)

2.3 tf.ones

创建全是1的张量

官方用法:

tf.ones(
    shape,
    dtype=tf.dtypes.float32,
    name=None,
    layout=None
)

示例:

a = tf.ones([3, 4], tf.int32)
print(a)

# 输出
tf.Tensor(
[[1 1 1 1]
 [1 1 1 1]
 [1 1 1 1]], shape=(3, 4), dtype=int32)

2.4 tf.eye

创建一个单位矩阵(张量)

官方用法:

tf.eye(
    num_rows,
    num_columns=None,
    batch_shape=None,
    dtype=tf.dtypes.float32,
    name=None
)

示例:

# 创建一个单位矩阵a,2行*2列
a = tf.eye(2)
print(a)

# 创建一个张量,3*单位矩阵(3行*3列的单位矩阵)
b = tf.eye(3, batch_shape=[3])
print(b)

# 这个看输出就知道了,解释起来费劲
c = tf.eye(2, num_columns=3)
print(c)

# 输出
tf.Tensor(
[[1. 0.]
 [0. 1.]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[[1. 0. 0.]
  [0. 1. 0.]
  [0. 0. 1.]]

 [[1. 0. 0.]
  [0. 1. 0.]
  [0. 0. 1.]]

 [[1. 0. 0.]
  [0. 1. 0.]
  [0. 0. 1.]]], shape=(3, 3, 3), dtype=float32)
tf.Tensor(
[[1. 0. 0.]
 [0. 1. 0.]], shape=(2, 3), dtype=float32)

2.5 tf.fill

创建一个张量,张量的值都用指定的数去填充

官方用法:

tf.fill(
    dims, value, name=None, layout=None
)

示例:

a = tf.fill([3, 4], 6)
print(a)

# 输出
tf.Tensor(
[[6 6 6 6]
 [6 6 6 6]
 [6 6 6 6]], shape=(3, 4), dtype=int32)

2.6 tf.one_hot

根据外部的值创建一个one_hot张量

官方用法:

tf.one_hot(
    indices,
    depth,
    on_value=None,
    off_value=None,
    axis=None,
    dtype=None,
    name=None
)

示例:

indices = [0, 1, 2]
a = tf.one_hot(indices, 3) 
print(a)
# 输出
# 解释:输入是indices,深度为3。那么indices第一个元素0对应于输出的[1,0,0]
# 表示第一行第一个位置存在0
tf.Tensor(
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]], shape=(3, 3), dtype=float32)

b = tf.one_hot(indices, 5)
print(b)
# 输出
# 解释:相比于a,深度增加了2;由于indices元素只有3,所以多余的填为0即可
tf.Tensor(
[[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]], shape=(3, 5), dtype=float32)

c = tf.one_hot([0,1,1,2,2], 3)
print(c)
# 输出
tf.Tensor(
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [0. 0. 1.]], shape=(5, 3), dtype=float32)

2.7 tf.random.normal

创建一个正太分布的张量

官方用法:

tf.random.normal(
    shape,
    mean=0.0,
    stddev=1.0,
    dtype=tf.dtypes.float32,
    seed=None,
    name=None
)

正太分布:
f ( x ) = 1 δ 2 π e − ( x − μ ) 2 2 δ 2 f(x) = \frac1{\delta\sqrt{2\pi}}e^{-\frac{(x-\mu)^2}{2\delta^2}} f(x)=δ2π 1e2δ2(xμ)2

示例:

tf.random.set_seed(5)
a = tf.random.normal([4], 0, 1, tf.float32)
print(a)

# 输出
tf.Tensor([-0.18030666 -0.95028627 -0.03964049 -0.7425406 ], shape=(4,), dtype=float32)
)
tf.random.set_seed(5)
a = tf.random.normal([2, 2], 0, 1, tf.float32)
print(a)

# 输出
# 解释,整个张量拉平就构成了正太分布的所有数
tf.Tensor(
[[-0.18030666 -0.95028627]
 [-0.03964049 -0.7425406 ]], shape=(2, 2), dtype=float32)

2.8 tf.random.truncated_normal

创建一个正太分布的张量,但是 |生成的数 - 平均值| <= 2倍标准差

官方用法:

tf.random.truncated_normal(
    shape,
    mean=0.0,
    stddev=1.0,
    dtype=tf.dtypes.float32,
    seed=None,
    name=None
)

示例:

tf.random.set_seed(5)
a = tf.random.truncated_normal([3, 4], 0, 1, tf.float32)
print(a)

# 输出
tf.Tensor(
[[-0.18030666 -0.95028627 -0.03964049 -0.7425406 ]
 [-0.25727183 -0.24710387  0.65812224  0.07492667]
 [-0.34847555 -1.1778127   0.6852275  -1.0851706 ]], shape=(3, 4), dtype=float32)

3. 张量变换

3.1 tf.reshape

变换张量的形状
官方用法:

tf.reshape(
    tensor, shape, name=None
)
# shape 表示变换后的形状;-1表示拉平到1维张量

示例:

tf.reshape([1, 2, 3], [2, 2])
# 输出,报错!因为原始一共就3个数,变换的形状却是2*2=4,大于3
InvalidArgumentError: ... Input to reshape is a tensor with 3 values, but the requested shape has 4 [Op:Reshape]
t = [[1, 2, 3],
     [4, 5, 6]]
a = tf.reshape(t, [3, 2])
print(a)

# 输出
tf.Tensor(
[[1 2]
 [3 4]
 [5 6]], shape=(3, 2), dtype=int32)
t = [[[1, 2, 3],
     [4, 5, 6]]]
a = tf.reshape(t, -1)
print(a)

# 输出,拉平到1维
tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32)

3.2 tf.expand_dims

拓展一个维度

tf.expand_dims(
    input, axis, name=None
)
# 如果input的维度是D,那么axis取值范围[-(D+1), D]

示例:

t = [[1, 2, 3],
     [4, 5, 6]]
a = tf.expand_dims(t, 0) # 等同于 a = tf.expand_dims(t, -3)
print(a)

# 输出,原先shape=(2, 3),
# 在 axis=0,即第0维前插入一个维度之后,变成 shape=(1, 2, 3)
tf.Tensor(
[[[1 2 3]
  [4 5 6]]], shape=(1, 2, 3), dtype=int32)
t = [[1, 2, 3],
     [4, 5, 6]]
a = tf.expand_dims(t, 1) # 等同于 a = tf.expand_dims(t, -2)
print(a)

# 输出,原先shape=(2, 3),
# 在 axis=1,即第1维前插入一个维度之后,变成 shape=(2, 1, 3)
tf.Tensor(
[[[1 2 3]]

 [[4 5 6]]], shape=(2, 1, 3), dtype=int32)
t = [[1, 2, 3],
     [4, 5, 6]]
a = tf.expand_dims(t, 2) # 等同于 a = tf.expand_dims(t, -1)
print(a)

# 输出,原先shape=(2, 3),
# 在 axis=2,即第2维前插入一个维度之后,变成 shape=(2, 3, 1)
tf.Tensor(
[[[1]
  [2]
  [3]]

 [[4]
  [5]
  [6]]], shape=(2, 3, 1), dtype=int32)

4. 常用函数

4.1 tf.shape

以张量形式返回输入张量的形状,注意返回的也是张量!

官方用法:

tf.shape(
    input, out_type=None, name=None
)

示例:

t = tf.constant([[[1, 1, 1], [2, 2, 2]], 
				[[3, 3, 3], [4, 4, 4]]])
print(tf.shape(t))
# 输出
tf.Tensor([2 2 3], shape=(3,), dtype=int32)

4.2 tf.size

返回张量包含的元素数量,注意返回的也是张量!

官方用法:

tf.size(
    input, out_type=None, name=None
)

示例:

t = tf.constant([[[1, 1, 1], [2, 2, 2]], 
				[[3, 3, 3], [4, 4, 4]]])
print(tf.size(t))
# 输出
tf.Tensor(12, shape=(), dtype=int32)

4.3 tf.rank

返回张量的秩

官方用法:

tf.rank(
    input, name=None
)

示例:

t = tf.constant([[[1, 1, 1], [2, 2, 2]], 
				[[3, 3, 3], [4, 4, 4]]])
print(tf.rank(t))  
## 输出
tf.Tensor(3, shape=(), dtype=int32)

4.4 tf.gather

根据索引以及axis,抽取张量数据。

官方用法:

tf.gather(
    params, indices, validate_indices=None, axis=None, batch_dims=0, name=None
)

示例:

params = tf.constant(['p0', 'p1', 'p2', 'p3', 'p4', 'p5'])
a = tf.gather(params, 3).numpy()
print(a)

# 输出
b'p3'
params = tf.constant(['p0', 'p1', 'p2', 'p3', 'p4', 'p5'])
indices = [2, 0, 2, 5]
a = tf.gather(params, indices).numpy()
print(a)

# 输出
[b'p2' b'p0' b'p2' b'p5']
params = tf.constant([[0, 1.0, 2.0],
                      [10.0, 11.0, 12.0],
                      [20.0, 21.0, 22.0],
                      [30.0, 31.0, 32.0]])
a = tf.gather(params, indices=[3,1]).numpy()
print(a)
# 输出
[[30. 31. 32.]
 [10. 11. 12.]]

b = tf.gather(params, indices=[2,1], axis=1).numpy()
print(b)
# 输出
[[ 2.  1.]
 [12. 11.]
 [22. 21.]
 [32. 31.]]

4.5 tf.matmul

矩阵相乘

官方用法:

tf.matmul(
    a,
    b,
    transpose_a=False,
    transpose_b=False,
    adjoint_a=False,
    adjoint_b=False,
    a_is_sparse=False,
    b_is_sparse=False,
    output_type=None,
    name=None
)

示例:

a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
c = tf.matmul(a, b)
print(c)
# 输出
tf.Tensor(
[[ 58  64]
 [139 154]], shape=(2, 2), dtype=int32)

5. 参考

Tensorflow用法

欢迎关注本人,我是喜欢搞事的程序猿; 一起进步,一起学习;

欢迎关注知乎:SmallerFL

也欢迎关注我的wx公众号:一个比特定乾坤

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SmallerFL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值