[Tensorflow] ValueError: 'x' has shape (h, w, c) before the loop, but shape (None, w, c) after one iteration. Use tf.autograph.experimental.set_loop_options to set shape invariants.

2023. 9. 9. 19:21·Tensorflow
728x90
반응형

제목이 좀 긴데, 해당 에러는 그래프 연산 모드에서 반복문을 사용할 경우 마주할 수 있는 에러이다.

 

ValueError: 'x' has shape (h, w, c) before the loop, but shape (None, w, c) after one iteration. Use tf.autograph.experimental.set_loop_options to set shape invariants.

 

오류가 난 코드를 함께 보자.

 

def cutout(
        x,
        patch_count,
        patch_base_factor, 
        patch_width_factor, 
        patch_height_factor
    ):
        out_x = x + 0.
        
        for i in range(patch_count):
            pw = tf.random.uniform(
            	(), 
                patch_width_factor[0], 
                patch_width_factor[1]
            ) * (img_w*patch_base_factor)
            
            pw = tf.cast(pw, tf.int32)
            
            ph = tf.random.uniform(
            	(), 
                patch_height_factor[0], 
                patch_height_factor[1]
            ) * (img_h*patch_base_factor)
            
            ph = tf.cast(ph, tf.int32)
            
            fl = tf.cast(img_w-pw, tf.float32)
            px = tf.random.uniform((), 0, fl)
            px = tf.cast(px, tf.int32)
            
            fl = tf.cast(img_h-ph, tf.float32)
            py = tf.random.uniform((), 0, fl)
            py = tf.cast(py, tf.int32)
            
            target = tf.random.uniform((ph, pw, 3), 0, 1)
            
            horizontal = tf.concat([out_x[py:py+ph, :px, :], target, out_x[py:py+ph, px+pw:, :]], axis=1)
            
            out_x = tf.concat([out_x[:py,:,:], horizontal, out_x[py+ph:,:,:]], axis=0)
        
        return out_x

위 코드는

- patch_count 만큼의 노이즈 패치를

- 랜덤한 위치에

- 랜덤한 크기로 넣어주는 함수이다.

 

 

위 코드를 보면 노이즈 패치를 만들고 concat을 통해 out_x와 같은 shape을 만들어주는 걸 확인할 수 있다.

 

그러나, 그래프 모드에서는 패치의 크기를 랜덤으로 정하는 부분부터 이해를 못한다.

 

우리는 반복문 내부의 연산이 종료되면 다시 (h,w,c)의 shape을 가질걸 알고있으나, 그래프 정의 시점에는 모른다.

 

그냥 랜덤한 부분을 None으로 때려버린다.

 

 

해결방법은 (h,w,c)임을 명시하는 것이다.

 

def cutout(
        x,
        patch_count,
        patch_base_factor, 
        patch_width_factor, 
        patch_height_factor
    ):
        out_x = x + 0.
        
        for i in range(patch_count):
            
            ...
            
            out_x = tf.reshape(out_x, (h,w,c))
        
        return out_x

코드 상으로 h,w,c는 free identifier지만 존재한다고 생각해주시면 감사하겠습니다.

 

reshape을 통해 shape을 명시해주면 오류가 발생하지 않는다!

저작자표시 비영리 (새창열림)

'Tensorflow' 카테고리의 다른 글

[Tensorflow] ValueError: Can't convert Python sequence with mixed types to Tensor.  (0) 2024.01.20
'Tensorflow' 카테고리의 다른 글
  • [Tensorflow] ValueError: Can't convert Python sequence with mixed types to Tensor.
uinone
uinone
노는 게 제일 좋아😉
  • uinone
    ideaDummy
    uinone
  • 전체
    오늘
    어제
    • 분류 전체보기
      • CS
        • 확률과 통계
        • 자료구조
        • 논리회로
        • OS
        • 데이터 통신
        • 데이터 과학
        • 컴파일러
      • 알고리즘
        • 그리디
      • 컴퓨터 비전
      • 안드로이드
      • Web
        • CSS
        • TypeScript
        • React.js
      • 기타
        • 모각코
        • 메모장
        • 오류해결
        • 풍미박산 기절초풍 설치과정
      • DL
      • ML
      • 언어
        • C
        • Ocaml
      • Tensorflow
      • 8기 글로벌 SW*AI인재 프로그램
      • 논문 정리
        • 3D Object Detection
        • 3D Multi Object Tracking
      • CUDA
      • Dataset
        • NuScenes
  • 블로그 메뉴

    • LinkedIn
    • Github
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    정렬
    NetworkFlow
    백준
    우선순위 큐
    그리디 알고리즘
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
uinone
[Tensorflow] ValueError: 'x' has shape (h, w, c) before the loop, but shape (None, w, c) after one iteration. Use tf.autograph.experimental.set_loop_options to set shape invariants.
상단으로

티스토리툴바