Tensorflow Graph 안에 If 문 사용하기 위해서 위의 함수를 이용할 수 있다.
tf.equal, tf.not_equal
Params :
x : Tensor, SparseTensor, IndexedSlices
y : Tensor, SparseTensor, IndexedSlices
name : optional
Returns :
Tensor, dtype=tf.bool, same size with x, y
설명 :
x 와 y 가 같은지 판단해서 bool 타입으로 반환한다. 이때 각각의 원소하나하나씩 판별해서 x, y 와 shape이 동일한 bool 타입 텐서를 반환한다.
x = tf.constant([2, 4, 2])
y = tf.constant(2)
tf.equal(x, y)
#<tf.Tensor: shape=(3,), dtype=bool, numpy=array([ True, False, True])>
x == y
#<tf.Tensor: shape=(3,), dtype=bool, numpy=array([ True, False, True])>
x = tf.constant([2, 4, 2])
y = tf.constant([2, 4, 8])
tf.not_equal(x, y)
#<tf.Tensor: shape=(3,), dtype=bool, numpy=array([False, False, True])>
x != y
#<tf.Tensor: shape=(3,), dtype=bool, numpy=array([False, False, True])>
tf.reduce_all
Params :
input_tensor : boolean tensor to reduce
axis : reduced dimensions, default=None -> all dimenstions
keepdims : default=False, True-> reduced dimensions with length 1
name : optional
Returns :
reduced Tensor
설명 :
tf.math.logical_and 와 동일하게 동작한다. dtype=tf.bool 타입의 텐서를 입력받아서 축을 기준으로 하나라도 false 가 존재하면 false, 나머지는 true 를 생성하는 텐서를 반환한다.
x = tf.constant([[True, True], [False, False]])
tf.reduce_all(x)
#<tf.Tensor: shape=(), dtype=bool, numpy=False>
tf.reduce_all(x, axis=1)
#<tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, False])>
tf.reduce_all(x, axis=1, keepdims=True)
#<tf.Tensor: shape=(2, 1), dtype=bool, numpy=
#array([[ True],
# [False]])>
활용 :
Tensorflow Graph를 생성할때, if 문에 tf.equal, tf.reduce_all 을 조합하여 사용가능하다.
if tf.reduce_all(tf.equal(X, compared_X)):
#do something...
else:
#do something...
예를 들어 두 텐서의 shape 을 비교하던가, 값을 비교하던가 할 수 있다. 원래 equal 메서드를 수행하면 입력 텐서와 동일한 shape의 텐서가 반환되는데 이는 if 문에 사용불가능하고 reduce_all 으로 판단할 수 있다.
tf.cond ( pred, true_fn=None, false_fn=None, name=None )
Params :
pred : scaler determining whether to true, false
true_fn : the callable function to be performed if pred is true
false_fn : he callable function to be performed if pred is false
name : return tensor name (optional)
Returns :
Tensors returned by true_fn or false_fn
설명 :
True or False 로 판단될 수 있는 pred 식을 입력하면, True 일경우 true_fn, False일 경우 false_fn 을 수행한 결과값을 반환한다.
이때 true_fn, false_fn 이 반환값의 형식이 동일해야한다. fn는 반드시 callable 이어야 하는데 인자를 넣고싶으면, lambda 함수를 이용한다.
x = tf.constant(2)
y = tf.constant(5)
def f1():
return tf.multiply(x, 10)
def f2():
return tf.add(y, 3)
tf.cond(tf.less(x, y), f1, f2)
#<tf.Tensor: shape=(), dtype=int32, numpy=20>
def f1(x):
return tf.multiply(x, 10)
def f2(x):
return tf.add(x, 3)
tf.cond(tf.less(x, y), lambda: f1(y), lambda: f2(x))
#<tf.Tensor: shape=(), dtype=int32, numpy=50>
'오늘 > 오늘의 함수' 카테고리의 다른 글
[Tesorflow] tf.random.categorical() (0) | 2022.01.03 |
---|---|
[tensorflow] tf.math.add_n, tf.math.reduce_mean, tf.cinsum (0) | 2021.12.09 |
[numpy] np.ufunc.accumulate (0) | 2021.12.08 |
[numpy] np.flip (0) | 2021.12.08 |
[Python] functools.partial (0) | 2021.12.04 |