如何使用 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 = np.array([(1,2,3),(3,2,1),(1,1,1)],dtype = 'int32')
matrix_2 = np.array([(0,0,0),(-1,0,1),(3,3,4)],dtype = 'int32')
print("The first matrix is ")
print (matrix_1)
print("The second matrix is ")
print (matrix_2)
print("The product is ")
matrix_1 = tf.constant(matrix_1)
matrix_2 = tf.constant(matrix_2)
matrix_prod = tf.matmul(matrix_1, matrix_2)
print((matrix_prod))

輸出

The first matrix is
[[1 2 3]
[3 2 1]
[1 1 1]]
The second matrix is
[[ 0 0 0]
[−1 0 1]
[ 3 3 4]]
The product is
tf.Tensor(
[[ 7 9 14]
[ 1 3 6]
[ 2 3 5]], shape=(3, 3), dtype=int32)

解釋

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

  • 使用 Numpy 包建立兩個矩陣。

  • 它們被從 Numpy 陣列轉換為 TensorFlow 中的常量值。

  • TensorFlow 中的“matmul”函式用於乘以矩陣中的值。

  • 結果積顯示在控制檯上。

更新於:2021年1月19日

932 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.