tensorflow2.0基础API实战

一、引入tf基础API

tf.function是tensorflow2.0中一个重要的feature,它可以把普通的python代码转成tensorflow的图结构。

tf.function可以让eager exection默认打开,如果没有tf.function,用eager exection编写的代码无法保存模型的中间训练结果。

note:本文着眼于实战tf的基础api,目的是让读者学会使用基础api,如果读者对自定义层次、自定义损失函数以及@tf.function的使用与自定义求导感兴趣,可以参考博主的其他文章,另有文章详细介绍。、

二、实战基础API

1、tf.constant 常量

#tf.constant:常量
t = tf.constant([[1., 2., 3.], [4., 5., 6.]])

# index索引操作
print(t)
print(t[:, 1:]) #取出从第二列以后的数值
print(t[..., 1]) #把第二列取出来当成一个单独的tensor

输出显示: 

tf.Tensor(
[[1. 2. 3.]
 [4. 5. 6.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[2. 3.]
 [5. 6.]], shape=(2, 2), dtype=float32)
tf.Tensor([2. 5.], shape=(2,), dtype=float32)
# ops算子操作
t = tf.constant([[1., 2., 3.], [4., 5., 6.]])
print(t+10)
print(tf.square(t)) #平方
print(t @ tf.transpose(t)) #乘以它的转置

输出显示:  

tf.Tensor(
[[11. 12. 13.]
 [14. 15. 16.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[ 1.  4.  9.]
 [16. 25. 36.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[14. 32.]
 [32. 77.]], shape=(2, 2), dtype=float32)
# tensorflow -> numpy conversion
t = tf.constant([[1., 2., 3.], [4., 5., 6.]])
print(t.numpy())
print(np.square(t))
np_t = np.array([[1., 2., 3.], [4., 5., 6.]])
print(tf.constant(np_t))

输出显示: 

[[1. 2. 3.]
 [4. 5. 6.]]
[[ 1.  4.  9.]
 [16. 25. 36.]]
tf.Tensor(
[[1. 2. 3.]
 [4. 5. 6.]], shape=(2, 3), dtype=float64)
# Scalars,0维的tensorflow
t = tf.constant(2.718)
print(t.numpy())
print(t.shape) #0维的矩阵
2.718
()
# strings
t = tf.constant("cafe")
print(t)
print(tf.strings.length(t))
print(tf.strings.length(t, unit="UTF8_CHAR"))
print(tf.strings.unicode_decode(t, "UTF8"))

输出显示:  

tf.Tensor(b'cafe', shape=(), dtype=string)
tf.Tensor(4, shape=(), dtype=int32)
tf.Tensor(4, shape=(), dtype=int32)
tf.Tensor([ 99  97 102 101], shape=(4,), dtype=int32)
# string array
t = tf.constant(["cafe", "coffee", "咖啡"])
print(tf.strings.length(t)) 
print(tf.strings.length(t, unit="UTF8_CHAR")) #获得它UTF8编码时的长度
r = tf.strings.unicode_decode(t, "UTF8") #unicode->UTF8
print(r)

输出显示:   

tf.Tensor([4 6 6], shape=(3,), dtype=int32)
tf.Tensor([4 6 2], shape=(3,), dtype=int32)
<tf.RaggedTensor [[99, 97, 102, 101], [99, 111, 102, 102, 101, 101], [21654, 21857]]> 
# ragged tensor:不完整的n维矩阵
r = tf.ragged.constant([[11, 12], [21, 22, 23], [], [41]])
# index op
print(r)
print(r[1]) #取出第一行
print(r[1:2]) #取出一到n行,左闭右开区间,只取1,则第二列。

输出显示:   

<tf.RaggedTensor [[11, 12], [21, 22, 23], [], [41]]>
tf.Tensor([21 22 23], shape=(3,), dtype=int32)
<tf.RaggedTensor [[21, 22, 23]]>
# ops on ragged tensor
r = tf.ragged.constant([[11, 12], [21, 22, 23], [], [41]])
r2 = tf.ragged.constant([[51, 52], [], [71]])
print(tf.concat([r, r2], axis = 0))#在0维度上进行拼接,竖向拼接,4行+3行:结果为7行
#print(tf.concat([r, r2], axis = 1)) #在1维度上进行拼接,出错,即:横向拼接

输出显示:   

<tf.RaggedTensor [[11, 12], [21, 22, 23], [], [41], [51, 52], [], [71]]>
r = tf.ragged.constant([[11, 12], [21, 22, 23], [], [41]])
r3 = tf.ragged.constant([[13, 14], [15], [], [42, 43]])
print(tf.concat([r, r3], axis = 0)) #在0维度上进行拼接,即:竖向拼接
print(tf.concat([r, r3], axis = 1)) #在1维度上进行拼接,即:横向拼接

输出显示:   

<tf.RaggedTensor [[11, 12], [21, 22, 23], [], [41], [13, 14], [15], [], [42, 43]]>
<tf.RaggedTensor [[11, 12, 13, 14], [21, 22, 23, 15], [], [41, 42, 43]]>
#把ragged tensor转变成tensor,空闲部分用0补齐
print(r.to_tensor()) # 0永远在正常值的后面

输出显示:   

tf.Tensor(
[[11 12  0]
 [21 22 23]
 [ 0  0  0]
 [41  0  0]], shape=(4, 3), dtype=int32)
# sparse tensor:应用于一个二维矩阵大部分位置都是0,少部分值为1时。
s = tf.SparseTensor(indices = [[0, 1], [1, 0], [2, 3]], #坐标,有序
                    values = [1., 2., 3.], #值
                    dense_shape = [3, 4]) #矩阵大小

print(s)
print(tf.sparse.to_dense(s)) #将sparse tensor转成普通的tensor(转成密集矩阵)

输出显示:   

SparseTensor(indices=tf.Tensor(
[[0 1]
 [1 0]
 [2 3]], shape=(3, 2), dtype=int64), values=tf.Tensor([1. 2. 3.], shape=(3,), dtype=float32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64))
tf.Tensor(
[[0. 1. 0. 0.]
 [2. 0. 0. 0.]
 [0. 0. 0. 3.]], shape=(3, 4), dtype=float32)
# ops on sparse tensors
s = tf.SparseTensor(indices = [[0, 1], [1, 0], [2, 3]], #坐标,有序
                    values = [1., 2., 3.], #值
                    dense_shape = [3, 4]) #矩阵大小

s2 = s * 2.0
print(s2)

#加法运算会报错
try:
    s3 = s + 1
except TypeError as ex:
    print(ex)

s4 = tf.constant([[10., 20.],
                  [30., 40.],
                  [50., 60.],
                  [70., 80.]])
print(tf.sparse.sparse_dense_matmul(s, s4))

输出显示:   

SparseTensor(indices=tf.Tensor(
[[0 1]
 [1 0]
 [2 3]], shape=(3, 2), dtype=int64), values=tf.Tensor([2. 4. 6.], shape=(3,), dtype=float32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64))
unsupported operand type(s) for +: 'SparseTensor' and 'int'
tf.Tensor(
[[ 30.  40.]
 [ 20.  40.]
 [210. 240.]], shape=(3, 2), dtype=float32)
# sparse tensor
s5 = tf.SparseTensor(indices = [[0, 2], [0, 1], [2, 3]], #坐标,无序
                    values = [1., 2., 3.], #值
                    dense_shape = [3, 4]) #矩阵大小
print(s5) #可以正常打印
#print(tf.sparse.to_dense(s5)) #报错
s6 = tf.sparse.reorder(s5)
print(tf.sparse.to_dense(s6))

输出显示:   

SparseTensor(indices=tf.Tensor(
[[0 2]
 [0 1]
 [2 3]], shape=(3, 2), dtype=int64), values=tf.Tensor([1. 2. 3.], shape=(3,), dtype=float32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64))
tf.Tensor(
[[0. 2. 1. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 3.]], shape=(3, 4), dtype=float32)

 2、变量

# Variables
v = tf.Variable([[1., 2., 3.], [4., 5., 6.]])
print(v)
print(v.value()) #变成tensor
print(v.numpy())

输出显示:   

<tf.Variable 'Variable:0' shape=(2, 3) dtype=float32, numpy=
array([[1., 2., 3.],
       [4., 5., 6.]], dtype=float32)>
tf.Tensor(
[[1. 2. 3.]
 [4. 5. 6.]], shape=(2, 3), dtype=float32)
[[1. 2. 3.]
 [4. 5. 6.]]
# assign value
v.assign(2*v) #给变量重新赋值
print(v.numpy())
v[0, 1].assign(42) #给特定位置赋值
print(v.numpy())
v[1].assign([7., 8., 9.]) #给第一行赋值
print(v.numpy())

输出显示:   

[[ 2.  4.  6.]
 [ 8. 10. 12.]]
[[ 2. 42.  6.]
 [ 8. 10. 12.]]
[[ 2. 42.  6.]
 [ 7.  8.  9.]]
#变量的赋值只能用“assign”,不能用等号
try:
    v[1] = [7., 8., 9.]
except TypeError as ex:
    print(ex)

输出显示:   

 'ResourceVariable' object does not support item assignment

原创文章 46 获赞 49 访问量 2192

猜你喜欢

转载自blog.csdn.net/qq_41660119/article/details/105784100