Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cộng hai ma trận với TensorFlow


TensorFlow (Google) framework học máy mã nguồn mở, tối ưu NumPy/tensor, scalable, GPU, tài liệu tốt.

Cài đặt: pip install tensorflow

Tensor: mảng đa chiều với Rank (số chiều), Type (kiểu dữ liệu), Shape (hình dạng).

Sử dụng Jupyter Notebook: pip install tensorflow.

Cộng hai ma trận với TensorFlow

Ví dụ

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("Ma trận 1:", matrix_1)
print("Ma trận 2:", matrix_2)

matrix_1 = tf.constant(matrix_1)
matrix_2 = tf.constant(matrix_2)

matrix_sum = tf.add(matrix_1, matrix_2)
print("Tổng ma trận:", matrix_sum)

Đầu ra

Ma trận 1: [[1 2 3] [3 2 1] [1 1 1]]
Ma trận 2: [[ 0 0 0] [-1 0 1] [ 3 3 4]]
Tổng ma trận: tf.Tensor( [[1 2 3] [2 2 2] [4 4 5]], shape=(3, 3), dtype=int32)

Giải thích

  • Import TensorFlow, NumPy.
  • Tạo 2 ma trận 3x3 NumPy, chuyển sang tf.constant.
  • tf.add cộng element-wise 2 ma trận.
  • Kết quả ma trận 3x3.