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

การบวกเมทริกซ์ 2 ตัวด้วย TensorFlow


บทนำ

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

การติดตั้ง

pip install tensorflow

คุณสมบัติ Tensor

  • Rank - มิติของเทนเซอร์
  • Type - ชนิดข้อมูลองค์ประกอบ
  • Shape - ขนาดแถวและคอลัมน์

ตัวอย่าง: Matrix Addition ด้วย tf.add

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_sum = tf.add(matrix_1, matrix_2)
print("ผลบวก:", matrix_sum)

ผลลัพธ์

Matrix 1: [[1 2 3] [3 2 1] [1 1 1]]
Matrix 2: [[0 0 0] [-1 0 1] [3 3 4]]
ผลบวก: tf.Tensor([[1 2 3] [2 2 2] [4 4 5]], shape=(3, 3), dtype=int32)

คำอธิบาย

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