TensorFlow學習 常用方法

2021-10-24 18:48:40 字數 2940 閱讀 1380

表示scalar:標量

.numpy()方法可以把tensor轉化為numpy型別

.ndim 檢視維度

.shape形狀

.is_tensor(b) 判斷是不是tensor(isinstance(a,tf.tensor))

tf.convert_to_tensor(a,dtype = tf.int32)把a轉成tnesor

tf.cast(aa,dtype = tf.float32)專門用來資料型別轉換的

tf.zeros()中括號裡面是shape

tf.zeros_like(a)返回乙個和a一樣shape的zeros

tf.ones()

tf.ones_like(a)

tf.fill([2,2],2)返回乙個2行2列的tensor,全部填充2

tf.random.normal([2,2],mean = 1,stddev = 1)兩行兩列的tensor,在n(1,1)中取樣

tf.random.truncated_normal([2,2],mean = 1,stddev = 1)截斷的正態分佈取樣

tf.random.uniform([2,2],minval = 0,maxval = 1,dtype = float32)均勻分布,這裡在0-1之間取樣

tf.random.shuffle(a)打散a中的樣本順序

tf.one_hot(y,depth = 10) depth表示位數

tf.keras.losses.mes(y,out)得到每乙個樣本的均值

tf.reduce_mean(tensor,axis=none)計算張量tensor沿著指定的數軸(tensor的某一維度)上的的平均值,主要用作降維或者計算tensor(影象)的平均值。

numpy方式的索引:

a.shape out:tensorshape(([4,28,28,3])

a[0,1,2,3].shape 1

a[:,:14,:14,:] out:tensorshape([4,14,14,3]

a[:,0:28:2,0:28:2,:].shape out:tensorshape([4,14,14,3])

a[:,::2,::2,:].shape out:tensorshape([4,14,14,3])

start: end:step ::step

a.shape out:tensorshape(([2,4,28,28,3])

a[0,…].shape out:tensorshape([4,28,28,3])

a[…,0].shape out:tensorshape([2,4,28,28])

a[0,…,2].shape out:tensorshape([4,28,28])

.gather()

a.shape = [4,43,8]

tf.gather(a,axis = 0,indices = [2,3]).shape

out:[2,43,8]

取a的第0個維度上的第2,3行。gather可以取樣到任何乙個維度的任意行的組合,gather可以重複使用達到更加細緻的篩選,但gather每次只能在同乙個維度上隨意取gather_nd可以在多個維度上取樣

gather_nd(a,[0,1,2]).shape

gather_nd(a,[[1,2,3],[4,2,1],[1.4.2]]) 取了三個任意維度都不同的樣本

gather(a,[0,0,1,1,2,2])可以擴充維度,複製

tf.reshape(a,[5,4,53]) //把a轉置

tf.transpose(a,perm = [0,1,3,2]) //維度改變為0維度,1維度,3維度,2維度

增加維度tf.expand_dims(a,axis = 3)表示在3維前面增加乙個維度,

壓縮維度

expandim(a,axis = 0)擴充乙個維度

tf.tile() 對擴充的維度複製,產生到記憶體

broadcasting:沒有產生資料到記憶體,但可以計算。當乙個高維度和乙個低緯度計算的時候,會預設擴充低緯度適用到高維度上,如[4,32,8]+[5.0](標量)預設所有的都加5;如果是向量就加對應位。這個向量得是8,因為預設和【4,32,8】的8匹配。右邊維度開始對齊,維度沒有或者維度為1的才可以broadcasting

tf的log只有以e為底數的

矩陣相乘 a@b 或者 tf.matmul(a,b)

TensorFlow學習之常用函式

tensorflow的設計理念稱之為計算流圖,在編寫程式時,首先構築整個系統的graph,並不會直接生效。然後,在實際的執行時,啟動乙個session,程式才會真正的執行。很多python程式的底層為c語言或者其他語言,執行一行指令碼,就要切換一次,這樣做的好處就是 避免反覆地切換底層程式實際執行的...

TensorFlow學習日記(4) 線性回歸方程

今天進行了線性回歸方程的簡單程式設計,如下 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt 隨機生成1000個點,圍繞在y 0.1x 0.3的直線周圍 num points 1000 vectors...

tensorflow常用函式

1.variable 主要在於一些可訓練變數 trainable variables 比如模型的權重 weights 或者偏執值 bias 1 宣告時,必須提供初始值 2 在真實訓練時,其值是會改變的,自然事先需要指定初始值 weights tf.variable tf.random normal ...