Tensor是Tensorflow中重要的對象。下面是Tensor的常用方法,后面還會寫一篇隨筆記錄Variable的用法。
1. 生成一個(常)Tensor對象
>>>A = tf.constant(4) >>>B = tf.constant([[1, 2], [3, 4])) >>>A <tf.Tensor: id=76, shape=(), dtype=int32, numpy=4> >>>B <tf.Tensor: id=77, shape=(2, 2), dtype=int32, numpy= array([[1, 2], [3, 4]], dtype=int32)>
Tensor對象和ndarray對象看起來很像但也有差別,一個最大的差別是Tensor是不可變的(immutable)。這意味着你永遠也無法隨心所欲的對Tensor進行賦值,只能新創建一個新的Tensor。
2. 和Ndarray的互相轉換
>>>B.numpy() array([[1, 2], [3, 4]], dtype=int32) >>>np.array(B) array([[1, 2], [3, 4]], dtype=int32) >>>D = np.array([[1, 2], [3, 4]]) >>>tf.convert_to_tensor(D, dtype='int32') <tf.Tensor: id=79, shape=(2, 2), dtype=int32, numpy= array([[1, 2], [3, 4]], dtype=int32)>
Tensorflow2引入了叫做Eager execution的機制,讓Tensor和ndarray具有一樣的運算靈活性。除了以上的轉換方式之外,任意的Tensorflow操作都可以生成(返回)Tensor對象。
3. 矩陣運算
>>>a = tf.constant([[1, 2], [3, 4]]) >>>b = tf.constant([[1, 1], [1, 1]]) # Could have also said `tf.ones([2,2])` >>>print(tf.add(a, b), "\n") tf.Tensor( [[2 3] [4 5]], shape=(2, 2), dtype=int32) >>>print(tf.multiply(a, b), "\n") tf.Tensor( [[1 2] [3 4]], shape=(2, 2), dtype=int32) >>>print(tf.matmul(a, b), "\n") tf.Tensor( [[3 3] [7 7]], shape=(2, 2), dtype=int32)
以上三個操作返回的都是Tensor對象,同時這三個操作可以使用'+', '*', '@'代替。
4. 三種常用的操作
>>>c = tf.constant([[4.0, 5.0], [10.0, 1.0]]) >>>print(tf.reduce_max(c)) # Find the largest value tf.Tensor(10.0, shape=(), dtype=float32) >>>print(tf.argmax(c)) # Find the index of the largest value tf.Tensor([1 0], shape=(2,), dtype=int64) >>>print(tf.nn.softmax(c)) # # Compute the softmax tf.Tensor( [[2.6894143e-01 7.3105860e-01] [9.9987662e-01 1.2339458e-04]], shape=(2, 2), dtype=float32)
三種看名字就能看出功能的操作,其中tf.reduce_XX()是tensorflow中降維的操作。類似的操作:'reduce_all', 'reduce_any', 'reduce_logsumexp', 'reduce_max', 'reduce_mean', 'reduce_min', 'reduce_prod', 'reduce_sum'。
5. Dtype轉換
>>>the_f64_tensor = tf.constant([2.2, 3.3, 4.4], dtype=tf.float64) >>>the_f16_tensor = tf.cast(the_f64_tensor, dtype=tf.float16) # Now, let's cast to an uint8 and lose the decimal precision >>>the_u8_tensor = tf.cast(the_f16_tensor, dtype=tf.uint8) >>>print(the_u8_tensor) tf.Tensor([2 3 4], shape=(3,), dtype=uint8)
numpy中可以使用astype()來進行轉換,Tensorflow中則使用tf.cast()方法來轉化不同數據類型的Tensor。
6. 廣播操作
Tensor的廣播操作和numpy中基本完全一樣,機制可以看這篇文章:https://jakevdp.github.io/PythonDataScienceHandbook/02.05-computation-on-arrays-broadcasting.html