PKU TensorFlow 張量生成

2021-10-14 18:50:11 字數 2348 閱讀 2859

判斷張量是幾階的,就看其最左邊有幾個方括號

tf.constant(張量內容,dtype=資料型別(可選)

)

import tensorflowas tfa=tf.constant([1

,5],dtype=tf.int64)

print

(a)print

(a.dtype)

print

(a.shape)

如果去掉dtype項,不同電腦環境不同導致預設值不同,可能導致後續程式bug

tf. convert_to_tensor(資料名,dtype=資料型別(可選)

)

import tensorflowas tf

import numpyas np

a = np.arange(0,

5)b = tf.convert_to_tensor( a, dtype=tf.int64 )

print

(a)print

(b)

建立全為0的張量

tf. zeros(維度)
建立全為1的張量

tf. ones(維度)
建立全為指定值的張量

tf. fill(維度,指定值)
維度:

一維直接寫個數

二維用[行,列]

多維用[n,m,j,k……]

例子:

a = tf.zeros([2

,3])

b = tf.ones(4)

c = tf.fill([2

,2],

9)print

(a)print

(b)print

(c)

執行結果:

tf.tensor([[

0.0.

0.][

0.0.

0.]]

, shape=(2

,3), dtype=float32)

tf.tensor([1

.1.1

.1.]

, shape=(4

,), dtype=float32)

tf.tensor([[

99][

99]]

, shape=(2

,2), dtype=int32)

生成正態分佈的隨機數,預設均值為0,標準差為1

tf. random.normal(維度,mean=均值,stddev=標準差)
生成截斷式正態分佈的隨機數

tf. random.truncated_normal (維度,mean=均值,stddev=標準差)
在tf.truncated_normal中如果隨機生成資料的取值在(μ-2σ,μ+2σ)之外則重新進行生成,保證了生成值在均值附近。

生成均勻分布隨機數[ minval, maxval)

tf. random. uniform(維度,minval=最小值,maxval=最大值)
例子:

d = tf.random.normal([2

,2], mean=

0.5, stddev=1)

print

(d)e = tf.random.truncated_normal([2

,2], mean=

0.5, stddev=1)

print

(e)

執行結果:

tf.tensor([[

0.7925745

0.643315][

1.4752257

0.2533372]]

, shape=(2

,2), dtype=float32)

tf.tensor([[

1.3688478

1.0125661][

0.17475659

-0.02224463]]

, shape=(2

,2), dtype=float32)

21

pytorch 張量 張量的生成

張量的生成 import torch import numpy as np 使用tensor.tensor 函式構造張量 a torch.tensor 1.0,1.0 2.2 print a 獲取張量的維度 print 張量的維度 a.shape 獲取張量的形狀大小 print 張量的大小 a.si...

pytorch 張量 張量的資料型別

張量定義 import torch torch.tensor 1.2 3.4 dtype 獲取張量的資料型別,其中torch.tensor 函式生成乙個張量 torch.float32 torch.set default tensor type torch.doubletensor 設定張量的預設資...

tensorflow 中檢視張量值和張量大小

通過with tf.session assess print sess.run y 即可列印出變數的值。下面給出例子importnumpyasnp importtensorflowastf x tf.constant 1,2,3,4,5,6 y tf.reshape x,2,3 withtf.ses...