Nhập môn TensorFlow bằng Python
Isaiah Hull
Visiting Associate Professor of Finance, BI Norwegian Business School




#Import constant và add từ tensorflow
from tensorflow import constant, add
# Định nghĩa tensor 0 chiều
A0 = constant([1])
B0 = constant([2])
# Định nghĩa tensor 1 chiều
A1 = constant([1, 2])
B1 = constant([3, 4])
# Định nghĩa tensor 2 chiều
A2 = constant([[1, 2], [3, 4]])
B2 = constant([[5, 6], [7, 8]])
# Thực hiện cộng tensor với add()
C0 = add(A0, B0)
C1 = add(A1, B1)
C2 = add(A2, B2)
add() thực hiện cộng theo phần tử giữa hai tensor
Cộng theo phần tử yêu cầu hai tensor cùng shape:
Toán tử add() được nạp chồng
Nhân theo phần tử dùng multiply()
Nhân ma trận dùng matmul()
matmul(A,B) nhân A với B# Import các toán tử từ tensorflow
from tensorflow import ones, matmul, multiply
# Định nghĩa tensor
A0 = ones(1)
A31 = ones([3, 1])
A34 = ones([3, 4])
A43 = ones([4, 3])
multiply(A0, A0), multiply(A31, A31), và multiply(A34, A34)matmul(A43, A34) nhưng không phải matmul(A43, A43)reduce_sum() cộng dồn theo các chiều của tensorreduce_sum(A) cộng qua mọi chiều của Areduce_sum(A, i) cộng theo chiều i# Import các phép từ tensorflow
from tensorflow import ones, reduce_sum
# Tạo tensor 2x3x4 toàn số 1
A = ones([2, 3, 4])
# Cộng qua mọi chiều
B = reduce_sum(A)
# Cộng theo các chiều 0, 1 và 2
B0 = reduce_sum(A, 0)
B1 = reduce_sum(A, 1)
B2 = reduce_sum(A, 2)
Nhập môn TensorFlow bằng Python