TensorFlow v2.0的基本张量操作

使用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:


<tf.Tensor: id=74, shape=(2, 2), dtype=int32, numpy=
array([[19, 22],
       [43, 50]])>
# 将张量转换为Numpy
product.numpy()

output:

array([[19., 22.],
       [43., 50.]], dtype=float32)

欢迎关注磐创博客资源汇总站:

http://docs.panchuang.net/

欢迎关注PyTorch官方中文教程站:

http://pytorch.panchuang.net/