【TensorFlow】之基本运算

加法

tf.add

tf.add(x,y,name=None)
参数说明:
x:一个张量,必须是下列类型之一:bfloat16/half/float32/uint8/int8/int16/int32/int64/complex64/complex128/string
y: 一个张量,类型必须同x
name:操作的名字,可选参数
返回值: x+y
一个张量,类型同x

import tensorflow as tf
a = tf.constant(2)
b = tf.constant(5)
addOp = tf.add(a,b)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(addOp))
print(addOp)
sess.close()

输出:

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

tf.math.add

同tf.add

减法

tf.subtract

tf.subtract(x,y,name=None)
参数说明:
x:一个张量,必须是以下类型之一:bfloat16/half/float32/float64/uint8/int8/uint16/int16/int32/int64/complex64/complex128
y:一个张量,类型同x
name:张量操作的名字,可选参数。
返回值: x-y
一个张量,类型同x

import tensorflow as tf
a = tf.constant(2)
b = tf.constant(5)
subOp = tf.subtract(a,b)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(subOp))
print(subOp)
sess.close()

输出:

-3
Tensor("Sub:0", shape=(), dtype=int32)

注:subtract支持广播操作

乘法

tf.multiply

tf.multiply(x,y,name=None)
参数说明:
x:一个张量,必须是下列类型之一:bfloat16/half/float32/float64/uint8/uint16/int16/int32/int64/complex64/complex128
y:一个张量,类型同x
返回值: x*y
一个张量,类型同x

import tensorflow as tf
a = tf.constant(2)
b = tf.constant(5)
mulOp = tf.multiply(a,b)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(mulOp))
print(mulOp)
sess.close()

输出:

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

tf.matmul

同tf.multiply(a,b)
注意:tf.matmul(a,b)代表的是矩阵乘法,其中,矩阵a的列和矩阵b的行数相等;tf.multiply(a,b)代表的是点乘,其中矩阵a的列要么为1要么和矩阵b同列,矩阵a和矩阵b行数必须相等。

tf.scalar_mul

标量和张量相乘:

tf.scalar_mul(scalar,x)
参数说明:
scalar:标量
x:一个张量
返回值: scalar*x

import tensorflow as tf
b = tf.constant(5)
scalar_mul_Op = tf.scalar_mul(2,b)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(scalar_mul_Op))
print(scalar_mul_Op)
sess.close()

除法

tf.div

除法操作,如果其中一个是浮点数,则结果是浮点类型,否则是整数类型。

tf.div(x,y,name=None)
参数说明:
x:实数数值类型,分子
y:实数类型,父母
name:操作名字
返回值:
x/y

import tensorflow as tf
a = tf.constant(2)
b = tf.constant(5)
div_op = tf.div(a,b)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(div_op))
print(div_op)
sess.close()

输出:

0
Tensor("div:0", shape=(), dtype=int32)

注:如果是tf.div(1.0,2)输出的就是0.5。

注意,如果输入的是
a = tf.constant(1.0)
b = tf.constant(5)
div_op = tf.div(a,b)
在执行时就会报错,因为这里需要b也是float32类型的,因此改成:
b = tf.constant(5.0) 或 b = tf.constant(5,dtype=tf.float32)即可

【参考网站】

  1. tensorflow之算术运算符
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值