tensorflow2.0 基礎一 常用數據類型及轉換

Tensor 是什麼

scalar: 1.1
vector: [1.1],[1.1,2.2,...]
matrix: [[1.1,2.2],[3.3,4.4],[5.5,6.6]]
tensor: rank > 2

以上都可以叫做tensor

TF數據類型

  • int, float, double
  • bool
  • string

Create Tensor

In[3]: tf.constant(1)
Out[3]: <tf.Tensor: id=0, shape=(), dtype=int32, numpy=1>

In[4]: tf.constant(1.)
Out[4]: <tf.Tensor: id=6, shape=(), dtype=float32, numpy=1.0>

In[5]: tf.constant(2.2,dtype=tf.int32)
Out[5]: TypeError: Cannot convert provided value to EagerTensor. Provided value: 2.2 Requested dtype: int32

In[6]: tf.constant(2., dtype=tf.double)
Out[6]: <tf.Tensor: id=25, shape=(), dtype=float64, numpy=2.0>

In[7]: tf.constant([True,False])
Out[7]: <tf.Tensor: id=39, shape=(2,), dtype=bool, numpy=array([ True, False])>

In[8]: tf.constant('hello, world.')
Out[8]: <tf.Tensor: id=56, shape=(), dtype=string, numpy=b'hello, world.'>

Tensor Property

在這裏插入圖片描述

Check Tensor Type

在這裏插入圖片描述

Convert 轉換

在這裏插入圖片描述

bool int

在這裏插入圖片描述

tf.Variable

在這裏插入圖片描述
特別注意tf.Variable 通過isinstance判斷是否爲tensor會返回False,所以儘量使用tf.is_tensor。

To numpy

在這裏插入圖片描述

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