Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- 시계열데이터
- 판다스 #Pandas #DataFrame #Statistics #통계 #파이썬 #Python #Resample
- 깃허브
- AI #Inductive_Bias #Relational_inductive_bias
- Github
- tensorflow #tensorflow-gpu #python #ubuntu #텐서플로우
- SQL #python #MySQL #PostgreSQL
- version_error
- tf.where
- MachineLearning
- 특정값지우기
- git
- 선형회귀
- 비동기모듈
- REST_API
- 깃
- pandas #python #date #datetime
- TensorFlow
- 파이썬
- Asyncio
- fashionmnist
- python #pandas #data_preprocessing #data_process
- pandas #python #excel #판다스 #파이썬 #엑셀저장 #xlsxwriter
- Python
- AI #RNN #LSTM #LSTMP #인공지능 #언어학습 #순차학습
- pandas #ewma #python #지수이동가중평균 #파이썬 #판다스 #ema #ewm
- ngrok
- aiohttp
- SQL #PostgreSQL
- mnist
Archives
- Today
- Total
린스토리
[Tensorflow v.2] Tensor의 특정 기준에 해당하는 값 변경하기(tf.where 활용하기) 본문
Tensorflow/Tensorflow Tutorial
[Tensorflow v.2] Tensor의 특정 기준에 해당하는 값 변경하기(tf.where 활용하기)
rinaaaLee 2022. 8. 9. 15:36Tensorflow의 Tensor 값 중 특정 기준에 해당하는 값을 변경하는 일이 생겼다.
Tensor는 불변의 값이라서 그냥 numpy array처럼 index를 이용해 값을 변경하는 것이 어려웠다.
그래서 tf.where를 활용해 값을 변경하는 법을 소개하고자 한다.
다음과 같은 tensor가 있다고 생각해보자.

이 tensor의 값 중에서 10 이상인 값을 10으로 대체하고 싶은 상황이라고 가정한다.
만약 tensor가 아니라 list 혹은 numpy array라면 index를 활용해 값을 변경할 수 있을 것이다.
하지만 tensor이기 때문에 이 방법을 사용할 수 없었다. (사용할 수 있는 방법이 있나..? 있으면 알려주세요..!)
>> Flow
그래서 나는 다음과 같은 순서로 tensor의 값을 변경하고자 했다.
1. tensor
[[4.], [3.], [13.], [6.], [5.], [11.], [8.], [9.]]
2. tensor.reshape
[4., 3., 13., 6., 5., 11., 8., 9.]
3. 기준값 10 이상일 경우 True, 이하인 경우 False로 Bool values로 변경
[False, False, True, False, False, True, False, False]
4. tf.where
[4., 3., 10., 6., 5., 10., 8., 9.]
5. tf.reshape
[[4.], [3.], [10.], [6.], [5.], [10.], [8.], [9.]]
여기서 tf.where를 알아보도록 하자.
>> tf.where
tf.where(condition, x, y) : tensorflow 공식 홈페이지 참고
condition = [True, False, False, True]
x = [1, 2, 3, 4]
y = [100, 200, 300, 400]
tf.where(condition, x, y)
-> Condition이 True일 경우: X의 값을 가져온다.
-> Condition이 False일 경우: Y의 값을 가져온다.
==> [1, 200, 300, 4]
>> 코드
import tensorflow as tf
def value_change(logits, figure):
compare = tf.multiply(figure , tf.ones(shape=tf.shape(logits)))
indices = logits > compare # is a tensor if bool values
indices = tf.reshape(indices, [-1]) # reshape to flat
logits_flat = tf.reshape(logits, [-1]) # reshape to flat
values_change = tf.reshape(compare, [-1]) # reshape to flat
logits_convert = tf.where(indices, values_change, logits_flat)
logits_convert = tf.reshape(logits_convert, [-1, 1])
return logits_convert
tensor = tf.constant([[4],[3],[13],[6],[5],[11],[8],[9]])
a = value_change(tensor, 10)
이렇게 적용하면 결과는 다음과 같이 나온다.

이렇게 해서 Tensor의 특정 값을 변경해보았다...!!!!
나는 이걸, train을 통해 나온 prediction값에서 loss를 주기 전에 값을 변경하여 들어가도록 해주었다.
한단계씩 해보니 넘 재밌다!
'Tensorflow > Tensorflow Tutorial' 카테고리의 다른 글
| [Tensorflow v.2] Tutorial_Classification(분류) 문제 다루기 (0) | 2022.07.07 |
|---|
Comments