tensorflow比較兩個tensor大小

2021-08-21 13:32:21 字數 1571 閱讀 1181

# 出錯情況:

import tensorflow as tf

import numpy as np

a = tf.placeholder(tf.float32, shape=([2]))

b = tf.placeholder(tf.float32, shape=([2]))

# 直接用if a[0]if tf.less(a[0], b[0]) is true:   # 或者寫成is not none 也都不對的

c = a

print("a is small")

else:

print('b is small')

c = b

sess = tf.session()

feed_dict =

_c, _, _= sess.run([c, a, b], feed_dict=feed_dict)

print(_c)

feed_dict =

bc, _, _ = sess.run([c, a, b], feed_dict=feed_dict)

print(bc)

sess.close()

# 上面輸出是

[ 3.  4.]

[ 2.  4.]

一直只輸出b的值,並沒有判斷

# tf為1.3版本 

# 解決方法:if else語句好像沒有起作用 所以判斷語句都用tf.cond()來代替就可以了

import tensorflow as tf

import numpy as np

a = tf.placeholder(tf.float32, shape=([2]))

b = tf.placeholder(tf.float32, shape=([2]))

d = tf.constant(true)

get = tf.greater(b[0], a[0])

c = tf.cond(tf.greater(b[0], a[0]),  lambda: a,  lambda: b)  # 不能用if else

sess = tf.session()

feed_dict =

gg, _c, _a, _b= sess.run( [get, c, a[0], b[0]], feed_dict=feed_dict)

print(gg, _c, _a, _b)

feed_dict =

_g, bc, aa, bb = sess.run([get, c, a[0], b[0]], feed_dict=feed_dict)

print(_g, bc, aa, bb)

sess.close()

# 輸出會輸出小的數了:

true [ 1.  2.] 1.0 3.0

false [ 2.  4.] 5.0 2.0

# tensorflow裡如果把tensor和numpy if and or while這些混用的都是會有問題,所以一般還是不要用if while這些numpy下的語句了。包含or not這些邏輯運算等tensorflow都有自己的定義的(tf.logical_and,...)。還是用tensor統一的好

兩個排序演算法比較

一.起泡法排序 起泡法排序 掌握兩個重點,1 n個數排序需要進行n 1趟排序 2 第j趟排序需進行n j次比較 交換 程式如下 定義一維陣列,這裡a 0 不用,儲存a 1 a 5 共5個元素,因此n為5.include main for i 1 i 5 i printf n d a i 上述程式中,...

vim 比較兩個檔案

1.使用vim的比較模式開啟兩個檔案 vim d file1 file2 或vimdiff file1 file2 2.如果已經開啟了檔案file1,再開啟另乙個檔案file2進行比較 vert diffsplit file2 如果沒有用vert命令,diffsplit則會分上下兩個視窗。3.如果已...

比較兩個時間大小

datetime.compare t1,t2 比較兩個日期大小,排前面的小,排在後面的大,比如 2011 2 1就小於2012 3 2 返回值小於零 t1 小於 t2。返回值等於零 t1 等於 t2。返回值大於零 t1 大於 t2。如 c sharp view plain copy using sy...