Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การคูณเมทริกซ์ 2 ตัวด้วย TensorFlow (Matrix Multiplication)


บทนำ

TensorFlow เฟรมเวิร์ก ML จาก Google โค้ดเปิด ใช้กับ Python ใช้ในงานวิจัยและการผลิต มีเทคนิคเพิ่มประสิทธิภาพ ใช้ NumPy และเทนเซอร์ รองรับ Deep Neural Networks สเกลได้ดี ใช้ GPU computation จัดการทรัพยากรอัตโนมัติ มีไลบรารี ML มากมาย เอกสารดี

การติดตั้ง

pip install tensorflow

Tensor

เทนเซอร์ = อาร์เรย์หลายมิติ สำหรับ Data flow graph

ตัวอย่าง: Matrix Multiplication ด้วย tf.matmul

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("Matrix 1:", matrix_1)
print("Matrix 2:", matrix_2)

matrix_1 = tf.constant(matrix_1)
matrix_2 = tf.constant(matrix_2)
matrix_prod = tf.matmul(matrix_1, matrix_2)
print("ผลคูณ:", matrix_prod)

ผลลัพธ์

Matrix 1: [[1 2 3] [3 2 1] [1 1 1]]
Matrix 2: [[0 0 0] [-1 0 1] [3 3 4]]
ผลคูณ: tf.Tensor([[7 9 14] [1 3 6] [2 3 5]], shape=(3, 3), dtype=int32)

คำอธิบาย

  • นำเข้าแพ็กเกจและตั้งชื่อย่อ
  • สร้าง 2 เมทริกซ์ 3x3 ด้วย NumPy
  • แปลงเป็น TensorFlow constant
  • ใช้ tf.matmul คูณเมทริกซ์ (Matrix Multiplication)
  • แสดงผลคูณบนคอนโซล