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

Tính tổng phần tử/hàng cụ thể của ma trận với TensorFlow


TensorFlow (Google) framework học máy mã nguồn mở, tối ưu NumPy/tensor. Hỗ trợ mạng nơ-ron sâu, scalable, GPU.

Cài đặt: pip install tensorflow

Tensor: mảng đa chiều trong đồ thị luồng dữ liệu.

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

Tính tổng phần tử/hàng cụ thể của ma trận với TensorFlow

Ví dụ

import tensorflow as tf
import numpy as np

matrix_1 = tf.Variable([[1,2,3],[4,5,8],[9,10,0]])
print("Ma trận:")
print(matrix_1)

print("Tổng tất cả phần tử:")
result = tf.reduce_sum(matrix_1)
print(result)

print("Tổng từng hàng:")
result = tf.reduce_sum(matrix_1, 1)
print(result)

Đầu ra

Ma trận: 
Tổng tất cả phần tử: tf.Tensor(42, shape=(), dtype=int32)
Tổng từng hàng: tf.Tensor([ 6 17 19], shape=(3,), dtype=int32)

Giải thích

  • Import TensorFlow, NumPy.
  • Tạo ma trận 3x3 bằng tf.Variable.
  • tf.reduce_sum(matrix) → tổng tất cả phần tử (scala).
  • tf.reduce_sum(matrix, 1) → tổng theo axis=1 (từng hàng), trả về vector shape (3,).
  • In kết quả ra console.