張量(Tensor):多維數組(列表) 階:張量的維數
張量可以表示0階到n階數組(列表)
基本的數據類型
- tf.int,tf.float
- tf.bool
- tf.string
生成一個張量
-
如何創建一個張量
用法:tf.constant(張量內容,dtype=數據類型(可選))
例子:import tensorflow as tf #創建一個張量 a = tf.constant([1,5],dtype = tf.int64) print(a) print(a.dtype) print(a.shape) 輸出結果: tf.Tensor([1 5], shape=(2,), dtype=int64) #有幾個逗號說明是幾維張量 這個是一個一維張量,裏面有兩個值1和5 <dtype: 'int64'> (2,)
-
將numpy的數據類型轉換爲Tensor數據類型
用法:tf.convert_to_tensor(數據名,dtype=數據類型(可選))
例子:import tensorflow as tf import numpy as np a = np.arange(0,5) b = tf.convert_to_tensor(a,dtype=tf.int64) print(a) print(b) 輸出結果: [0 1 2 3 4] tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)
-
創建特殊的張量
a. 創建全爲0的張量:tf.zeros(維度)
b. 創建全爲1的張量:tf.ones(維度)
c. 創建全爲指定值的張量:tf.fill(維度,指定值)
維度:一維:直接寫個數
二維:用[行,列]
多維:用[n,m,j.k……]
例子:import tensorflow as tf 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([[9 9][9 9]], shape=(2, 2), dtype=int32)
-
生成隨機數
a. 生成正態分佈的隨機數,默認均值爲0,標準差爲1。 用法:tf.random.normal(維度,mean=均值,stddev = 標準差)
b. 生成截斷式正態分佈的隨機數。 用法: tf.random.truncated_normal(維度,mean=均值,stddev = 標準差)
c. 生成均勻分佈隨機數。 用法: tf.random.uniform(維度,minval = 最小值,maxval = 最大值)
例子:import tensorflow as tf d = tf.random.normal([2,2],mean = 0.5, stddev = 1) e = tf.random.truncated_normal([2,2],mean = 0.5, stddev = 1) f = tf.random.uniform([2,2],minval = 0.5, maxval = 1) print(d) print(e) print(f) 輸出結果: tf.Tensor([[-1.3744324 0.2684363 ][-0.14133292 1.949162 ]], shape=(2, 2), dtype=float32) tf.Tensor([[1.1253768 0.18428034][1.5979812 0.20128158]], shape=(2, 2), dtype=float32) tf.Tensor([[0.5172171 0.7131886 ][0.6884367 0.50856155]], shape=(2, 2), dtype=float32)
下面的是筆者的微信公衆號,歡迎關注,會持續更新c++、python、tensorflow、機器學習、深度學習等系列文章