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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章