马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
前言
在TensorFlow中既可以使用数学运算符号进行数学运算也可以使用TensorFlow定义好的数学运算方法。
1. 运算符与函数的对应关系
TensorFlow重载了Python运算符,使其能够直接操纵张量(Tensor)。例如:
加法:a + b 等价于 tf.add(a, b)
减法:a - b 等价于 tf.subtract(a, b)
乘法:a * b 等价于 tf.multiply(a, b)
除法:a / b 等价于 tf.divide(a, b)
矩阵乘法:a @ b 等价于 tf.matmul(a, b)
- import tensorflow as tf
- # 定义常量
- a = tf.constant(2)
- b = tf.constant(3)
- # 使用运算符
- c1 = a + b # 结果为 5
- print(c1.numpy())
- # 使用TensorFlow函数
- c2 = tf.add(a, b) # 结果相同
- print(c2.numpy())
复制代码 效果如下:
2.何时必须使用函数?
以下场景需直接调用TensorFlow函数:
归约操纵:如tf.reduce_sum()(求和)、tf.reduce_mean()(求平均)等。
复杂运算:如矩阵乘法(tf.matmul)、卷积(tf.nn.conv2d)、梯度盘算等。
指定参数:如设置盘算轴(axis)、数据范例(dtype)或操纵名称(name)。
聚合运算:
- import tensorflow as tf
- import numpy as np
- x = np.random.randint(0,10, size=(3,6))
- x_mean = tf.reduce_mean(x)
- # 默认会聚合所有的维度
- print(x_mean.numpy())
- # 可以指定聚合的轴
- x_reduce_mean = tf.reduce_mean(x, axis=0)
- print(x_reduce_mean.numpy())
复制代码 效果如下;
矩阵运算:
- import tensorflow as tf
- import numpy as np
- # 矩阵运算
- x = np.random.randint(0,10, size=(3,6))
- y = np.random.randint(0,10, size=(6,4))
- dot = tf.matmul(x, y)
- print(dot.numpy())
复制代码- [[129 73 184 121]
- [ 99 83 137 122]
- [137 63 121 97]]
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |