tf.range, tf.equal, tf.where, tf.clip_by_value 정리
728x90

tf.range
:리스트를 만들 듯이 텐서를 만들 때 편함
특히 batch마다 batch_size가 다를 때 용이함

 

#공식 문서
tf.range(limit, delta=1, dtype=None, name='range')
tf.range(start, limit, delta=1, dtype=None, name='range')

 

start = 3
limit = 18
delta = 3
tf.range(start, limit, delta) 
# 예상 출력: [3, 6, 9, 12, 15]

start = 3
limit = 1
delta = -0.5
tf.range(start, limit, delta)  
# 예상 출력: [3, 2.5, 2, 1.5]

limit = 5
tf.range(limit)  
# 예상 출력: [0, 1, 2, 3, 4]

# 실전 예시
indices = tf.range(tf.shape(spectra)[0]) 
# spectra의 첫 차원의 batch 길이에 맞춰서 0부터 batch size까지 텐서 생성

 

 

https://www.tensorflow.org/api_docs/python/tf/range

 

tf.range  |  TensorFlow v2.16.1

Creates a sequence of numbers.

www.tensorflow.org


tf.equal
x,y를 비교해서 텐서로 저장하기 용이함
tf.where이랑 세트라고 보면 됨

 

#공식문서
tf.math.equal(
    x, y, name=None
)

 

x = tf.constant([2, 4])
y = tf.constant(2)
tf.math.equal(x, y)
# 예상 출력: <tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, False])>

x = tf.constant([2, 4])
y = tf.constant([2, 4])
tf.math.equal(x, y)
# 예상 출력: <tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True,  True])>

# 실전 예시
is_last_in_batch = tf.equal((indices + 1) % batch_size, 0)
# (i+1)%B == 0 인 경우 -> is_last_in_batch로 true false 저장해서 tensor로 저장해 놓음

 

https://www.tensorflow.org/api_docs/python/tf/math/equal

 

tf.math.equal  |  TensorFlow v2.16.1

Returns the truth value of (x == y) element-wise.

www.tensorflow.org


tf.where
tf.equal에 따라서 값을 저장하기 용이함
condition 값에 따라 True면 x저장, False면 y저장 -> boolen tensor가 만들어짐

#공식 문서
tf.where(
    condition, x=None, y=None, name=None
)

tf.where([True, False, False, True]).numpy()
# 예상 출력: array([[0], [3]])

tf.where([True, False, False, True],
         [1, 2, 3, 4],
         [100, 200, 300, 400]).numpy()
#예상 출력: array([  1, 200, 300,   4], dtype=int32)

#실전 예시
idx_offset = tf.where(is_last_in_batch, -batch_size, 1)
# is_last_in_batch가 true이면 인덱스를 -batch_size, false이면 1로 지정

 

https://www.tensorflow.org/api_docs/python/tf/where

 

tf.where  |  TensorFlow v2.16.1

Returns the indices of non-zero elements, or multiplexes x and y.

www.tensorflow.org


tf.clip_by_value

최대 값과 최소 값을 자르기 용이함

#공식 문서
tf.clip_by_value(
    t, clip_value_min, clip_value_max, name=None
)

 

t = tf.constant([[-10., -1., 0.], [0., 2., 10.]])
t2 = tf.clip_by_value(t, clip_value_min=-1, clip_value_max=1)
t2.numpy()
#예상 출력: array([[-1., -1.,  0.], [ 0.,  1.,  1.]], dtype=float32)

#실전 예시
mix_indices = tf.clip_by_value(mix_indices, 0, tf.shape(spectra)[0] - 1)
# mix_incidices의 최대 최소 지정

 

https://www.tensorflow.org/api_docs/python/tf/clip_by_value

 

tf.clip_by_value  |  TensorFlow v2.16.1

Clips tensor values to a specified min and max.

www.tensorflow.org

 

728x90

댓글

공지사항
업데이트
인기 글
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
최근댓글
250x250