TensorFlow v2 基本操作

2022-08-09,,

张量(Tensor)基本操作

更多TensorFlow v2 示例:Tensor Flow v2 入门示例
参考:TensorFlow-Examples
博主使用Jupyter Notebook(python3)编写
TensorFlow版本为2.2.0



本程序介绍一些基本的张量(Tensor)操作

#from __future__ import print_function#__future__模块将新版本的内容导入旧版本,如使用python2需要启用
import tensorflow as tf
#定义张量(tensor)
a = tf.constant(2)
b = tf.constant(3)
c = tf.constant(5)
print(a)

运行结果:
tf.Tensor(2, shape=(), dtype=int32)

#基本张量(tensor)操作
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())

运行结果:
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())

运行结果:
mean = 3
sum = 10

#矩阵乘法
matrix1 = tf.constant([[1., 2.], [3., 4.]])
matrix2 = tf.constant([[5., 6.], [7., 8.]])

product = tf.matmul(matrix1, matrix2)
print(product.numpy())

运行结果:
[[19. 22.]
[43. 50.]]

#矩阵点乘,对应数字相乘
product1 = matrix1 * matrix2
print(product1)
print(product1.numpy())

运行结果:
tf.Tensor(
[[ 5. 12.]
[21. 32.]], shape=(2, 2), dtype=float32)
[[ 5. 12.]
[21. 32.]]


张量(Tensor)也支持python中的+,-,*,/,**,…

add = a + b
sub = a - b
mul = a * b
div = a / b

print('add =', add.numpy())
print('sub =', sub.numpy())
print('mul =', mul.numpy())
print('div =', div.numpy())

运行结果:
add = 5
sub = -1
mul = 6
div = 0.6666666666666666

但不同的是对Tensor进行运算时必须保持数值的类型相同
数值类型不同则会报错,如:

test = add + div

运行结果:
InvalidArgumentError: cannot compute AddV2 as input #1(zero-based) was expected to be a int32 tensor but is a double tensor [Op:AddV2]

test = add * div

运行结果:
InvalidArgumentError: cannot compute Mul as input #1(zero-based) was expected to be a int32 tensor but is a double tensor [Op:Mul]

对int数除1即可

print((add/1+div).numpy())

运行结果:
5.666666666666667

本文地址:https://blog.csdn.net/m0_48796437/article/details/107135340

《TensorFlow v2 基本操作.doc》

下载本文的Word格式文档,以方便收藏与打印。