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