[Pytorch] Pytorch에서 tensor를 boolean tensor으로 바꾸는 방법

Luckydl21·2022년 2월 18일
post-thumbnail

tensorflow에서는 tf.cast를 사용하면 tensor를 쉽게 boolean tensor로 변경이 가능하다.

tf.cast 예시
tensor=tf.constant([[12,-2],[-5,4]])
tensor=tf.cast(tensor>=0,tf.int32)
print(tensor)
tf.Tensor(
[[1 0]
 [0 1]], shape=(2, 2), dtype=int32)
pytorch에서는 변경 방법이 두가지 있음
예시
tensor=torch.tensor([0,10,0,12])
방법 01) > operator 사용
(tensor>0).type(torch.int32)
tensor([0, 1, 0, 1], dtype=torch.int32)
방법 02) gt()사용
tensor.gt(0).to(torch.int32)
tensor([0, 1, 0, 1], dtype=torch.int32)

0개의 댓글