TensorFlow v2.0的基本張量操作

2019-10-23     人工智慧遇見磐創

使用TensorFlow v2.0的基本張量操作

from __future__ import print_function
import tensorflow as tf
# 定義張量常量
a = tf.constant(2)
b = tf.constant(3)
c = tf.constant(5)
# 各種張量操作
# 注意:張量也支持python的操作(+,*,...)
add = tf.add(a,b)
sub = tf.subtract(a,b)
mul = tf.multiply(a,b)
div = tf.divide(a,b)
# 訪問張量的值
print("add=",add.numpy())
print("sub=",sub.numpy())
print("mul=",mul.numpy())
print("div=",div.numpy())

output:

add= 5
sub= -1
mul= 6
div= 0.6666666666666666
# 更多一些操作
mean = tf.reduce_mean([a,b,c])
sum =tf.reduce_sum([a,b,c])
# 訪問張量的值
print("mean=",mean.numpy())
print("sum=",sum.numpy())

output:

mean= 3
sum= 10
# 矩陣乘法
matrix1 = tf.constant([[1,2],[3,4]])
matrix2 = tf.constant([[5,6],[7,8]])
product = tf.matmul(matrix1,matrix2)
# 展示張量
product

output:


array([[19, 22],
[43, 50]])>
# 將張量轉換為Numpy
product.numpy()

output:

array([[19., 22.],
[43., 50.]], dtype=float32)
文章來源: https://twgreatdaily.com/zh-mo/qN0r920BMH2_cNUgVO3L.html