如何在 Python 中使用 Tensorflow 對矩陣的特定元素/行求和?


Tensorflow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用以實現演算法、深度學習應用程式等等。它用於研究和生產目的。

它具有最佳化技術,有助於快速執行復雜的數學運算。這是因為它使用了 NumPy 和多維陣列。這些多維陣列也稱為“張量”。該框架支援使用深度神經網路。它具有高度可擴充套件性,並附帶許多流行的資料集。它使用 GPU 計算並自動管理資源。

可以使用以下程式碼行在 Windows 上安裝“tensorflow”包:

pip install tensorflow

張量是 TensorFlow 中使用的資料結構。它有助於連線流圖中的邊。此流圖稱為“資料流圖”。張量只不過是多維陣列或列表。

我們將使用 Jupyter Notebook 來執行這些程式碼。可以使用“pip install tensorflow”在 Jupyter Notebook 上安裝 TensorFlow。

以下是一個示例:

示例

import tensorflow as tf
import numpy as np

matrix_1 = tf.Variable([[1,2,3],[4,5,8],[9,10,0]])
print("The matrix is ")
print (matrix_1)

print("The sum of all elements ")
result = tf.reduce_sum(matrix_1)
print(result)
print("The sum of specific rows is")
result = tf.reduce_sum(matrix_1, 1)
print(result)

輸出

The matrix is
<tf.Variable 'Variable:0' shape=(3, 3) dtype=int32, numpy=
array([[ 1, 2, 3],
   [ 4, 5, 8],
   [ 9, 10, 0]], dtype=int32)>
The sum of all elements
tf.Tensor(42, shape=(), dtype=int32)
The sum of specific rows is
tf.Tensor([ 6 17 19], shape=(3,), dtype=int32)

解釋

  • 匯入所需的包併為其提供別名,以便於使用。

  • 使用 Numpy 包建立矩陣。

  • 使用“reduce_sum”函式查詢矩陣所有值的總和。

  • 如果除了傳遞矩陣之外,還將特定值傳遞給“reduce_sum”,則它會計算每一行的總和。

  • 結果輸出顯示在控制檯上。

更新於: 2021年1月19日

329 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.