天天看点

tensorflow2------基础API的使用

 这里主要介绍了tensorflow中常量和变量的使用。

常量使用的是tf.constant或tf.ragged.constant来创建

变量使用的是tf.Variable来创建

import matplotlib as mpl #画图用的库
import matplotlib.pyplot as plt
#下面这一句是为了可以在notebook中画图
%matplotlib inline
import numpy as np
import sklearn   #机器学习算法库
import pandas as pd #处理数据的库   
import os
import sys
import time
import tensorflow as tf

from tensorflow import keras   #使用tensorflow中的keras
#import keras #单纯的使用keras

print(tf.__version__)
print(sys.version_info)
for module in mpl, np, sklearn, pd, tf, keras:
    print(module.__name__, module.__version__)



2.0.0
sys.version_info(major=3, minor=6, micro=9, releaselevel='final', serial=0)
matplotlib 3.1.2
numpy 1.18.0
sklearn 0.21.3
pandas 0.25.3
tensorflow 2.0.0
tensorflow_core.keras 2.2.4-tf
           
t = tf.constant([[1.,2.,3.],[4.,5.,6.]])
print(t) #这里输出的是 一个 tensor
print(t[:,1:]) #输出 第二列之后的矩阵tensor
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算子操作
print(t+10)
print(tf.square(t))
print(tf.transpose(t))#transpose表示转置



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(
[[1. 4.]
 [2. 5.]
 [3. 6.]], shape=(3, 2), dtype=float32)
           
#tensorflow与numpy相互转换
print(t.numpy()) #调用numpy方法将 矩阵 直接取出
print(np.square(t))
np_t=np.array([[7.,8.,9.],[6.,5.,4.]])
print(tf.constant(np_t))



[[1. 2. 3.]
 [4. 5. 6.]]
[[ 1.  4.  9.]
 [16. 25. 36.]]
tf.Tensor(
[[7. 8. 9.]
 [6. 5. 4.]], shape=(2, 3), dtype=float64)
           
#对于0维数据(也就是一个值)
#scalars
t=tf.constant(2.55)
print(t)
print(t.shape)#shape为空括号,即0维
print(t.numpy())

t2=tf.constant([1.,2.])
print(t2.numpy())
print(t2.shape)#shape为2维



tf.Tensor(2.55, shape=(), dtype=float32)
()
2.55
[1. 2.]
(2,)
           
#strings
t=tf.constant("abcdefg")
print(t)
print(tf.strings.length(t)) #t的长度
print(tf.strings.length(t,unit="UTF8_CHAR"))#utf8编码时的长度
print(tf.strings.unicode_decode(t,"UTF8"))#将字符串转换为utf8编码
print(t.numpy())




tf.Tensor(b'abcdefg', shape=(), dtype=string)
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor(7, shape=(), dtype=int32)
tf.Tensor([ 97  98  99 100 101 102 103], shape=(7,), dtype=int32)
b'abcdefg'
           
#strings array 存储一个数组的字符串
t=tf.constant(["abc","defgh","ij","深度学习"])
print(t)
print(tf.strings.length(t))
print(tf.strings.length(t,unit="UTF8_CHAR"))
print(tf.strings.unicode_decode(t,"UTF8"))#tf.RaggedTensor表示不规则的n维矩阵,即矩阵的每一行长度不同



tf.Tensor([b'abc' b'defgh' b'ij' b'\xe6\xb7\xb1\xe5\xba\xa6\xe5\xad\xa6\xe4\xb9\xa0'], shape=(4,), dtype=string)
tf.Tensor([ 3  5  2 12], shape=(4,), dtype=int32)
tf.Tensor([3 5 2 4], shape=(4,), dtype=int32)
<tf.RaggedTensor [[97, 98, 99], [100, 101, 102, 103, 104], [105, 106], [28145, 24230, 23398, 20064]]>
           
#ragged tensor
r=tf.ragged.constant([[1,2],[3,4,5],[],[8]])
print(r)
print(r[0])
print(r[1])

print(r[0:1])
print(r[2:])#取第二个数组之后的所有(不包含第二个)
print(r[:2])#取第二个数组之前的所有(包含第二个)
print(r[1:2])#左闭右开区间,只取第二个数组



<tf.RaggedTensor [[1, 2], [3, 4, 5], [], [8]]>
tf.Tensor([1 2], shape=(2,), dtype=int32)
tf.Tensor([3 4 5], shape=(3,), dtype=int32)
<tf.RaggedTensor [[1, 2]]>
<tf.RaggedTensor [[], [8]]>
<tf.RaggedTensor [[1, 2], [3, 4, 5]]>
<tf.RaggedTensor [[3, 4, 5]]>
           
#ops on ragged tensor
r2=tf.ragged.constant([[51,52],[],[71]])
print(r2)
print(tf.concat([r,r2],axis=0))#在r后面拼接r2



<tf.RaggedTensor [[51, 52], [], [71]]>
<tf.RaggedTensor [[1, 2], [3, 4, 5], [], [8], [51, 52], [], [71]]>
           
r3=tf.ragged.constant([[88,22],[11],[32],[23,34,56]])
print(tf.concat([r,r3],axis=1))#axis为1时,r矩阵中对应行追加r3中对应行数值,所以必须保证r、r3是同行数的



<tf.RaggedTensor [[1, 2, 88, 22], [3, 4, 5, 11], [32], [8, 23, 34, 56]]>
           
#将ragged tensor转换为普通的tensor
print(r2.to_tensor())#其他位补零即可



tf.Tensor(
[[51 52]
 [ 0  0]
 [71  0]], shape=(3, 2), dtype=int32)
           
#只用几个特性(参数)来描述一个稀疏矩阵的张量就叫做稀疏张量
#sparse tensor稀疏张量,tf.SparseTensor就用了三个维度:indices,values,dense_shape来描述一个稀疏矩阵
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))#转换为一般的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 tensor
s2=s*0.2
print(s2)
print(tf.sparse.to_dense(s2))

#sparse tensor不能直接使用加法运算
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))#将 sparse tensor与 普通tensor矩阵 做乘法



SparseTensor(indices=tf.Tensor(
[[0 1]
 [1 0]
 [2 3]], shape=(3, 2), dtype=int64), values=tf.Tensor([0.2 0.4 0.6], shape=(3,), dtype=float32), dense_shape=tf.Tensor([3 4], shape=(2,), dtype=int64))
tf.Tensor(
[[0.  0.2 0.  0. ]
 [0.4 0.  0.  0. ]
 [0.  0.  0.  0.6]], shape=(3, 4), dtype=float32)
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]],# indices必须要顺序排列,不然直接调用to_dense会报错,可以使用reorder
                  values=[1.,2.,3.],dense_shape=[3,4])
print(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)
           
#前面说的都是常量,使用的是tf.constant或tf.ragged.constant创建
#接下来将变量Variables
v=tf.Variable([[1.,2.,3.],
               [4.,5.,6.]])
print(v)#打印变量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)#矩阵第0行第1列重新赋值为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.]]
           
#不能用等于号赋值
try:
    v[1]=[7.,8.,9.]
except TypeError as ex:
    print(ex)



'ResourceVariable' object does not support item assignment
           

继续阅读