deep_learning_Function_tf.add()、tf.subtract()、tf.multiply()、tf.div()


tf.add()、tf.subtract()、tf.multiply()、tf.div()函数介绍和示例

1. tf.add()

释义:加法操作

示例:

x = tf.constant(2, dtype=tf.float32, name=None)
y = tf.constant(3, dtype=tf.float32, name=None)
z = tf.add(x, y)         # 加法操作

X = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name=None)
Y = tf.constant([[1, 1, 1], [2, 2 ,2]], dtype=tf.float32, name=None)
Z = tf.add(X, Y)         # 矩阵加法操作,对应位置元素相加

with tf.Session() as sess:
    print(sess.run(z))
    print('='*30)

    print(sess.run(Z))
5.0
==============================
[[2. 3. 4.]
 [6. 7. 8.]]

2. tf.subtract()

释义:减法操作

示例:

x = tf.constant(10, dtype=tf.float32, name=None)
y = tf.constant(4, dtype=tf.float32, name=None)
z = tf.subtract(x, y)         # 减法操作

X = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name=None)
Y = tf.constant([[1, 1, 1], [2, 2 ,2]], dtype=tf.float32, name=None)
Z = tf.subtract(X, Y)         # 矩阵减法操作,对应位置元素相减

with tf.Session() as sess:
    print(sess.run(z))
    print('='*30)
    
    print(sess.run(Z))
6.0
==============================
[[0. 1. 2.]
 [2. 3. 4.]]

3. tf.multiply()

释义:将两个矩阵中对应元素各自相乘

示例:

import tensorflow as tf

X = tf.constant([[1, 2, 3], [4, 5 ,6]], dtype=tf.float32, name=None)
Y = tf.constant([[1, 1, 1], [2, 2 ,2]], dtype=tf.float32, name=None)
Z = tf.multiply(X, Y)       # 乘法操作,对应位置元素相乘

with tf.Session() as sess:
    print(sess.run(Z))
[[ 1.  2.  3.]
 [ 8. 10. 12.]]

tf.matmul()和tf.scalar_mul()函数介绍和示例见csdn 博客

4. tf.div()

释义:除法操作

示例:

x = tf.constant(6, dtype=tf.float32, name=None)
y = tf.constant(3, dtype=tf.float32, name=None)
z = tf.div(x, y)           # 标量/标量

X1 = tf.constant(6, dtype=tf.float32, name=None)
Y1 = tf.constant([[1, 2], [2, 3]], dtype=tf.float32, name=None)
Z1 = tf.div(X1, Y1)        # 标量/矩阵

X2 = tf.constant([[6, 12], [6, 12]], dtype=tf.float32, name=None)
Y2 = tf.constant([[1, 2], [2, 3]], dtype=tf.float32, name=None)
Z2 = tf.div(X2, Y2)        # 矩阵/矩阵,对应元素相除

with tf.Session() as sess:
    print(sess.run(z))
    print('='*30)
    
    print(sess.run(Z1))
    print('='*30)
    
    print(sess.run(Z2))   
2.0
==============================
[[6. 3.]
 [3. 2.]]
==============================
[[6. 6.]
 [3. 4.]]

————————————————
原文链接:https://blog.csdn.net/qq_36512295/article/details/100600390


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM