人工智能深度学习入门练习之(18)TensorFlow – 张量运算

我们已经知道怎么创建张量,现在来学习张量运算。

TensorFlow包含了许多基本的张量运算操作,让我们从一个简单的平方运算开始。

要进行平方运算,可以使用tf.sqrt(x)函数,x是一个浮点数。

import tensorflow as tf
x = tf.constant([2.0], dtype = tf.float32)
print(tf.sqrt(x))

输出

Tensor("Sqrt:0", shape=(1,), dtype=float32)     

注意: 返回的是一个张量对象,而不是2的平方运算结果。此处打印的是张量定义,而不是运算的实际值。在后面章节中,将介绍TensorFlow如何执行操作。

下面是常用运算操作的列表。用法相似,每个操作都需要一个或多个参数。

  • tf.add(a, b)
  • tf.substract(a, b)
  • tf.multiply(a, b)
  • tf.div(a, b)
  • tf.pow(a, b)
  • tf.exp(a)
  • tf.sqrt(a)

示例

import tensorflow as tf
# Add

# 创建两个张量: 一个带1和2的张量, 一个3和4的张量
tensor_a = tf.constant([[1, 2]], dtype = tf.int32)
tensor_b = tf.constant([[3, 4]], dtype = tf.int32)

# 把两个张量加起来
tensor_add = tf.add(tensor_a, tensor_b)

print(tensor_add)   

输出

Tensor("Add:0", shape=(1, 2), dtype=int32)      

注意: 两个张量需要有相同的形状才能相加。

你也可以对这两个张量做乘法。

# Multiply
tensor_multiply = tf.multiply(tensor_a, tensor_b)
print(tensor_multiply)          

输出

Tensor("Mul:0", shape=(1, 2), dtype=int32)  

猜你喜欢

转载自www.cnblogs.com/huanghanyu/p/13164094.html