Tensorflow函數之tf.equal和tf.cast

Tensorflow函數之tf.equal、tf.cast

1、tf.equal是對比兩個向量或者矩陣的值是否相等。

對應元素相等返回true,不相等返回false。注意返回的數據類型。

import tensorflow as tf  
import numpy as np  
 
A = [[1,3,4,5,6]]  #1*5矩陣
B = [[1,3,4,3,2]]  #1*5矩陣

C = [1,3,4,5,6]  #有5個元素的向量
D = [1,3,4,3,2]  #有5個元素的向量
 
with tf.compat.v1.Session() as sess:  
    print(sess.run(tf.equal(A, B)))#矩陣與矩陣
    print(sess.run(tf.equal(C, D)))#向量與向量
    print(sess.run(tf.equal(C, B)))#向量與矩陣
    print(sess.run(tf.equal(B, D)))#矩陣與向量

輸出:

[[ True  True  True False False]] #矩陣
[ True  True  True False False]   #向量
[[ True  True  True False False]] #矩陣
[[ True  True  True  True  True]]  #矩陣

2、tf.cast用於轉換數據類型。

表示:tf.cast(x, dtype, name=None)
如將tensor轉換爲bool,或者將bool轉換爲tensor,具體實例如下:

import tensorflow as tf  
a = tf.Variable([1,0,0,1,0])  
b = tf.cast(a,dtype = bool) #tensor轉換爲bool
c = tf.cast(b,dtype=tf.int32)#bool轉換爲tensor
init_op = tf.compat.v1.initialize_all_variables()
with tf.compat.v1.Session() as sess:
    sess.run(init_op)#加入默認圖中,變量初始化
    print(sess.run([a,b,c]))#獲取值

輸出:

[array([1, 0, 0, 1, 0]),
 array([ True, False, False,  True, False]), 
 array([1, 0, 0, 1, 0])]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章