[Part2. Unit 18] 

패턴 086(~이 고마워요. [Thank you for]

~ 088(진심으로 감사드려요 [I appreciate])


패턴 086 ~이 고마워요. [Thank you for]

for 뒤에는 you help처럼 바로 명사가 나올 수도 있고 for beibg -ing형이 따라 올 수도 있죠. 누군가에게 고마움을 표시할 때 시간과 장소를 가리지 않고 쓸 수 있는 패턴이랍니다.  Thanks for...로 써도 돼요.

1. 집까지 데려다 주어서 고맙습니다.
★ Thank you for bringing me home.

2. 친절히 대해 줘서 감사합니다.
★ Thank you for your hospitality.

3. 저녁 감사합니다.
★ Thank you for dinner.

4. 파티에 와 주셔서 고맙습니다.
★ Thank you for coming to my party.

5. 제 생각을 해주셔서 고마워요.

★ Thank you for thinking of me.

패턴 087 대단히 고마워요. [Thanks a lot for]

Thanks a lot for...에서 a lot은 '많다'라는 의미이므로 ' ~에 많은 감사드려요'라는 말이 되겠죠? 이 패턴은 Thank you so much for... 로 바꿔서 말해도 돼요.

1. 해주신 모든 것에 진심으로 감사를 드립니다.
★ Thanks a lot for all you have done.

2. 저녁을 해주셔서 대단히 감사합니다.
★ Thanks a lot for cooking dinner.

3. 도와주셔서 정말 고맙습니다.
★ Thanks a lot for all your help.

4. 우리 아이들을 돌봐주셔서 정말 고맙습니다.
★ Thanks a lot for taking care of my kids.

5. 세탁을 해줘서 대단히 고맙다.

★ Thanks a lot for doing my laundry

패턴 088 진심으로 감사드려요 [I appreciate]

우리는 잘몰라서 그 동안 못 썼지만 영어권 나라의 사람들은 엄청나게 많이 쓰는 패턴이 바로 I appreciate...입니다. 특히 비즈니스나 공식적인 상황에서 정중한 감사를 표할 때 쓸 수 있는 최상의 표현이죠. 중간에 really를 넣어서 I really appreciate...라고 할 수도 있어요.

1. 당신의 친절에 감사를 드립니다
★ I appreciate your kindness.

2. 선생님의 노력에 감사를 드립니다.
★ I appreciate your effort.

3. 당신의 넓은 마음에 진심으로 감사를 드립니다.
★ I appreciate your generosity.

4. 도움에 진심으로 감사를 드립니다.
★ I appreciate your help.

5. 저를 위해 해주신 모든 것에 깊이 감사 드려요.

★ I appreciate everything you're done for me.


이 포스팅은 영어회화 핵심패턴 233 교재의 Unit 18(패턴 086 ~ 패턴 088)대한 학습노트입니다.

Posted by 이성윤

[Part2. Unit 17] 

패턴 082(당신의 ~는 누구죠? [Who is your]

~ 085(~할 사람? [Who is ready for])


패턴 082 당신의 ~는 누구죠? [Who is your]

미국 대학교때에는 advisor라는 사람이 학생들의 학점 관리는 도와주는데 이 사람을 만나러 가면 데스크에서 Who is your advisor? 라고 물어보지요. 이 패턴을 응용해 Who is your favorite...?라고 하면 '네가 가장 좋아하는 ~는 누구야?'가 돼요.

1. 네 선생님은 누구셔?
★ Who is your teacher?

2. 네가 가장 좋아하는 남자 배우는 누구야?
★ Who is your favorite actor?

3. 가장 좋아하는 여자 배우가 누구예요?
★ Who is your favorite actress?

4. 가장 친한 친구가 누구야?
★ Who is your best friend?

5. 담당 의사는 누구세요?

★ Who is your pharmacist?

패턴 083 누가 ~할 거죠? [Who is going to]

be going to...는 여러분도 잘 알다시피 ' ~할 것이다'란 뜻이에요. 이패턴은 그 앞에 '누구'를 의미하는 who가 붙은 형태이지요. Who is를 줄여서 who's라고 하면 박자가 맞아 입에 딱 붙을 거에요.

1. 누가 책임질 거야?
★ Who is going to take responsibility

2. 누가 운전할래?
★ Who is going to drive?

3. 그 자리는 누가 맡나요?
★ Who is going to take over the position?

4. 누가 개를 돌볼 건가요?
★ Who is going to take care of the dog?

5. 누가 아이를 볼 거예요?

★ Who is going to watch the baby?

패턴 084 누가 ~을 좋아하지요? [Who likes]

의문사 Who 다음에 바로 동사가 온 패턴이죠? 이런 종류의 패턴으로 Who wants...? Who goes...? Who pays...등이 있답니다.

1. 여기서 누가 야구를 좋아하지?
★ Who likes baseball?

2. 여기서 사과파이를 좋아하는 사람은 누구야
★ Who likes apple pie?

3. 카드하기 좋아하는 사람은?
★ Who likes to play cards?

4. 파티 계획하기를 좋아하는 사람은 누구야?
★ Who likes to plan parties?

5. 수영하는 것 좋아하는 사람은?

★ Who likes to swim?

패턴 085 ~할 사람? [Who is ready for]

be ready for...는 ' ~에 대해 준비를 하다'라는 의미이므로 Who is ready for...?를 직역하면 ' ~에 누가 준비되어 있어요?'라는 말이 됩니다.

1. 잠시 쉴 사람?
★ Who is ready for a break?

2. 스낵 먹을 사람
★ Who is ready for a snack?

3. 재미있는 시간을 보낼 사람?
★ Who is ready for a good time?

4. 파티에 올 사람?
★ Who is ready for a party?

5. 휴가를 갈 사람?

★ Who is ready for a vacation?


이 포스팅은 영어회화 핵심패턴 233 교재의 Unit 17(패턴 082 ~ 패턴 085)대한 학습노트입니다.

Posted by 이성윤

[Part2. Unit 16] 

패턴 079(어떤 것을 ~할래요? [Which one do you]

~ 081(어느 차가(를) ~하나요? [Which car])


패턴 079 어떤 것을 ~할래요? [Which one do you]

which는 양자택일에 사용되는 의문사로, which one은 '어떤 것'을 가리켜요. 따라서 차를 사러 가서 그랜저와 코란도 가운데 어느 것을 선택할지, 또는 쇼핑을 할 때 둘 중에 어떤 것을 살지 묻는 경우에 흔히 쓸 수 있죠.

1. 어떤 게 더 좋아?
★ Which one do you prefer?

2. 넌 어떤 걸 원해
★ Which one do you want?

3. 당신은 어떤 것을 좋아하세요?
★ Which one do you like?

4. 어떤 것을 가지고 계세요?
★ Which one do you have?

5. 어떤 게 필요하세요?

★ Which one do you need?

패턴 080 어느 길(방법)로 ~하나요? [Which way]

way가 길이므로 which way는 여러 갈래 길 가운데 '어느 길'이 되겠죠? 운전을 하고 가다가 'A길과 B길 가운데 어떤 길로 갈래?' 라고 말할 때 흔히 쓰는 패턴이에요.

1. 어느 길로 가야 하지?
★ Which way should we go?

2. 어떤 길이 더 빠르지?
★ Which way is faster?

3. 어떤 방법이 더 나아?
★ Which way is better?

4. 어떤 방법이 더 쉬울까요?
★ Which way is easier?

5. 그 여자분은 어떤 길로 갔나요?

★ Which way did she run?

패턴 081 어느 차가(를) ~하나요? [Which car]

which car...와 what kind of car...는 약간 다른 뜻을 가지고 있어요. 눈 앞에 보이는 A와 B를 비교해서 어느 차를 의미하는 경우에는 which car...를 쓰고ㅡ 수많은 차량 가운데 '어떤 차를 살 거냐?' 아니면 '어떤 차를 좋아하느냐?'고 물어볼 때는 what kind of car...를 쓰죠.

1. 어느 차를 사고 싶으세요?
★ Which car do you want to buy?

2. 당신 차는 어느 것이죠?
★ Which car is yours?

3. 어떤 차가 더 비싼가요?
★ Which car is worth more?

4. 어느 차가 더 잘 달리나요?
★ Which car runs better?

5. 어떤 차가 연료를 덜 먹나요?

★ Which car gets the best gas mileage?


이 포스팅은 영어회화 핵심패턴 233 교재의 Unit 16(패턴 079 ~ 패턴 081)대한 학습노트입니다.

Posted by 이성윤

[Part2. Unit 15] 

패턴 077(언제 ~할 것 같아요? [When do you expect to]

~ 078(마지막으로 ~한 게 언제에여? [When was the last time])


패턴 077 언제 ~할 것 같아요? [When do you expect to]

expect는 '예상하다 / 생각하다'는 뜻을 갖고 있죠. 그래서 직역하면 '당신은 언제 ~하리라 예상하세요?'가 돼요. 그런데 expect가 진행형으로 쓰이면 '아이를 베고 있다'는 뜻이 되기도 하지요. 즉, She is expecting이라고 하면 She's pregnant(그녀는 임신 중이야)라는 뜻이 되니 조심하세요.

1. 언제쯤이면 준비될까?
★ When do you expect to be ready?

2. 퇴근은 언제 할 것 같아?
★ When do you expect to leave work?

3. 그 프로젝트는 언제 끝날 것 같아?
★ When do you expect to complete the project?

4. 당신은 언제쯤 마을을 떠날 생각이죠?
★ When do you expect to leave town?

5. 언제 이사를 갈 예정입니까?

★ When do you expect to move?


패턴 078 마지막으로 ~한 게 언제에여? [When was the last time]

아주 다양하게 쓸 수 있는 패턴이랍니다. When was the last time다음에는 예문에서 보듯이 you나 he같은 주어가 등장하죠.

1. 네가 마지막으로 운동한 게 언제야?
★ When was the last time you exercised?

2. 영화를 마지막으로 본 게 언제죠?
★ When was the last time you saw a movie?

3. 그녀의 소식을 마지막으로 들은 게 언제야?
★ When was the last time you heard from her?

4. 휴가를 마지막으로 간 계 언제입니까?
★ When was the last time you went on vacation?

5. 네가 그 도시를 마지막으로 떠났던 게 언제니?

★ When was the last time you went out on the town?


이 포스팅은 영어회화 핵심패턴 233 교재의 Unit 15(패턴 077 ~ 패턴 078)대한 학습노트입니다.

Posted by 이성윤

2018년 01월 08일  "스토리 바이블 "

스토리 바이블

저자: 셀리 로이드 존스, 그림: 제이고, 역: 윤종석

출판사: 두란노키즈

목차: 하늘로 오르는 거대한 계단, 웃음의 아들


2018년 01월 09일  "스토리 바이블 "

스토리 바이블

저자: 셀리 로이드 존스, 그림: 제이고, 역: 윤종석

출판사: 두란노키즈

목차: 특별한 선물


2018년 01월 10일  "스토리 바이블 "

스토리 바이블

저자: 셀리 로이드 존스, 그림: 제이고, 역: 윤종석

출판사: 두란노키즈

목차: 아무도 원치 않는 여자


2018년 01월 11일  "태교 여행"


2018년 01월 12일  "태교 여행"


2018년 01월 13일  "스토리 바이블"

스토리 바이블

저자: 셀리 로이드 존스, 그림: 제이고, 역: 윤종석

출판사: 두란노키즈

목차: 용서하는 통치자


2018년 01월 14일  "스토리 바이블 "

스토리 바이블

저자: 셀리 로이드 존스, 그림: 제이고, 역: 윤종석

출판사: 두란노키즈

목차: 하나님의 구출작전, 길을 내시는 하나님

Posted by 이성윤

[API] Tensorflow Convert to Tensor - slicing and joining

(텐서플로우 텐서 변환 - 자르고 붙이기)


자르고 붙이기

TensorFlow는 텐서를 자르고 특정 부분을 추출해내거나, 여러 텐서를 붙일 수 있는 몇 가지 함수를 제공합니다.


tf.slice(input_, begin, size, name=None)


텐서의 특정 부분을 추출합니다.


이 함수는 텐서 input에서 begin 위치에서 시작해 크기 size인 부분을 추출합니다. 추출할 부분의 size는 텐서 구조(shape)로 표현되는데, size[i]가 input에서 추출할 i번째 차원의 원소의 수입니다. 추출 부분의 시작 위치 begin은 각 차원에서의 오프셋(offset)으로 표현됩니다. 즉, begin[i]는 input의 i번째 차원에서 시작 위치의 오프셋입니다.


begin은 0부터 시작하고, size는 1부터 시작합니다. 만약 size[i]가 -1이라면, 차원 i의 모든 남은 원소들이 추출 부분에 포함됩니다. 즉, 이는 아래와 같이 설정하는 것과 동일합니다.

size[i] = input.dim_size(i) - begin[i]


이 함수는 다음의 조건이 만족되어야 합니다:

0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]


예시:

# 'input'은 [[[1, 1, 1], [2, 2, 2]],

#            [[3, 3, 3], [4, 4, 4]],

#            [[5, 5, 5], [6, 6, 6]]]

tf.slice(input, [1, 0, 0], [1, 1, 3]) ==> [[[3, 3, 3]]]

tf.slice(input, [1, 0, 0], [1, 2, 3]) ==> [[[3, 3, 3],

                                            [4, 4, 4]]]

tf.slice(input, [1, 0, 0], [2, 1, 3]) ==> [[[3, 3, 3]],

                                           [[5, 5, 5]]]

인자:
  • input_Tensor.
  • beginint32 또는 int64형 Tensor.
  • sizeint32 또는 int64형 Tensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.slice 결과

In [1]:

import tensorflow as tf

import tfutil

 

# [1, 2, 3, 4, 5, 6, 7, 8, 9]

const1 = tf.constant([123456789])

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(9,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1 2 3 4 5 6 7 8 9]

In [2]:

sl_const1 = tf.slice(const1, [2], [3])

print(sl_const1)

print(tf.shape(sl_const1))

tfutil.print_operation_value(sl_const1)

Tensor("Slice:0", shape=(3,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[3 4 5]

In [3]:

# [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19,20]]

const2 = tf.constant([[12345678910], [111213141516171819,20]])

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2, 10), dtype=int32)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[ 1  2  3  4  5  6  7  8  9 10]

 [11 12 13 14 15 16 17 18 19 20]]

In [4]:

sl_const2 = tf.slice(const2, [01], [13])

print(sl_const2)

print(tf.shape(sl_const2))

tfutil.print_operation_value(sl_const2)

Tensor("Slice_1:0", shape=(1, 3), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[2 3 4]]

In [5]:

sl_const2 = tf.slice(const2, [02], [13])

print(sl_const2)

print(tf.shape(sl_const2))

tfutil.print_operation_value(sl_const2)

Tensor("Slice_2:0", shape=(1, 3), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[3 4 5]]

In [6]:

sl_const2 = tf.slice(const2, [11], [13])

print(sl_const2)

print(tf.shape(sl_const2))

tfutil.print_operation_value(sl_const2)

Tensor("Slice_3:0", shape=(1, 3), dtype=int32)

Tensor("Shape_5:0", shape=(2,), dtype=int32)

[[12 13 14]]

In [7]:

sl_const2 = tf.slice(const2, [12], [13])

print(sl_const2)

print(tf.shape(sl_const2))

tfutil.print_operation_value(sl_const2)

Tensor("Slice_4:0", shape=(1, 3), dtype=int32)

Tensor("Shape_6:0", shape=(2,), dtype=int32)

[[13 14 15]]

In [8]:

# [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]

const3 = tf.constant([[[123], [456]], [[789], [101112]], [[131415], [161718]]])

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(3, 2, 3), dtype=int32)

Tensor("Shape_7:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 4  5  6]]

 [[ 7  8  9]

  [10 11 12]]

 [[13 14 15]

  [16 17 18]]]

In [9]:

sl_const3 = tf.slice(const3, [000], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_5:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_8:0", shape=(3,), dtype=int32)

[[[1]]]

In [10]:

sl_const3 = tf.slice(const3, [000], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_6:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_9:0", shape=(3,), dtype=int32)

[[[1 2]]]

In [11]:

sl_const3 = tf.slice(const3, [010], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_7:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_10:0", shape=(3,), dtype=int32)

[[[4]]]

In [12]:

sl_const3 = tf.slice(const3, [010], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_8:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_11:0", shape=(3,), dtype=int32)

[[[4 5]]]

In [13]:

sl_const3 = tf.slice(const3, [100], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_9:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_12:0", shape=(3,), dtype=int32)

[[[7]]]

In [14]:

sl_const3 = tf.slice(const3, [100], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_10:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_13:0", shape=(3,), dtype=int32)

[[[7 8]]]

In [15]:

sl_const3 = tf.slice(const3, [110], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_11:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_14:0", shape=(3,), dtype=int32)

[[[10]]]

In [16]:

sl_const3 = tf.slice(const3, [110], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_12:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_15:0", shape=(3,), dtype=int32)

[[[10 11]]]

In [17]:

sl_const3 = tf.slice(const3, [200], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_13:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_16:0", shape=(3,), dtype=int32)

[[[13]]]

In [18]:

sl_const3 = tf.slice(const3, [200], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_14:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_17:0", shape=(3,), dtype=int32)

[[[13 14]]]

In [19]:

sl_const3 = tf.slice(const3, [210], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_15:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_18:0", shape=(3,), dtype=int32)

[[[16]]]

In [20]:

sl_const3 = tf.slice(const3, [210], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_16:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_19:0", shape=(3,), dtype=int32)

[[[16 17]]]

In [21]:

# [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]

sl_const3 = tf.slice(const3, [000], [111])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_17:0", shape=(1, 1, 1), dtype=int32)

Tensor("Shape_20:0", shape=(3,), dtype=int32)

[[[1]]]

In [22]:

sl_const3 = tf.slice(const3, [000], [112])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_18:0", shape=(1, 1, 2), dtype=int32)

Tensor("Shape_21:0", shape=(3,), dtype=int32)

[[[1 2]]]

In [23]:

sl_const3 = tf.slice(const3, [000], [113])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_19:0", shape=(1, 1, 3), dtype=int32)

Tensor("Shape_22:0", shape=(3,), dtype=int32)

[[[1 2 3]]]

In [24]:

sl_const3 = tf.slice(const3, [000], [121])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_20:0", shape=(1, 2, 1), dtype=int32)

Tensor("Shape_23:0", shape=(3,), dtype=int32)

[[[1]

  [4]]]

In [25]:

sl_const3 = tf.slice(const3, [000], [122])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_21:0", shape=(1, 2, 2), dtype=int32)

Tensor("Shape_24:0", shape=(3,), dtype=int32)

[[[1 2]

  [4 5]]]

In [26]:

sl_const3 = tf.slice(const3, [000], [123])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_22:0", shape=(1, 2, 3), dtype=int32)

Tensor("Shape_25:0", shape=(3,), dtype=int32)

[[[1 2 3]

  [4 5 6]]]

In [27]:

sl_const3 = tf.slice(const3, [000], [311])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_23:0", shape=(3, 1, 1), dtype=int32)

Tensor("Shape_26:0", shape=(3,), dtype=int32)

[[[ 1]]

 [[ 7]]

 [[13]]]

In [28]:

sl_const3 = tf.slice(const3, [000], [321])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_24:0", shape=(3, 2, 1), dtype=int32)

Tensor("Shape_27:0", shape=(3,), dtype=int32)

[[[ 1]

  [ 4]]

 [[ 7]

  [10]]

 [[13]

  [16]]]

In [29]:

sl_const3 = tf.slice(const3, [000], [312])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_25:0", shape=(3, 1, 2), dtype=int32)

Tensor("Shape_28:0", shape=(3,), dtype=int32)

[[[ 1  2]]

 [[ 7  8]]

 [[13 14]]]

In [30]:

sl_const3 = tf.slice(const3, [000], [322])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_26:0", shape=(3, 2, 2), dtype=int32)

Tensor("Shape_29:0", shape=(3,), dtype=int32)

[[[ 1  2]

  [ 4  5]]

 [[ 7  8]

  [10 11]]

 [[13 14]

  [16 17]]]

In [31]:

sl_const3 = tf.slice(const3, [000], [313])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_27:0", shape=(3, 1, 3), dtype=int32)

Tensor("Shape_30:0", shape=(3,), dtype=int32)

[[[ 1  2  3]]

 [[ 7  8  9]]

 [[13 14 15]]]

In [32]:

sl_const3 = tf.slice(const3, [000], [323])

print(sl_const3)

print(tf.shape(sl_const3))

tfutil.print_operation_value(sl_const3)

Tensor("Slice_28:0", shape=(3, 2, 3), dtype=int32)

Tensor("Shape_31:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 4  5  6]]

 [[ 7  8  9]

  [10 11 12]]

 [[13 14 15]

  [16 17 18]]]


tf.split(split_dim, num_split, value, name='split')


한 차원을 따라서 입력된 텐서를 num_split개의 텐서로 분리합니다.


split_dim 차원을 따라서 value를 num_split 개의 작은 텐서로 분리합니다. num_split이 value.shape[split_dim]을 나눌 수 있어야 합니다.


예시:

# 'value'는 구조(shape) [5, 30]의 텐서

# 'value'를 차원 1을 따라 3개의 텐서로 분리

split0, split1, split2 = tf.split(1, 3, value)

tf.shape(split0) ==> [5, 10]

인자:
  • split_dim: 0-D int32 Tensor. 텐서를 분리할 차원. [0, rank(value)) 범위 내에 있어야 합니다.
  • num_split: Python 정수. 텐서를 분리할 개수.
  • value: 분리할 Tensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

value를 분리하여 얻어진 num_split개의 Tensor.


출처: 텐서 변환


Tensorflow tf.split 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

 

# [1, 2, 3, 4, 5, 6, 7, 8, 9]

const1 = tf.constant(np.array([12345678910]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(10,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10]

In [2]:

sp1_const1, sp2_const1 = tf.split(const1, 20)

print(sp1_const1)

print(tf.shape(sp1_const1))

tfutil.print_operation_value(sp1_const1)

Tensor("split:0", shape=(5,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 2 3 4 5]

In [3]:

print(sp2_const1)

print(tf.shape(sp2_const1))

tfutil.print_operation_value(sp2_const1)

Tensor("split:1", shape=(5,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[ 6  7  8  9 10]

In [4]:

# [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]

const2 = tf.constant([[1234], [5678], [9101112], [13141516], [17181920]])

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_2:0", shape=(5, 4), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[ 1  2  3  4]

 [ 5  6  7  8]

 [ 9 10 11 12]

 [13 14 15 16]

 [17 18 19 20]]

In [5]:

sp1_const2, sp2_const2 = tf.split(const2, 21)

print(sp1_const2)

print(tf.shape(sp1_const2))

tfutil.print_operation_value(sp1_const2)

Tensor("split_1:0", shape=(5, 2), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[ 1  2]

 [ 5  6]

 [ 9 10]

 [13 14]

 [17 18]]

In [6]:

print(sp2_const2)

print(tf.shape(sp2_const2))

tfutil.print_operation_value(sp2_const2)

Tensor("split_1:1", shape=(5, 2), dtype=int32)

Tensor("Shape_5:0", shape=(2,), dtype=int32)

[[ 3  4]

 [ 7  8]

 [11 12]

 [15 16]

 [19 20]]

In [7]:

# [5, 30]

var1 = tf.Variable(tf.random_normal([530]))

print(var1)

print(tf.shape(var1))

<tf.Variable 'Variable:0' shape=(5, 30) dtype=float32_ref>

Tensor("Shape_6:0", shape=(2,), dtype=int32)

In [8]:

sp1_var1, sp2_var1, sp3_var1 = tf.split(var1, 31)

print(sp1_var1)

print(tf.shape(sp1_var1))

Tensor("split_2:0", shape=(5, 10), dtype=float32)

Tensor("Shape_7:0", shape=(2,), dtype=int32)

In [9]:

print(sp2_var1)

print(tf.shape(sp2_var1))

Tensor("split_2:1", shape=(5, 10), dtype=float32)

Tensor("Shape_8:0", shape=(2,), dtype=int32)

In [10]:

print(sp3_var1)

print(tf.shape(sp3_var1))

Tensor("split_2:2", shape=(5, 10), dtype=float32)

Tensor("Shape_9:0", shape=(2,), dtype=int32)


tf.tile(input, multiples, name=None)


주어진 텐서를 타일링(tiling)하여 새로운 텐서를 만듭니다.


이 함수는 주어진 텐서 input을 multiples회 복사하여 새로운 텐서를 만듭니다. 출력 텐서의 i번째 차원은 input.dims(i) * multiples[i] 개의 원소를 가지고, 이는 input의 원소들이 multiples[i]번 복사된 것에 해당합니다. 예로, [a b c d]를 [2]로 타일링하면 [a b c d a b c d]를 얻습니다.

인자:
  • input: 1-D 혹은 그 이상의 Tensor.
  • multiplesint32형 Tensor. 1-D. 길이는 input의 차원의 수와 같아야 합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.tile 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [1, 2, 3, 4, 5, 6, 7, 8, 9]

const1 = tf.constant(np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(10,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10]

In [3]:

ti_const1 = tf.tile(const1, [1])

print(ti_const1)

print(tf.shape(ti_const1))

tfutil.print_operation_value(ti_const1)

Tensor("Tile:0", shape=(10,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10]

In [4]:

ti_const1 = tf.tile(const1, [2])

print(ti_const1)

print(tf.shape(ti_const1))

tfutil.print_operation_value(ti_const1)

Tensor("Tile_1:0", shape=(20,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10]

In [5]:

ti_const1 = tf.tile(const1, [3])

print(ti_const1)

print(tf.shape(ti_const1))

tfutil.print_operation_value(ti_const1)

Tensor("Tile_2:0", shape=(30,), dtype=int32)

Tensor("Shape_3:0", shape=(1,), dtype=int32)

[ 1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5

  6  7  8  9 10]


tf.pad(tensor, paddings, mode='CONSTANT', name=None)


텐서에 패딩을 적용합니다.


이 함수는 지정한 paddings에 따라 tensor에 패딩을 적용합니다. padding은 구조(shape)가 [n, 2]인 정수형 텐서이고, 여기서 n은 tensor의 랭크(rank)입니다. input의 각각의 차원 D에 대해, paddings[D, 0]은 tensor의 원소 앞에 몇 개의 값을 넣을 것인지, paddings[D, 1]은 tensor의 원소 뒤에 몇 개의 값을 넣을 것인지를 나타냅니다. 만약 mode가 "REFLECT"라면, paddings[D, 0]과 paddings[D, 1] 모두 tensor.dim_size(D) - 1보다 크지 않아야 합니다. mode가 "SYMMETRIC"이라면, paddings[D, 0]과 paddings[D, 1] 모두 tensor.dim_size(D)보다 크지 않아야 합니다.


패딩이 이루어진 뒤 출력에서 차원 D의 길이는 다음과 같습니다.

paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]


예시:

# 't'는 [[1, 2, 3], [4, 5, 6]].

# 'paddings'는 [[1, 1,], [2, 2]].

# 't'의 랭크(rank)는 2.

pad(t, paddings, "CONSTANT") ==> [[0, 0, 0, 0, 0, 0, 0],

                                  [0, 0, 1, 2, 3, 0, 0],

                                  [0, 0, 4, 5, 6, 0, 0],

                                  [0, 0, 0, 0, 0, 0, 0]]


pad(t, paddings, "REFLECT") ==> [[6, 5, 4, 5, 6, 5, 4],

                                 [3, 2, 1, 2, 3, 2, 1],

                                 [6, 5, 4, 5, 6, 5, 4],

                                 [3, 2, 1, 2, 3, 2, 1]]


pad(t, paddings, "SYMMETRIC") ==> [[2, 1, 1, 2, 3, 3, 2],

                                   [2, 1, 1, 2, 3, 3, 2],

                                   [5, 4, 4, 5, 6, 6, 5],

                                   [5, 4, 4, 5, 6, 6, 5]]

인자:
  • tensorTensor.
  • paddingsint32형 Tensor.
  • mode: "CONSTANT", "REFLECT", "SYMMETRIC" 중 하나.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

tensor와 같은 자료형의 Tensor.

예외:
  • ValueError: 모드가 "CONSTANT", "REFLECT", or "SYMMETRIC" 중의 하나가 아닌 경우.

출처: 텐서 변환


Tensorflow tf.pad 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [[1, 2, 3], [4, 5, 6]]

const1 = tf.constant(np.array([[1, 2, 3], [4, 5, 6]]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2, 3), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]]

In [3]:

paddings =  [[0, 0,], [0, 1]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad:0", shape=(2, 4), dtype=int32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[1 2 3 0]

 [4 5 6 0]]

In [4]:

paddings =  [[0, 0,], [1, 0]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_1:0", shape=(2, 4), dtype=int32)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[0 1 2 3]

 [0 4 5 6]]

In [5]:

paddings =  [[0, 0,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_2:0", shape=(2, 5), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[0 1 2 3 0]

 [0 4 5 6 0]]

In [6]:

paddings =  [[0, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_3:0", shape=(3, 3), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [0 0 0]]

In [7]:

paddings =  [[1, 0,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_4:0", shape=(3, 3), dtype=int32)

Tensor("Shape_5:0", shape=(2,), dtype=int32)

[[0 0 0]

 [1 2 3]

 [4 5 6]]

In [8]:

paddings =  [[1, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_5:0", shape=(4, 3), dtype=int32)

Tensor("Shape_6:0", shape=(2,), dtype=int32)

[[0 0 0]

 [1 2 3]

 [4 5 6]

 [0 0 0]]

In [9]:

paddings =  [[1, 1,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "CONSTANT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("Pad_6:0", shape=(4, 5), dtype=int32)

Tensor("Shape_7:0", shape=(2,), dtype=int32)

[[0 0 0 0 0]

 [0 1 2 3 0]

 [0 4 5 6 0]

 [0 0 0 0 0]]

In [10]:

# [[1, 2, 3], [4, 5, 6]]

paddings =  [[0, 0,], [0, 1]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad:0", shape=(2, 4), dtype=int32)

Tensor("Shape_8:0", shape=(2,), dtype=int32)

[[1 2 3 2]

 [4 5 6 5]]

In [11]:

paddings =  [[0, 0,], [1, 0]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_1:0", shape=(2, 4), dtype=int32)

Tensor("Shape_9:0", shape=(2,), dtype=int32)

[[2 1 2 3]

 [5 4 5 6]]

In [12]:

paddings =  [[0, 0,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_2:0", shape=(2, 5), dtype=int32)

Tensor("Shape_10:0", shape=(2,), dtype=int32)

[[2 1 2 3 2]

 [5 4 5 6 5]]

In [13]:

paddings =  [[0, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_3:0", shape=(3, 3), dtype=int32)

Tensor("Shape_11:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [1 2 3]]

In [14]:

paddings =  [[1, 0,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_4:0", shape=(3, 3), dtype=int32)

Tensor("Shape_12:0", shape=(2,), dtype=int32)

[[4 5 6]

 [1 2 3]

 [4 5 6]]

In [15]:

paddings =  [[1, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_5:0", shape=(4, 3), dtype=int32)

Tensor("Shape_13:0", shape=(2,), dtype=int32)

[[4 5 6]

 [1 2 3]

 [4 5 6]

 [1 2 3]]

In [16]:

paddings =  [[1, 1,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_6:0", shape=(4, 5), dtype=int32)

Tensor("Shape_14:0", shape=(2,), dtype=int32)

[[5 4 5 6 5]

 [2 1 2 3 2]

 [5 4 5 6 5]

 [2 1 2 3 2]]

In [17]:

paddings =  [[1, 1,], [2, 2]]

pad_const1 = tf.pad(const1, paddings, "REFLECT")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_7:0", shape=(4, 7), dtype=int32)

Tensor("Shape_15:0", shape=(2,), dtype=int32)

[[6 5 4 5 6 5 4]

 [3 2 1 2 3 2 1]

 [6 5 4 5 6 5 4]

 [3 2 1 2 3 2 1]]

In [18]:

# [[1, 2, 3], [4, 5, 6]]

paddings =  [[0, 0,], [0, 1]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_8:0", shape=(2, 4), dtype=int32)

Tensor("Shape_16:0", shape=(2,), dtype=int32)

[[1 2 3 3]

 [4 5 6 6]]

In [19]:

paddings =  [[0, 0,], [1, 0]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_9:0", shape=(2, 4), dtype=int32)

Tensor("Shape_17:0", shape=(2,), dtype=int32)

[[1 1 2 3]

 [4 4 5 6]]

In [20]:

paddings =  [[0, 0,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_10:0", shape=(2, 5), dtype=int32)

Tensor("Shape_18:0", shape=(2,), dtype=int32)

[[1 1 2 3 3]

 [4 4 5 6 6]]

In [21]:

paddings =  [[0, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_11:0", shape=(3, 3), dtype=int32)

Tensor("Shape_19:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [4 5 6]]

In [22]:

paddings =  [[1, 0,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_12:0", shape=(3, 3), dtype=int32)

Tensor("Shape_20:0", shape=(2,), dtype=int32)

[[1 2 3]

 [1 2 3]

 [4 5 6]]

In [23]:

paddings =  [[1, 1,], [0, 0]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_13:0", shape=(4, 3), dtype=int32)

Tensor("Shape_21:0", shape=(2,), dtype=int32)

[[1 2 3]

 [1 2 3]

 [4 5 6]

 [4 5 6]]

In [24]:

paddings =  [[1, 1,], [1, 1]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_14:0", shape=(4, 5), dtype=int32)

Tensor("Shape_22:0", shape=(2,), dtype=int32)

[[1 1 2 3 3]

 [1 1 2 3 3]

 [4 4 5 6 6]

 [4 4 5 6 6]]

In [25]:

paddings =  [[1, 1,], [2, 2]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_15:0", shape=(4, 7), dtype=int32)

Tensor("Shape_23:0", shape=(2,), dtype=int32)

[[2 1 1 2 3 3 2]

 [2 1 1 2 3 3 2]

 [5 4 4 5 6 6 5]

 [5 4 4 5 6 6 5]]

In [26]:

paddings =  [[1, 1,], [3, 3]]

pad_const1 = tf.pad(const1, paddings, "SYMMETRIC")

print(pad_const1)

print(tf.shape(pad_const1))

tfutil.print_operation_value(pad_const1)

Tensor("MirrorPad_16:0", shape=(4, 9), dtype=int32)

Tensor("Shape_24:0", shape=(2,), dtype=int32)

[[3 2 1 1 2 3 3 2 1]

 [3 2 1 1 2 3 3 2 1]

 [6 5 4 4 5 6 6 5 4]

 [6 5 4 4 5 6 6 5 4]]


tf.concat(concat_dim, values, name='concat')


텐서들을 하나의 차원에서 이어붙입니다.


텐서들의 리스트 values를 차원 concat_dim에서 이어붙입니다. 만약 values[i].shape = [D0, D1, ... Dconcat_dim(i), ...Dn]이면, 이어붙인 결과의 구조(shape)는 아래와 같습니다.


[D0, D1, ... Rconcat_dim, ...Dn]


여기서,

Rconcat_dim = sum(Dconcat_dim(i))


입니다. 즉, concat_dim 차원을 따라 입력된 텐서들의 데이터가 연결됩니다.


입력할 텐서들의 차원의 수는 모두 동일해야 하며, concat_dim 차원을 제외한 모든 차원의 길이가 동일해야 합니다.


예시:

t1 = [[1, 2, 3], [4, 5, 6]]

t2 = [[7, 8, 9], [10, 11, 12]]

tf.concat(0, [t1, t2]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]


# tensor t3의 구조(shape)는 [2, 3]

# tensor t4의 구조(shape)는 [2, 3]

tf.shape(tf.concat(0, [t3, t4])) ==> [4, 3]

tf.shape(tf.concat(1, [t3, t4])) ==> [2, 6]

인자:
  • concat_dim: 0-D int32형 Tensor. 텐서를 이어붙일 차원.
  • valuesTensor들의 리스트 또는 Tensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

입력 텐서들을 이어붙여 만든 Tensor.


출처: 텐서 변환


Tensorflow tf. 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [[1, 2, 3], [4, 5, 6]]

const1 = tf.constant(np.array([[1, 2, 3], [4, 5, 6]]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2, 3), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]]

In [3]:

# [[7, 8, 9], [10, 11, 12]]

const2 = tf.constant(np.array([[7, 8, 9], [10, 11, 12]]), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2, 3), dtype=int32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[ 7  8  9]

 [10 11 12]]

In [4]:

cc_const1 = tf.concat([const1, const2], 0)

print(cc_const1)

print(tf.shape(cc_const1))

tfutil.print_operation_value(cc_const1)

Tensor("concat:0", shape=(4, 3), dtype=int32)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[ 1  2  3]

 [ 4  5  6]

 [ 7  8  9]

 [10 11 12]]

In [5]:

cc_const1 = tf.concat([const1, const2], 1)

print(cc_const1)

print(tf.shape(cc_const1))

tfutil.print_operation_value(cc_const1)

Tensor("concat_1:0", shape=(2, 6), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[ 1  2  3  7  8  9]

 [ 4  5  6 10 11 12]]


tf.stack(values, axis=0, name='stack')


Defined in tensorflow/python/ops/array_ops.py.

See the guides: Layers (contrib) > Higher level ops for building neural network layersTensor Transformations > Slicing and Joining

Stacks a list of rank-R tensors into one rank-(R+1) tensor.

Packs the list of tensors in values into a tensor with rank one higher than each tensor in values, by packing them along the axis dimension. Given a list of length N of tensors of shape (A, B, C);

if axis == 0 then the output tensor will have the shape (N, A, B, C). if axis == 1 then the output tensor will have the shape (A, N, B, C). Etc.

For example:

x = tf.constant([1, 4])
y
= tf.constant([2, 5])
z
= tf.constant([3, 6])
tf
.stack([x, y, z])  # [[1, 4], [2, 5], [3, 6]] (Pack along first dim.)
tf
.stack([x, y, z], axis=1)  # [[1, 2, 3], [4, 5, 6]]

This is the opposite of unstack. The numpy equivalent is

tf.stack([x, y, z]) = np.stack([x, y, z])

Args:

  • values: A list of Tensor objects with the same shape and type.
  • axis: An int. The axis to stack along. Defaults to the first dimension. Negative values wrap around, so the valid range is [-(R+1), R+1).
  • name: A name for this operation (optional).

Returns:

  • output: A stacked Tensor with the same type as values.

Raises:

  • ValueError: If axis is out of the range [-(R+1), R+1).

출처: API r1.4


Tensorflow tf.stack 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [[1, 2, 3], [4, 5, 6]]

# [[7, 8, 9], [10, 11, 12]]

const1 = tf.constant(np.array([1, 2, 3]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1 2 3]

In [3]:

const2 = tf.constant(np.array([4, 5, 6]), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(3,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[4 5 6]

In [4]:

const3 = tf.constant(np.array([7, 8, 9]), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(3,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[7 8 9]

In [5]:

pack_const1 = tf.stack([const1, const2, const3])

print(pack_const1)

print(tf.shape(pack_const1))

tfutil.print_operation_value(pack_const1)

Tensor("stack:0", shape=(3, 3), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [7 8 9]]

In [6]:

pack_const1 = tf.stack([const1, const2, const3], axis=1)

print(pack_const1)

print(tf.shape(pack_const1))

tfutil.print_operation_value(pack_const1)

Tensor("stack_1:0", shape=(3, 3), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[1 4 7]

 [2 5 8]

 [3 6 9]]


tf.unstack(value, num=None, axis=0, name='unstack')


Defined in tensorflow/python/ops/array_ops.py.
See the guide: Tensor Transformations > Slicing and Joining

Unpacks the given dimension of a rank-R tensor into rank-(R-1) tensors.Unpacks num tensors from value by chipping it along the axis dimension. If num is not specified (the default), it is inferred from value's shape. If value.shape[axis] is not known, ValueError is raised.

For example, given a tensor of shape (A, B, C, D);

If axis == 0 then the i'th tensor in output is the slice value[i, :, :, :] and each tensor in output will have shape (B, C, D). (Note that the dimension unpacked along is gone, unlike split).

If axis == 1 then the i'th tensor in output is the slice value[:, i, :, :] and each tensor in output will have shape (A, C, D). Etc.

This is the opposite of stack. The numpy equivalent is

tf.unstack(x, n) = np.unstack(x)

Args:

  • value: A rank R > 0 Tensor to be unstacked.
  • num: An int. The length of the dimension axis. Automatically inferred if None (the default).
  • axis: An int. The axis to unstack along. Defaults to the first dimension. Negative values wrap around, so the valid range is [-R, R).
  • name: A name for the operation (optional).

Returns:
The list of Tensor objects unstacked from value.


Raises:

  • ValueError: If num is unspecified and cannot be inferred.
  • ValueError: If axis is out of the range [-R, R).

출처: 텐서 변환


Tensorflow tf.unstack 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

const1 = tf.constant(np.array([1, 2, 3]), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1 2 3]

In [3]:

const2 = tf.constant(np.array([4, 5, 6]), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(3,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[4 5 6]

In [4]:

const3 = tf.constant(np.array([7, 8, 9]), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(3,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[7 8 9]

In [5]:

pack_const1 = tf.stack([const1, const2, const3])

print(pack_const1)

print(tf.shape(pack_const1))

tfutil.print_operation_value(pack_const1)

Tensor("stack:0", shape=(3, 3), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [7 8 9]]

In [6]:

up_const1, up_const2, up_const3 = tf.unstack(pack_const1)

print(up_const1)

print(tf.shape(up_const1))

tfutil.print_constant(up_const1)

Tensor("unstack:0", shape=(3,), dtype=int32)

Tensor("Shape_4:0", shape=(1,), dtype=int32)

[1 2 3]

In [7]:

print(up_const2)

print(tf.shape(up_const2))

tfutil.print_constant(up_const2)

Tensor("unstack:1", shape=(3,), dtype=int32)

Tensor("Shape_5:0", shape=(1,), dtype=int32)

[4 5 6]

In [8]:

print(up_const3)

print(tf.shape(up_const3))

tfutil.print_constant(up_const3)

Tensor("unstack:2", shape=(3,), dtype=int32)

Tensor("Shape_6:0", shape=(1,), dtype=int32)

[7 8 9]

In [9]:

pack_const1 = tf.stack([const1, const2, const3], axis=1)

print(pack_const1)

print(tf.shape(pack_const1))

tfutil.print_operation_value(pack_const1)

Tensor("stack_1:0", shape=(3, 3), dtype=int32)

Tensor("Shape_7:0", shape=(2,), dtype=int32)

[[1 4 7]

 [2 5 8]

 [3 6 9]]

In [10]:

up_const1, up_const2, up_const3 = tf.unstack(pack_const1)

print(up_const1)

print(tf.shape(up_const1))

tfutil.print_constant(up_const1)

Tensor("unstack_1:0", shape=(3,), dtype=int32)

Tensor("Shape_8:0", shape=(1,), dtype=int32)

[1 4 7]

In [11]:

print(up_const2)

print(tf.shape(up_const2))

tfutil.print_constant(up_const2)

Tensor("unstack_1:1", shape=(3,), dtype=int32)

Tensor("Shape_9:0", shape=(1,), dtype=int32)

[2 5 8]

In [12]:

print(up_const3)

print(tf.shape(up_const3))

tfutil.print_constant(up_const3)

Tensor("unstack_1:2", shape=(3,), dtype=int32)

Tensor("Shape_10:0", shape=(1,), dtype=int32)

[3 6 9]


tf.reverse_sequence(input, seq_lengths, seq_dim, batch_dim=None, name=None)


텐서를 특정한 부분을 반전시킵니다.


이 함수는 먼저 input을 batch_dim 차원을 따라 여러 개의 슬라이스로 나눕니다. 그리고 각각의 슬라이스 i에서 seq_dim 차원을 따라 처음 seq_lengths[i]개의 원소들이 반전됩니다.


seq_lengths의 원소들은 seq_lengths[i] < input.dims[seq_dim]을 만족해야 하고, seq_lengths는 길이 input.dims[batch_dim]의 벡터여야 합니다.


반환될 텐서에서 batch_dim 차원의 i번째 슬라이스는, 입력 텐서의 i번째 슬라이스에서 seq_dim 차원을 따라 첫 seq_lengths[i] 개의 원소들이 반전된 것과 같습니다.


예시:

# 다음과 같이 설정합니다.

batch_dim = 0

seq_dim = 1

input.dims = (4, 8, ...)

seq_lengths = [7, 2, 3, 5]


# 입력 텐서의 각각의 슬라이스는 seq_dim 차원에서 seq_lengths 까지 반전됩니다.

output[0, 0:7, :, ...] = input[0, 7:0:-1, :, ...]

output[1, 0:2, :, ...] = input[1, 2:0:-1, :, ...]

output[2, 0:3, :, ...] = input[2, 3:0:-1, :, ...]

output[3, 0:5, :, ...] = input[3, 5:0:-1, :, ...]


# seq_lengths 이후의 부분은 그대로 들어갑니다.

output[0, 7:, :, ...] = input[0, 7:, :, ...]

output[1, 2:, :, ...] = input[1, 2:, :, ...]

output[2, 3:, :, ...] = input[2, 3:, :, ...]

output[3, 2:, :, ...] = input[3, 2:, :, ...]


다른 예시:

# 다음과 같이 설정합니다.
batch_dim = 2
seq_dim = 0
input.dims = (8, ?, 4, ...)
seq_lengths = [7, 2, 3, 5]

# 입력 텐서의 각각의 슬라이스는 seq_dim 차원에서 seq_lengths 까지 반전됩니다.
output[0:7, :, 0, :, ...] = input[7:0:-1, :, 0, :, ...]
output[0:2, :, 1, :, ...] = input[2:0:-1, :, 1, :, ...]
output[0:3, :, 2, :, ...] = input[3:0:-1, :, 2, :, ...]
output[0:5, :, 3, :, ...] = input[5:0:-1, :, 3, :, ...]

# seq_lengths 이후의 부분은 그대로 들어갑니다.
output[7:, :, 0, :, ...] = input[7:, :, 0, :, ...]
output[2:, :, 1, :, ...] = input[2:, :, 1, :, ...]
output[3:, :, 2, :, ...] = input[3:, :, 2, :, ...]
output[2:, :, 3, :, ...] = input[2:, :, 3, :, ...]
인자:
  • inputTensor. 반전시킬 텐서.
  • seq_lengthsint64형 1-D Tensor. 길이는 input.dims(batch_dim) 이며, max(seq_lengths) < input.dims(seq_dim)을 만족합니다.
  • seq_dimint. (부분적으로) 반전되는 차원.
  • batch_dimint. 텐서의 반전이 이루어지는 차원, 기본값은 0. (선택사항)
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형과 구조(shape)의 Tensorinput의 일부분이 반전되어 있습니다.


출처: 텐서 변환


Tensorflow tf.reverse_sequence 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[1, 2, 3, 4, 0, 0, 0],

     [1, 2, 3, 0, 0, 0, 0],

     [1, 2, 3, 4, 5, 6, 7]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3, 7), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3 4 0 0 0]

 [1 2 3 0 0 0 0]

 [1 2 3 4 5 6 7]]

In [3]:

seq_lens = [4, 3, 7]

rs_const1 = tf.reverse_sequence(const1, seq_lens, seq_dim=1, batch_dim=0)

print(rs_const1)

print(tf.shape(rs_const1))

tfutil.print_operation_value(rs_const1)

Tensor("ReverseSequence:0", shape=(3, 7), dtype=int32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[4 3 2 1 0 0 0]

 [3 2 1 0 0 0 0]

 [7 6 5 4 3 2 1]]

In [4]:

x = [[[1, 2, 3, 4, 0, 0, 0], [1, 0, 2, 0, 0, 0, 0]],

     [[1, 2, 3, 4, 5, 0, 0], [0, 2, 1, 4, 0, 0, 0]],

     [[1, 2, 3, 4, 5, 6 ,7], [1, 2, 3, 4, 0, 6, 0]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(3, 2, 7), dtype=int32)

Tensor("Shape_2:0", shape=(3,), dtype=int32)

[[[1 2 3 4 0 0 0]

  [1 0 2 0 0 0 0]]

 [[1 2 3 4 5 0 0]

  [0 2 1 4 0 0 0]]

 [[1 2 3 4 5 6 7]

  [1 2 3 4 0 6 0]]]

In [5]:

seq_lens = [4, 3, 5]

rs_const2 = tf.reverse_sequence(const2, seq_lens, seq_dim=2, batch_dim=0)

print(rs_const2)

print(tf.shape(rs_const2))

tfutil.print_operation_value(rs_const2)

Tensor("ReverseSequence_1:0", shape=(3, 2, 7), dtype=int32)

Tensor("Shape_3:0", shape=(3,), dtype=int32)

[[[4 3 2 1 0 0 0]

  [0 2 0 1 0 0 0]]

 [[3 2 1 4 5 0 0]

  [1 2 0 4 0 0 0]]

 [[5 4 3 2 1 6 7]

  [0 4 3 2 1 6 0]]]

In [6]:

seq_lens = [4, 3]

rs_const2 = tf.reverse_sequence(const2, seq_lens, seq_dim=2, batch_dim=1)

print(rs_const2)

print(tf.shape(rs_const2))

tfutil.print_operation_value(rs_const2)

Tensor("ReverseSequence_2:0", shape=(3, 2, 7), dtype=int32)

Tensor("Shape_4:0", shape=(3,), dtype=int32)

[[[4 3 2 1 0 0 0]

  [2 0 1 0 0 0 0]]

 [[4 3 2 1 5 0 0]

  [1 2 0 4 0 0 0]]

 [[4 3 2 1 5 6 7]

  [3 2 1 4 0 6 0]]]


tf.reverse(tensor, dims, name=None)


텐서의 특정 차원을 반전시킵니다.


tensor와 그 텐서의 각 차원에 해당하는 bool형 텐서 dims가 주어졌을 때, 이 함수는 dims[i]가 True인 경우 tensor의 차원 i를 반전시킵니다.


tensor는 차원을 8개까지 가질 수 있습니다. tensor의 차원의 수는 dims의 원소의 수와 동일해야 합니다. 즉, 다음의 식이 성립해야 합니다.

rank(tensor) = size(dims)

예시:

# tensor 't'는 [[[[ 0,  1,  2,  3],

#                 [ 4,  5,  6,  7],

#                 [ 8,  9, 10, 11]],

#                [[12, 13, 14, 15],

#                 [16, 17, 18, 19],

#                 [20, 21, 22, 23]]]]

# tensor 't'의 구조(shape)는 [1, 2, 3, 4]


# 'dims'가 [3] 일 때

reverse(t, dims) ==> [[[[ 3,  2,  1,  0],

                        [ 7,  6,  5,  4],

                        [ 11, 10, 9, 8]],

                       [[15, 14, 13, 12],

                        [19, 18, 17, 16],

                        [23, 22, 21, 20]]]]


# 'dims'가 [1] 일 때

reverse(t, dims) ==> [[[[12, 13, 14, 15],

                        [16, 17, 18, 19],

                        [20, 21, 22, 23]

                       [[ 0,  1,  2,  3],

                        [ 4,  5,  6,  7],

                        [ 8,  9, 10, 11]]]]


# 'dims'가 [2] 일 때

reverse(t, dims) ==> [[[[8, 9, 10, 11],

                        [4, 5, 6, 7],

                        [0, 1, 2, 3]]

                       [[20, 21, 22, 23],

                        [16, 17, 18, 19],

                        [12, 13, 14, 15]]]]

인자:
  • tensorTensor. 자료형이 uint8int8int32boolhalffloat32float64 중 하나여야 합니다. Up to 8-D.
  • dimsbool형 1-D Tensor. 반전시킬 차원을 나타냅니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

tensor와 자료형과 구조(shape)가 같은 Tensor.


출처: 텐서 변환


Tensorflow tf.reverse 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[ 0123],

        [ 4567],

        [ 89, 10, 11]],

        [[12, 13, 14, 15],

        [16, 17, 18, 19],

        [20, 21, 22, 23]]]]

 

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 2, 3, 4), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[ 0  1  2  3]

   [ 4  5  6  7]

   [ 8  9 10 11]]

  [[12 13 14 15]

   [16 17 18 19]

   [20 21 22 23]]]]

In [3]:

dims = [3]

dims_const1 = tf.reverse(const1, dims)

print(dims_const1)

print(tf.shape(dims_const1))

tfutil.print_operation_value(dims_const1)

Tensor("ReverseV2:0", shape=(1, 2, 3, 4), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[ 3  2  1  0]

   [ 7  6  5  4]

   [11 10  9  8]]

  [[15 14 13 12]

   [19 18 17 16]

   [23 22 21 20]]]]

In [4]:

dims = [1]

dims_const1 = tf.reverse(const1, dims)

print(dims_const1)

print(tf.shape(dims_const1))

tfutil.print_operation_value(dims_const1)

Tensor("ReverseV2_1:0", shape=(1, 2, 3, 4), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[12 13 14 15]

   [16 17 18 19]

   [20 21 22 23]]

  [[ 0  1  2  3]

   [ 4  5  6  7]

   [ 8  9 10 11]]]]

In [5]:

 dims = [2]

dims_const1 = tf.reverse(const1, dims)

print(dims_const1)

print(tf.shape(dims_const1))

tfutil.print_operation_value(dims_const1)

Tensor("ReverseV2_2:0", shape=(1, 2, 3, 4), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[ 8  9 10 11]

   [ 4  5  6  7]

   [ 0  1  2  3]]

  [[20 21 22 23]

   [16 17 18 19]

   [12 13 14 15]]]]


tf.transpose(a, perm=None, name='transpose')


a를 전치합니다. perm에 따라 차원의 순서를 구성합니다.


반환되는 텐서의 차원 i는 입력되는 텐서의 차원 perm[i]에 해당합니다. 만약 perm이 주어지지 않을 경우, (n-1...0)으로 설정됩니다. 여기서 n은 입력 텐서의 랭크(rank)입니다. 따라서, 기본적으로 이 함수는 2-D 텐서가 입력될 경우 일반적인 행렬 전치를 수행합니다.


예시:

# 'x'는 [[1 2 3]

#        [4 5 6]]

tf.transpose(x) ==> [[1 4]

                     [2 5]

                     [3 6]]


# perm의 기본값과 동일한 경우

tf.transpose(x, perm=[1, 0]) ==> [[1 4]

                                  [2 5]

                                  [3 6]]


# 'perm'은 차원이 n > 2인 텐서일 경우 더 유용합니다.

# 'x'는   [[[1  2  3]

#           [4  5  6]]

#          [[7  8  9]

#           [10 11 12]]]

# 차원-0의 행렬들에 대해서 전치를 수행합니다.

tf.transpose(x, perm=[0, 2, 1]) ==> [[[1  4]

                                      [2  5]

                                      [3  6]]


                                     [[7 10]

                                      [8 11]

                                      [9 12]]]

인자:
  • aTensor.
  • perma의 차원들의 순열.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

전치된 Tensor.


출처: 텐서 변환


Tensorflow tf.transpose 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

'''

A=[2,3,4] matrix, using perm(1,0,2) will get B=[3,2,4]

 

Index = (0,1,2)

A     = [2,3,4]

Perm  = (1,0,2)

B     = (3,2,4)  --> Perm 1 from Index 1 (3), Perm 0 from Index 0 (2), Perm 2 from Index 2 (4) --> so get (3,2,4

'''

In [3]:

x = [[1, 2, 3, 4, 5, 6]]

 

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 6), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3 4 5 6]]

In [4]:

perm = [1, 0]

trans_const1 = tf.transpose(const1, perm)

print(trans_const1)

print(tf.shape(trans_const1))

tfutil.print_operation_value(trans_const1)

Tensor("transpose:0", shape=(6, 1), dtype=int32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[1]

 [2]

 [3]

 [4]

 [5]

 [6]]

In [5]:

perm = [0, 1]

trans_const1 = tf.transpose(const1, perm)

print(trans_const1)

print(tf.shape(trans_const1))

tfutil.print_operation_value(trans_const1)

Tensor("transpose_1:0", shape=(1, 6), dtype=int32)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[1 2 3 4 5 6]]

In [6]:

x = [[1, 2, 3], [4, 5, 6]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2, 3), dtype=int32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]]

In [7]:

perm = [1, 0]

trans_const2 = tf.transpose(const2, perm)

print(trans_const2)

print(tf.shape(trans_const2))

tfutil.print_operation_value(trans_const2)

Tensor("transpose_2:0", shape=(3, 2), dtype=int32)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[1 4]

 [2 5]

 [3 6]]

In [8]:

perm = [0, 1]

trans_const2 = tf.transpose(const2, perm)

print(trans_const2)

print(tf.shape(trans_const2))

tfutil.print_operation_value(trans_const2)

Tensor("transpose_3:0", shape=(2, 3), dtype=int32)

Tensor("Shape_5:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]]

In [9]:

x = [[[ 123],

      [ 456]],

     [[ 789],

      [10, 11, 12]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(2, 2, 3), dtype=int32)

Tensor("Shape_6:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 4  5  6]]

 [[ 7  8  9]

  [10 11 12]]]

In [10]:

perm = [1, 0, 2]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_4:0", shape=(2, 2, 3), dtype=int32)

Tensor("Shape_7:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 7  8  9]]

 [[ 4  5  6]

  [10 11 12]]]

In [11]:

perm = [2, 0, 1]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_5:0", shape=(3, 2, 2), dtype=int32)

Tensor("Shape_8:0", shape=(3,), dtype=int32)

[[[ 1  4]

  [ 7 10]]

 [[ 2  5]

  [ 8 11]]

 [[ 3  6]

  [ 9 12]]]

In [12]:

perm = [2, 1, 0]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_6:0", shape=(3, 2, 2), dtype=int32)

Tensor("Shape_9:0", shape=(3,), dtype=int32)

[[[ 1  7]

  [ 4 10]]

 [[ 2  8]

  [ 5 11]]

 [[ 3  9]

  [ 6 12]]]

In [13]:

perm = [1, 2, 0]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_7:0", shape=(2, 3, 2), dtype=int32)

Tensor("Shape_10:0", shape=(3,), dtype=int32)

[[[ 1  7]

  [ 2  8]

  [ 3  9]]

 [[ 4 10]

  [ 5 11]

  [ 6 12]]]

In [14]:

perm = [0, 2, 1]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_8:0", shape=(2, 3, 2), dtype=int32)

Tensor("Shape_11:0", shape=(3,), dtype=int32)

[[[ 1  4]

  [ 2  5]

  [ 3  6]]

 [[ 7 10]

  [ 8 11]

  [ 9 12]]]

In [15]:

perm = [0, 1, 2]

trans_const3 = tf.transpose(const3, perm)

print(trans_const3)

print(tf.shape(trans_const3))

tfutil.print_operation_value(trans_const3)

Tensor("transpose_9:0", shape=(2, 2, 3), dtype=int32)

Tensor("Shape_12:0", shape=(3,), dtype=int32)

[[[ 1  2  3]

  [ 4  5  6]]

 [[ 7  8  9]

  [10 11 12]]]


tf.extract_image_patches(images, padding, ksizes=None, strides=None, rates=None, name=None)


images에서 패치(patch)들을 추출하여 출력의 "depth" 차원에 넣습니다.

인자:
  • imagesTensor. 자료형이 float32float64int32int64uint8int16int8uint16half 중 하나여야 합니다. 구조(shape)가 [batch, in_rows, in_cols, depth]인 4-D 텐서입니다.
  • padding"SAME" 또는 "VALID"string. 사용할 패딩 알고리즘을 선택합니다.


    크기와 관련된 인자는 다음과 같이 정해집니다:

    ksizes = [1, ksize_rows, ksize_cols, 1]
    strides = [1, strides_rows, strides_cols, 1]
    rates = [1, rates_rows, rates_cols, 1]
  • ksizesint들의 리스트. 기본값은 []images의 각 차원에 대한 슬라이딩 윈도우의 크기를 지정합니다. (선택사항)

  • stridesint들의 리스트. 기본값은 []. 길이 4의 1-D 텐서. 이미지에서 추출할 두 patch 사이의 중심 거리를 지정합니다. [1, stride_rows, stride_cols, 1]와 같은 형태여야 합니다. (선택사항)
  • ratesint들의 리스트. 기본값은 []. 길이 4의 1-D 텐서. 입력의 스트라이드로, 입력에서 두 연속된 patch 샘플들이 얼마나 멀리 떨어져 있어야 할 지 지정합니다. [1, rate_rows, rate_cols, 1]와 같은 형태여야 합니다. (선택사항) patch를 추출할 때 patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)으로 놓고 공간적으로 rates의 인자로 부차추출(subsampling)하는 것과 동일합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

images와 자료형이 같은 Tensor. 구조(shape)가 [batch, out_rows, out_cols, ksize_rows * ksize_cols * depth]인 4-D 텐서입니다. 크기가 ksize_rows x ksize_cols x depth인 "depth" 차원에서 벡터화된 이미지 패치(patch)들을 포함합니다.


출처: 텐서 변환


Tensorflow tf.extract_image_patches 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

n = 10

# images is a 1 x 10 x 10 x 1 array that contains the numbers 1 through 100 in order

images = [[[[x * n + y + 1] for y in range(n)] for x in range(n)]]

 

const1 = tf.constant(np.array(images), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 10, 10, 1), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[  1]

   [  2]

   [  3]

   [  4]

   [  5]

   [  6]

   [  7]

   [  8]

   [  9]

   [ 10]]

  [[ 11]

   [ 12]

   [ 13]

   [ 14]

   [ 15]

   [ 16]

   [ 17]

   [ 18]

   [ 19]

   [ 20]]

……………

  [[ 91]

   [ 92]

   [ 93]

   [ 94]

   [ 95]

   [ 96]

   [ 97]

   [ 98]

   [ 99]

   [100]]]]

In [3]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (1 x 1 x 1 ) = 1

# ksizes: raws: [1] col: [1]

ksizes = [1, 1, 1, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[  1]

   [  4]

   [  7]

   [ 10]]

  [[ 31]

   [ 34]

   [ 37]

   [ 40]]

  [[ 61]

   [ 64]

   [ 67]

   [ 70]]

  [[ 91]

   [ 94]

   [ 97]

   [100]]]]

In [4]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (1 x 2 x 1 ) = 2

# ksizes: raws: [1, 2]  col: [1, 2]

ksizes = [1, 1, 2, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_1:0", shape=(1, 4, 3, 2), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[ 1  2]

   [ 4  5]

   [ 7  8]]

  [[31 32]

   [34 35]

   [37 38]]

  [[61 62]

   [64 65]

   [67 68]]

  [[91 92]

   [94 95]

   [97 98]]]]

In [5]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (1 x 3 x 1 ) = 3

# ksizes: raws: [1, 2, 3]   col: [1, 2, 3]

ksizes = [1, 1, 3, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_2:0", shape=(1, 4, 3, 3), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]

   [ 4  5  6]

   [ 7  8  9]]

  [[31 32 33]

   [34 35 36]

   [37 38 39]]

  [[61 62 63]

   [64 65 66]

   [67 68 69]]

  [[91 92 93]

   [94 95 96]

   [97 98 99]]]]

In [6]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (2 x 3 x 1 ) = 6 -> [ 1  2  3 11 12 13] ..

# ksizes: raws: [1  2  3 ]   col: [1  2  3 11 12 13]

ksizes = [1, 2, 3, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_3:0", shape=(1, 3, 3, 6), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13]

   [ 4  5  6 14 15 16]

   [ 7  8  9 17 18 19]]

  [[31 32 33 41 42 43]

   [34 35 36 44 45 46]

   [37 38 39 47 48 49]]

  [[61 62 63 71 72 73]

   [64 65 66 74 75 76]

   [67 68 69 77 78 79]]]]

In [7]:

# Ksizes Test

# output_depth = ksize_rows * ksize_cols * depth = (3 x 3 x 1 ) = 9 -> [ 1 2 3 11 12 13 21 22 23] ..

# ksizes: raws: [1  2  3 ]   col: [1  2  3 11 12 13 21 22 23]

ksizes = [1, 3, 3, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_4:0", shape=(1, 3, 3, 9), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 4  5  6 14 15 16 24 25 26]

   [ 7  8  9 17 18 19 27 28 29]]

  [[31 32 33 41 42 43 51 52 53]

   [34 35 36 44 45 46 54 55 56]

   [37 38 39 47 48 49 57 58 59]]

  [[61 62 63 71 72 73 81 82 83]

   [64 65 66 74 75 76 84 85 86]

   [67 68 69 77 78 79 87 88 89]]]]

In [8]:

# strides Test

# output_depth = ksize_rows * ksize_cols * depth = (3 x 3 x 1 ) = 9 -> [ 1 2 3 11 12 13 21 22 23] ..

# strides: raws: [1, 4, 7]   col: [1, 31, 61]

ksizes = [1, 3, 3, 1]

strides = [1, 3, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_5:0", shape=(1, 3, 3, 9), dtype=int32)

Tensor("Shape_6:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 4  5  6 14 15 16 24 25 26]

   [ 7  8  9 17 18 19 27 28 29]]

  [[31 32 33 41 42 43 51 52 53]

   [34 35 36 44 45 46 54 55 56]

   [37 38 39 47 48 49 57 58 59]]

  [[61 62 63 71 72 73 81 82 83]

   [64 65 66 74 75 76 84 85 86]

   [67 68 69 77 78 79 87 88 89]]]]

In [9]:

# strides Test

# output_depth = ksize_rows * ksize_cols * depth = (3 x 3 x 1 ) = 9 -> [ 1 2 3 11 12 13 21 22 23] ..

# strides: raws: [1, 4, 7]   col: [1, 21, 41, 61]

ksizes = [1, 3, 3, 1]

strides = [1, 2, 3, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_6:0", shape=(1, 4, 3, 9), dtype=int32)

Tensor("Shape_7:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 4  5  6 14 15 16 24 25 26]

   [ 7  8  9 17 18 19 27 28 29]]

  [[21 22 23 31 32 33 41 42 43]

   [24 25 26 34 35 36 44 45 46]

   [27 28 29 37 38 39 47 48 49]]

  [[41 42 43 51 52 53 61 62 63]

   [44 45 46 54 55 56 64 65 66]

   [47 48 49 57 58 59 67 68 69]]

  [[61 62 63 71 72 73 81 82 83]

   [64 65 66 74 75 76 84 85 86]

   [67 68 69 77 78 79 87 88 89]]]]

In [10]:

# strides Test

# output_depth = ksize_rows * ksize_cols * depth = (3 x 3 x 1 ) = 9 -> [ 1 2 3 11 12 13 21 22 23] ..

# strides: raws: [1, 3, 5, 7]   col: [1, 31, 61]

ksizes = [1, 3, 3, 1]

strides = [1, 3, 2, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_7:0", shape=(1, 3, 4, 9), dtype=int32)

Tensor("Shape_8:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 3  4  5 13 14 15 23 24 25]

   [ 5  6  7 15 16 17 25 26 27]

   [ 7  8  9 17 18 19 27 28 29]]

  [[31 32 33 41 42 43 51 52 53]

   [33 34 35 43 44 45 53 54 55]

   [35 36 37 45 46 47 55 56 57]

   [37 38 39 47 48 49 57 58 59]]

  [[61 62 63 71 72 73 81 82 83]

   [63 64 65 73 74 75 83 84 85]

   [65 66 67 75 76 77 85 86 87]

   [67 68 69 77 78 79 87 88 89]]]]

In [11]:

# We generate four outputs as follows:

# 1. 3x3 patches with stride length 5

ksizes = [1, 3, 3, 1]

strides = [1, 5, 5, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_8:0", shape=(1, 2, 2, 9), dtype=int32)

Tensor("Shape_9:0", shape=(4,), dtype=int32)

[[[[ 1  2  3 11 12 13 21 22 23]

   [ 6  7  8 16 17 18 26 27 28]]

  [[51 52 53 61 62 63 71 72 73]

   [56 57 58 66 67 68 76 77 78]]]]

In [12]:

# 2. Same as above, but the rate is increased to 2

ksizes = [1, 3, 3, 1]

strides = [1, 5, 5, 1]

rates = [1, 2, 2, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_9:0", shape=(1, 2, 2, 9), dtype=int32)

Tensor("Shape_10:0", shape=(4,), dtype=int32)

[[[[  1   3   5  21  23  25  41  43  45]

   [  6   8  10  26  28  30  46  48  50]]

  [[ 51  53  55  71  73  75  91  93  95]

   [ 56  58  60  76  78  80  96  98 100]]]]

In [13]:

# 3. 4x4 patches with stride length 7; only one patch should be generated

ksizes = [1, 4, 4, 1]

strides = [1, 7, 7, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='VALID')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_10:0", shape=(1, 1, 1, 16), dtype=int32)

Tensor("Shape_11:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4 11 12 13 14 21 22 23 24 31 32 33 34]]]]

In [14]:

# 4. Same as above, but with padding set to 'SAME'

ksizes = [1, 4, 4, 1]

strides = [1, 7, 7, 1]

rates = [1, 1, 1, 1]

exi_const1 = tf.extract_image_patches(const1, ksizes, strides, rates, padding='SAME')

print(exi_const1)

print(tf.shape(exi_const1))

tfutil.print_operation_value(exi_const1)

Tensor("ExtractImagePatches_11:0", shape=(1, 2, 2, 16), dtype=int32)

Tensor("Shape_12:0", shape=(4,), dtype=int32)

[[[[  1   2   3   4  11  12  13  14  21  22  23  24  31  32  33  34]

   [  8   9  10   0  18  19  20   0  28  29  30   0  38  39  40   0]]

  [[ 71  72  73  74  81  82  83  84  91  92  93  94   0   0   0   0]

   [ 78  79  80   0  88  89  90   0  98  99 100   0   0   0   0   0]]]]


tf.space_to_batch(input, paddings, block_size, name=None)


타입 T의 4-D 텐서에 대한 SpaceToBatch 함수입니다.


텐서에 제로 패딩을 붙이고 공간적인 데이터의 블록을 batch로 재배열합니다. 구체적으로, 이 함수는 입력 텐서의 height와 width 차원이 batch 차원으로 옮겨진 복사본을 반환합니다. 제로 패딩이 행해진 뒤, 입력 텐서의 height와 width 값 모두 블록 크기로 나눌 수 있어야 합니다.

인자:
  • input: 구조(shape)가 [batch, height, width, depth]인 4-D Tensor.
  • paddingsint32형 2-D Tensor. 구조(shape)가 [2, 2]이며, 음이 아닌 정수로 구성됩니다. 입력을 공간 차원에서 어떻게 패딩할 것인지에 대해 다음과 같은 형태로 지정합니다.

    paddings = [[pad_top, pad_bottom], [pad_left, pad_right]]

    입력 텐서에서 패딩이 이루어지면 다음과 같은 공간 차원들을 가지게 됩니다.

    height_pad = pad_top + height + pad_bottom
    width_pad = pad_left + width + pad_right

    block_size는 1보다 커야 합니다. 이는 블록의 크기를 지정합니다.


    • height와 width 차원에서 block_size x block_size의 크기를 가지는 블록들은 각 위치에서 batch 차원으로 재배열됩니다.
    • 출력 텐서의 배치(batch)는 batch * block_size * block_size와 같습니다.
    • block_size가 height_pad와 width_pad의 약수여야 합니다.


      출력 텐서의 구조는 다음과 같습니다.

      [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]

  • block_sizeint.


  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.space_to_batch 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[1], [2]], [[3], [4]]]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [3]:

# return: [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]

# paddings = [[pad_top, pad_bottom], [pad_left, pad_right]]

# height_pad = pad_top + height + pad_bottom

# width_pad = pad_left + width + pad_right

# blocksize = Both height_pad and width_pad must be divisible by block_size.

paddings = [[0, 0],[0, 0]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [4]:

paddings = [[0, 0],[0, 1]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_1:0", shape=(1, 2, 3, 1), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[1]

   [2]

   [0]]

  [[3]

   [4]

   [0]]]]

In [5]:

paddings = [[0, 0],[1, 1]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_2:0", shape=(1, 2, 4, 1), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[0]

   [1]

   [2]

   [0]]

  [[0]

   [3]

   [4]

   [0]]]]

In [6]:

paddings = [[0, 1],[1, 1]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_3:0", shape=(1, 3, 4, 1), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[[[[0]

   [1]

   [2]

   [0]]

  [[0]

   [3]

   [4]

   [0]]

  [[0]

   [0]

   [0]

   [0]]]]

In [7]:

paddings = [[1, 1],[1, 1]]

blocksize = 1

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_4:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[0]

   [0]

   [0]

   [0]]

  [[0]

   [1]

   [2]

   [0]]

  [[0]

   [3]

   [4]

   [0]]

  [[0]

   [0]

   [0]

   [0]]]]

In [8]:

paddings = [[0, 0],[0, 0]]

blocksize = 2

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_5:0", shape=(4, 1, 1, 1), dtype=int32)

Tensor("Shape_6:0", shape=(4,), dtype=int32)

[[[[1]]]

 [[[2]]]

 [[[3]]]

 [[[4]]]]

In [9]:

# [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]

# blocksize = Both height_pad and width_pad must be divisible by block_size.

paddings = [[0, 0],[1, 1]]

blocksize = 2

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_6:0", shape=(4, 1, 2, 1), dtype=int32)

Tensor("Shape_7:0", shape=(4,), dtype=int32)

[[[[0]

   [2]]]

 [[[1]

   [0]]]

 [[[0]

   [4]]]

 [[[3]

   [0]]]]

In [10]:

# [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]

# blocksize = Both height_pad and width_pad must be divisible by block_size.

paddings = [[1, 1],[1, 1]]

blocksize = 2

stb_const1 = tf.space_to_batch(const1, paddings, blocksize)

print(stb_const1)

print(tf.shape(stb_const1))

tfutil.print_operation_value(stb_const1)

Tensor("SpaceToBatchND_7:0", shape=(4, 2, 2, 1), dtype=int32)

Tensor("Shape_8:0", shape=(4,), dtype=int32)

[[[[0]

   [0]]

  [[0]

   [4]]]

 [[[0]

   [0]]

  [[3]

   [0]]]

 [[[0]

   [2]]

  [[0]

   [0]]]

 [[[1]

   [0]]

  [[0]

   [0]]]]

In [11]:

x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(1, 2, 2, 3), dtype=int32)

Tensor("Shape_9:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]

   [ 4  5  6]]

  [[ 7  8  9]

   [10 11 12]]]]

In [12]:

paddings = [[0, 0],[0, 0]]

blocksize = 2

stb_const2 = tf.space_to_batch(const2, paddings, blocksize)

print(stb_const2)

print(tf.shape(stb_const2))

tfutil.print_operation_value(stb_const2)

Tensor("SpaceToBatchND_8:0", shape=(4, 1, 1, 3), dtype=int32)

Tensor("Shape_10:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]]]

 [[[ 4  5  6]]]

 [[[ 7  8  9]]]

 [[[10 11 12]]]]

In [13]:

x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]], [[9], [10], [11], [12]], [[13], [14], [15], [16]]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_11:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]]

  [[ 5]

   [ 6]

   [ 7]

   [ 8]]

  [[ 9]

   [10]

   [11]

   [12]]

  [[13]

   [14]

   [15]

   [16]]]]

In [14]:

paddings = [[0, 0],[0, 0]]

blocksize = 2

stb_const3 = tf.space_to_batch(const3, paddings, blocksize)

print(stb_const3)

print(tf.shape(stb_const3))

tfutil.print_operation_value(stb_const3)

Tensor("SpaceToBatchND_9:0", shape=(4, 2, 2, 1), dtype=int32)

Tensor("Shape_12:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 3]]

  [[ 9]

   [11]]]

 [[[ 2]

   [ 4]]

  [[10]

   [12]]]

 [[[ 5]

   [ 7]]

  [[13]

   [15]]]

 [[[ 6]

   [ 8]]

  [[14]

   [16]]]]

In [15]:

x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]]], [[[9], [10], [11], [12]], [[13], [14], [15], [16]]]]

const4 = tf.constant(np.array(x), dtype=tf.int32)

print(const4)

print(tf.shape(const4))

tfutil.print_constant(const4)

Tensor("Const_3:0", shape=(2, 2, 4, 1), dtype=int32)

Tensor("Shape_13:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]]

  [[ 5]

   [ 6]

   [ 7]

   [ 8]]]

 [[[ 9]

   [10]

   [11]

   [12]]

  [[13]

   [14]

   [15]

   [16]]]]

In [16]:

paddings = [[0, 0],[0, 0]]

blocksize = 2

stb_const4 = tf.space_to_batch(const4, paddings, blocksize)

print(stb_const4)

print(tf.shape(stb_const4))

tfutil.print_operation_value(stb_const4)

Tensor("SpaceToBatchND_10:0", shape=(8, 1, 2, 1), dtype=int32)

Tensor("Shape_14:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 3]]]

 [[[ 9]

   [11]]]

 [[[ 2]

   [ 4]]]

 [[[10]

   [12]]]

 [[[ 5]

   [ 7]]]

 [[[13]

   [15]]]

 [[[ 6]

   [ 8]]]

 [[[14]

   [16]]]]


tf.batch_to_space(input, crops, block_size, name=None)


타입 T의 4-D 텐서에 대한 BatchToSpace 함수입니다.


배치(batch)의 데이터를 공간적인 데이터의 블록으로 재배열하고 자릅니다. SpaceToBatch 함수의 역과정에 해당합니다. 더 구체적으로, 이 함수는 input 텐서의 batch 차원의 값들이 height와 width 차원의 공간적인 블록으로 이동된 후, height 차원과 width 차원을 따라 잘린 텐서를 반환합니다.

인자:
  • input: 4-D Tensor[batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]의 구조(shape)를 가집니다. 입력 텐서의 배치(batch) 크기는 block_size * block_size의 배수여야 합니다.
  • cropsint32형 구조 [2, 2]의 2-D 텐서. 음이 아닌 정수로 구성됩니다. 중간 결과에서 공간 차원을 따라 몇 개의 원소를 잘라낼 것인지를 다음과 같이 결정합니다.

    crops = [[crop_top, crop_bottom], [crop_left, crop_right]]
  • block_sizeint.

  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 구조 [batch, height, width, depth]인 4-D Tensor.

height = height_pad - crop_top - crop_bottom
width = width_pad - crop_left - crop_right

을 만족합니다. block_size는 1보다 커야 합니다.


출처: 텐서 변환


Tensorflow tf.batch_to_space 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[1]]], [[[2]]], [[[3]]], [[[4]]]]

 

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(4, 1, 1, 1), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[1]]]

 [[[2]]]

 [[[3]]]

 [[[4]]]]

In [3]:

# crops = [[crop_top, crop_bottom], [crop_left, crop_right]]

# [batch, height, width, depth]

# height = height_pad - crop_top - crop_bottom

# width = width_pad - crop_left - crop_right

 

corps = [[0, 0],[0, 1]]

blocksize = 1

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND:0", shape=(4, 1, 0, 1), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[]

In [4]:

corps = [[0, 0],[0, 1]]

blocksize = 1

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_1:0", shape=(4, 1, 0, 1), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[]

In [5]:

corps = [[0, 1],[0, 0]]

blocksize = 1

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_2:0", shape=(4, 0, 1, 1), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[]

In [6]:

corps = [[1, 0],[0, 0]]

blocksize = 1

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_3:0", shape=(4, 0, 1, 1), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[]

In [7]:

corps = [[0, 0],[0, 0]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_4:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [8]:

corps = [[0, 0],[1, 1]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_5:0", shape=(1, 2, 0, 1), dtype=int32)

Tensor("Shape_6:0", shape=(4,), dtype=int32)

[]

In [9]:

corps = [[1, 1],[0, 0]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_6:0", shape=(1, 0, 2, 1), dtype=int32)

Tensor("Shape_7:0", shape=(4,), dtype=int32)

[]

In [10]:

corps = [[1, 1],[1, 1]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_7:0", shape=(1, 0, 0, 1), dtype=int32)

Tensor("Shape_8:0", shape=(4,), dtype=int32)

[]

In [11]:

x = [[[[ 123]]],

 [[[ 456]]],

 [[[ 789]]],

 [[[10, 11, 12]]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(4, 1, 1, 3), dtype=int32)

Tensor("Shape_9:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]]]

 [[[ 4  5  6]]]

 [[[ 7  8  9]]]

 [[[10 11 12]]]]

In [12]:

corps = [[0, 0],[0, 0]]

blocksize = 2

bts_const1 = tf.batch_to_space(const1, corps, blocksize)

print(bts_const1)

print(tf.shape(bts_const1))

tfutil.print_operation_value(bts_const1)

Tensor("BatchToSpaceND_8:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape_10:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [13]:

x = [[[[1], [3]], [[9], [11]]],

     [[[2], [4]], [[10], [12]]],

     [[[5], [7]], [[13], [15]]],

     [[[6], [8]], [[14], [16]]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(4, 2, 2, 1), dtype=int32)

Tensor("Shape_11:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 3]]

  [[ 9]

   [11]]]

 [[[ 2]

   [ 4]]

  [[10]

   [12]]]

 [[[ 5]

   [ 7]]

  [[13]

   [15]]]

 [[[ 6]

   [ 8]]

  [[14]

   [16]]]]

In [14]:

corps = [[0, 0],[0, 0]]

blocksize = 2

bts_const3 = tf.batch_to_space(const3, corps, blocksize)

print(bts_const3)

print(tf.shape(bts_const3))

tfutil.print_operation_value(bts_const3)

Tensor("BatchToSpaceND_9:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_12:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]]

  [[ 5]

   [ 6]

   [ 7]

   [ 8]]

  [[ 9]

   [10]

   [11]

   [12]]

  [[13]

   [14]

   [15]

   [16]]]]

In [15]:

x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]],

     [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]]

const4 = tf.constant(np.array(x), dtype=tf.int32)

print(const4)

print(tf.shape(const4))

tfutil.print_constant(const4)

Tensor("Const_3:0", shape=(8, 1, 2, 1), dtype=int32)

Tensor("Shape_13:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 3]]]

 [[[ 9]

   [11]]]

 [[[ 2]

   [ 4]]]

 [[[10]

   [12]]]

 [[[ 5]

   [ 7]]]

 [[[13]

   [15]]]

 [[[ 6]

   [ 8]]]

 [[[14]

   [16]]]]

In [16]:

corps = [[0, 0],[0, 0]]

blocksize = 2

bts_const4 = tf.batch_to_space(const4, corps, blocksize)

print(bts_const4)

print(tf.shape(bts_const4))

tfutil.print_operation_value(bts_const4)

Tensor("BatchToSpaceND_10:0", shape=(2, 2, 4, 1), dtype=int32)

Tensor("Shape_14:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 3]

   [ 4]]

  [[ 5]

   [ 6]

   [ 7]

   [ 8]]]

 [[[ 9]

   [10]

   [11]

   [12]]

  [[13]

   [14]

   [15]

   [16]]]]


tf.space_to_depth(input, block_size, name=None)


타입 T의 4-D 텐서에 대한 SpaceToDepth 함수입니다.


공간적인 데이터의 블록을 depth로 재배열합니다. 구체적으로, 입력 텐서의 height와 width 차원의 데이터를 depth 차원으로 옮깁니다. block_size는 입력 텐서의 블록 사이즈와 데이터가 어떻게 옮겨질지를 지정합니다.

  • 크기 block_size x block size의 블록이 각 위치의 depth로 재배열됩니다.
  • 출력 텐서의 depth 차원의 크기는 input_depth * block_size * block_size입니다.
  • 입력 텐서의 height와 width는 block_size의 배수여야 합니다.

즉, 만약 입력의 구조(shape)가[batch, height, width, depth]이면, 출력 텐서의 구조는 [batch, height/block_size, width/block_size, epth*block_size*block_size]이 됩니다.


이 함수는 입력 텐서의 랭크(rank)가 4여야 하며, block_size가 1 이상이어야 하고 height와 width의 약수여야 합니다.


이 함수는 합성곱 연산 사이의 활성화에서 데이터를 그대로 유지한 채로 크기를 변경시키는 때 유용합니다(예로, 풀링 대신 사용할 수 있습니다). 합성곱 연산만으로 이루어진 모델의 훈련에도 유용합니다.


예로, 구조 [1, 2, 2, 1]의 입력과 block_size = 2가 주어진 경우,

x = [[[[1], [2]],
      [[3], [4]]]]

이 함수는 다음과 같은 구조 [1, 1, 1, 4]의 텐서를 반환합니다.

[[[[1, 2, 3, 4]]]]

여기서, 입력은 크기 1의 배치를 가지며, 각 배치는 구조 [2, 2, 1]로 배열된 원소를 가집니다. 출력에서 각각은 width와 height가 모두 1이고, 4 채널의 depth를 가지도록 배열되며, 따라서 각각은 구조 [1, 1, 4]를 가지게 됩니다.


더 큰 depth를 가지는 입력 텐서의 경우(여기서는 [1, 2, 2, 3])를 봅시다.

x = [[[[1, 2, 3], [4, 5, 6]],
      [[7, 8, 9], [10, 11, 12]]]]

block_size에 2를 넣어 이 함수를 적용할 경우, 구조 [1, 1, 1, 12]인 텐서

[[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]

를 출력합니다. 비슷하게, block_size가 2이고 입력의 구조가 [1 4 4 1]인 경우,

x = [[[[1],   [2],  [5],  [6]],

      [[3],   [4],  [7],  [8]],

      [[9],  [10], [13],  [14]],

      [[11], [12], [15],  [16]]]]

이 함수는 구조 [1 2 2 4]인 다음 텐서를 반환합니다.

x = [[[[1, 2, 3, 4],
       [5, 6, 7, 8]],
      [[9, 10, 11, 12],
       [13, 14, 15, 16]]]]
인자:
  • inputTensor.
  • block_sizeint. 공간 블록의 크기를 지정합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.space_to_depth 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[1], [2]],

      [[3], [4]]]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [3]:

# input: [batch, height, width, depth]

# output: [batch, height/block_size, width/block_size, depth*block_size*block_size]

blocksize = 2

std_const1 = tf.space_to_depth(const1, blocksize)

print(std_const1)

print(tf.shape(std_const1))

tfutil.print_operation_value(std_const1)

Tensor("SpaceToDepth:0", shape=(1, 1, 1, 4), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[1 2 3 4]]]]

In [4]:

x = [[[[1, 2, 3], [4, 5, 6]],

      [[7, 8, 9], [10, 11, 12]]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(1, 2, 2, 3), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]

   [ 4  5  6]]

  [[ 7  8  9]

   [10 11 12]]]]

In [5]:

blocksize = 2

std_const2 = tf.space_to_depth(const2, blocksize)

print(std_const2)

print(tf.shape(std_const2))

tfutil.print_operation_value(std_const2)

Tensor("SpaceToDepth_1:0", shape=(1, 1, 1, 12), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4  5  6  7  8  9 10 11 12]]]]

In [6]:

x = [[[[1],   [2],  [5],  [6]],

      [[3],   [4],  [7],  [8]],

      [[9],  [10], [13],  [14]],

      [[11], [12], [15],  [16]]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 5]

   [ 6]]

  [[ 3]

   [ 4]

   [ 7]

   [ 8]]

  [[ 9]

   [10]

   [13]

   [14]]

  [[11]

   [12]

   [15]

   [16]]]]

In [7]:

blocksize = 2

std_const3 = tf.space_to_depth(const3, blocksize)

print(std_const3)

print(tf.shape(std_const3))

tfutil.print_operation_value(std_const3)

Tensor("SpaceToDepth_2:0", shape=(1, 2, 2, 4), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4]

   [ 5  6  7  8]]

  [[ 9 10 11 12]

   [13 14 15 16]]]]


tf.depth_to_space(input, block_size, name=None)


타입 T의 4-D 텐서에 대한 DepthToSpace 함수입니다.


depth의 데이터를 공간적인 데이터의 블록으로 재배열합니다. SpaceToDepth 함수의 역과정과 같습니다. 구체적으로, 이 함수는 depth 차원의 값들을 height와 width 차원들의 공간적인 블록으로 이동시킵니다. block_size는 입력의 블록 크기와 데이터가 어떻게 이동될지를 지정합니다.

  • depth에서 block_size * block_size 크기의 데이터가 block_size x block_size의 블록으로 재배열됩니다.
  • 출력 텐서의 width의 크기는 input_depth * block_size이며, height의 크기는 input_height * block_size 입니다.
  • 입력 텐서의 depth는 block_size * block_size의 배수여야 합니다.

즉, 만약 입력의 구조(shape)가 [batch, height, width, depth]라면, 출력 텐서의 구조는[batch, height*block_size, width*block_size, depth/(block_size*block_size)]와 같습니다.


이 함수는 입력 텐서의 랭크(rank)가 4여야 하며, block_size는 1 이상이고 block_size * block_size가 입력 텐서의 depth의 약수여야 합니다.


이 함수는 합성곱 연산 사이의 활성화에서 데이터를 그대로 유지한 채로 크기를 변경시키는 때 유용합니다(예로, 풀링 대신 사용할 수 있습니다). 합성곱 연산만으로 이루어진 모델의 훈련에도 유용합니다.


예로, 구조 [1, 1, 1, 4]의 입력과 block_size = 2가 주어진 경우,

x = [[[[1, 2, 3, 4]]]]

이 함수는 다음과 같은 구조 [1, 2, 2, 1]의 텐서를 반환합니다.

  [[[[1], [2]],
     [[3], [4]]]]

여기서, 입력은 크기 1의 배치를 가지며, 각 배치는 구조 [1, 1, 4]로 배열된 원소를 가집니다. 출력에서 각각은 2x2 원소에 1 채널의 (1 = 4 / (block_size * block_size)depth를 가지도록 배열되며, 따라서 각각은 구조 [2, 2, 1]을 가지게 됩니다.


더 큰 depth를 가지는 입력 텐서의 경우(여기서는 [1, 1, 1, 12])를 봅시다.

x = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]

block_size에 2를 넣어 이 함수를 적용할 경우, 구조 [1, 2, 2, 3]인 텐서

   [[[[1, 2, 3], [4, 5, 6]],
     [[7, 8, 9], [10, 11, 12]]]]

를 출력합니다. 비슷하게, block_size가 2이고 입력의 구조가 [1 2 2 4]인 경우,

x =  [[[[1, 2, 3, 4],
       [5, 6, 7, 8]],
      [[9, 10, 11, 12],
       [13, 14, 15, 16]]]]

이 함수는 구조 [1 4 4 1]인 다음 텐서를 반환합니다.

x = [[ [1],   [2],  [5],  [6]],
     [ [3],   [4],  [7],  [8]],
     [ [9],  [10], [13],  [14]],
     [ [11], [12], [15],  [16]]]
인자:
  • inputTensor.
  • block_sizeint. 공간 블록의 크기를 지정합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.depth_to_space 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[[[1, 2, 3, 4]]]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1, 1, 1, 4), dtype=int32)

Tensor("Shape:0", shape=(4,), dtype=int32)

[[[[1 2 3 4]]]]

In [3]:

blocksize = 2

dts_const1 = tf.depth_to_space(const1, blocksize)

print(dts_const1)

print(tf.shape(dts_const1))

tfutil.print_operation_value(dts_const1)

Tensor("DepthToSpace:0", shape=(1, 2, 2, 1), dtype=int32)

Tensor("Shape_1:0", shape=(4,), dtype=int32)

[[[[1]

   [2]]

  [[3]

   [4]]]]

In [4]:

x = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]]

const2 = tf.constant(np.array(x), dtype=tf.int32)

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(1, 1, 1, 12), dtype=int32)

Tensor("Shape_2:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4  5  6  7  8  9 10 11 12]]]]

In [5]:

blocksize = 2

dts_const2 = tf.depth_to_space(const2, blocksize)

print(dts_const2)

print(tf.shape(dts_const2))

tfutil.print_operation_value(dts_const2)

Tensor("DepthToSpace_1:0", shape=(1, 2, 2, 3), dtype=int32)

Tensor("Shape_3:0", shape=(4,), dtype=int32)

[[[[ 1  2  3]

   [ 4  5  6]]

  [[ 7  8  9]

   [10 11 12]]]]

In [6]:

x =  [[[[1, 2, 3, 4],

       [5, 6, 7, 8]],

      [[9, 10, 11, 12],

       [13, 14, 15, 16]]]]

const3 = tf.constant(np.array(x), dtype=tf.int32)

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(1, 2, 2, 4), dtype=int32)

Tensor("Shape_4:0", shape=(4,), dtype=int32)

[[[[ 1  2  3  4]

   [ 5  6  7  8]]

  [[ 9 10 11 12]

   [13 14 15 16]]]]

In [7]:

blocksize = 2

dts_const3 = tf.depth_to_space(const3, blocksize)

print(dts_const3)

print(tf.shape(dts_const3))

tfutil.print_operation_value(dts_const3)

Tensor("DepthToSpace_2:0", shape=(1, 4, 4, 1), dtype=int32)

Tensor("Shape_5:0", shape=(4,), dtype=int32)

[[[[ 1]

   [ 2]

   [ 5]

   [ 6]]

  [[ 3]

   [ 4]

   [ 7]

   [ 8]]

  [[ 9]

   [10]

   [13]

   [14]]

  [[11]

   [12]

   [15]

   [16]]]]


tf.gather(params, indices, validate_indices=None, name=None)


indices에 따라 params에서 슬라이스를 모읍니다.


indices는 임의 차원의 정수 텐서여야 합니다(주로 0-D 또는 1-D). 구조(shape)가 indices.shape + params.shape[1:]인 출력 텐서를 생성합니다.

# Scalar indices
output[:, ..., :] = params[indices, :, ... :]

# Vector indices
output[i, :, ..., :] = params[indices[i], :, ... :]

# Higher rank indices
output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :]

만약 indices이 순열이고 len(indices) == params.shape[0]이라면, 이 함수는 그에 따라 params를 재배열합니다.


 
인자:
  • paramsTensor.
  • indicesint32형 또는 int64형 Tensor.
  • validate_indicesbool. 기본값은 True. (선택사항)
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

params와 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.gather 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[1, 2, 3],

     [4, 5, 6], 

     [7, 8, 9]]

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3, 3), dtype=int32)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2 3]

 [4 5 6]

 [7 8 9]]

In [3]:

idx_const2 = tf.constant([1, 0, 2])

print(idx_const2)

print(tf.shape(idx_const2))

tfutil.print_constant(idx_const2)

Tensor("Const_1:0", shape=(3,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 0 2]

In [4]:

idx_flattened = tf.range(0, const1.shape[0]) * const1.shape[1] + idx_const2

print(idx_flattened)

print(tf.shape(idx_flattened))

tfutil.print_constant(idx_flattened)

Tensor("add:0", shape=(3,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[1 3 8]

In [5]:

# partial code 1

print(const1.shape[0])

tmp1 = tf.range(0, const1.shape[0])

print(tmp1)

print(tf.shape(tmp1))

tfutil.print_constant(tmp1)

3

Tensor("range_1:0", shape=(3,), dtype=int32)

Tensor("Shape_3:0", shape=(1,), dtype=int32)

[0 1 2]

In [6]:

# partial code 2

print(const1.shape[1])

tmp2 = tf.range(0, const1.shape[0]) * const1.shape[1]

print(tmp2)

print(tf.shape(tmp2))

tfutil.print_constant(tmp2)

3

Tensor("mul_1:0", shape=(3,), dtype=int32)

Tensor("Shape_4:0", shape=(1,), dtype=int32)

[0 3 6]

In [7]:

# partial code 3

tmp3 = tmp2 + idx_const2

print(tmp3)

print(tf.shape(tmp3))

tfutil.print_constant(tmp3)

Tensor("add_1:0", shape=(3,), dtype=int32)

Tensor("Shape_5:0", shape=(1,), dtype=int32)

[1 3 8]

In [8]:

params = tf.reshape(x, [-1]) 

print(params)

print(tf.shape(params))

tfutil.print_constant(params)

Tensor("Reshape:0", shape=(9,), dtype=int32)

Tensor("Shape_6:0", shape=(1,), dtype=int32)

[1 2 3 4 5 6 7 8 9]

In [9]:

gather_const1 = tf.gather(params,         # flatten input

              idx_flattened)  # use flattened indices

print(gather_const1)

print(tf.shape(gather_const1))

tfutil.print_constant(gather_const1)

Tensor("Gather:0", shape=(3,), dtype=int32)

Tensor("Shape_7:0", shape=(1,), dtype=int32)

[2 4 9]


tf.gather_nd(params, indices, name=None)


indices에 따라 params에서 값들을 모읍니다.


indices는 params의 인덱스들을 포함하는 정수형 텐서입니다. 구조(shape)는 [d_0, ..., d_N, R]이어야 하고, 여기서 R은 params의 랭크(rank)입니다. indices의 가장 안쪽의 차원들(길이 R의)는 params의 인덱스들에 해당합니다.


출력 텐서의 구조(shape)는 [d_0, ..., d_{n-1}]이고, 다음을 만족합니다.

output[i, j, k, ...] = params[indices[i, j, k, ..., :]]

예로, indices에 대해서 다음과 같습니다.

output[i] = params[indices[i, :]]
인자:
  • paramsR-D Tensor. 값들을 모을 Tensor입니다.
  • indicesint32형 또는 int64형 (N+1)-D Tensor. 구조(shape)가 [d_0, ..., d_N, R]이어야 합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

params와 같은 자료형의 N-D Tensorindices에 따라 주어진 인덱스들로부터 params의 값들을 모은 텐서입니다.


출처: 텐서 변환


Tensorflow tf.gather_nd 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# [d_0, ..., d_{Q-2}, params.shape[K], ..., params.shape[P-1]].

x = [['a', 'b'], ['c', 'd']]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2, 2), dtype=string)

Tensor("Shape:0", shape=(2,), dtype=int32)

[['a' 'b']

 ['c' 'd']]

In [3]:

# Simple indexing into a matrix:

indices = [[0, 0], [1, 1]]

gn_const1 = tf.gather_nd(const1, indices)

print(gn_const1)

print(tf.shape(gn_const1))

tfutil.print_operation_value(gn_const1)

Tensor("GatherNd:0", shape=(2,), dtype=string)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

['a' 'd']

In [4]:

# Slice indexing into a matrix:

indices = [[1], [0]]

gn_const1 = tf.gather_nd(const1, indices)

print(gn_const1)

print(tf.shape(gn_const1))

tfutil.print_operation_value(gn_const1)

Tensor("GatherNd_1:0", shape=(2, 2), dtype=string)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[['c' 'd']

 ['a' 'b']]

In [5]:

# Batched indexing into a matrix:

indices = [[[0, 0]], [[0, 1]]]

gn_const1 = tf.gather_nd(const1, indices)

print(gn_const1)

print(tf.shape(gn_const1))

tfutil.print_operation_value(gn_const1)

Tensor("GatherNd_2:0", shape=(2, 1), dtype=string)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[['a']

 ['b']]

In [6]:

# Batched slice indexing into a matrix:

indices = [[[1]], [[0]]]

gn_const1 = tf.gather_nd(const1, indices)

print(gn_const1)

print(tf.shape(gn_const1))

tfutil.print_operation_value(gn_const1)

Tensor("GatherNd_3:0", shape=(2, 1, 2), dtype=string)

Tensor("Shape_4:0", shape=(3,), dtype=int32)

[[['c' 'd']]

 [['a' 'b']]]

In [7]:

x = [[['a0', 'b0'], ['c0', 'd0']],

    [['a1', 'b1'], ['c1', 'd1']]]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2, 2, 2), dtype=string)

Tensor("Shape_5:0", shape=(3,), dtype=int32)

[[['a0' 'b0']

  ['c0' 'd0']]

 [['a1' 'b1']

  ['c1' 'd1']]]

In [8]:

# Indexing into a 3-tensor:

indices = [[1]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_4:0", shape=(1, 2, 2), dtype=string)

Tensor("Shape_6:0", shape=(3,), dtype=int32)

[[['a1' 'b1']

  ['c1' 'd1']]]

In [9]:

indices = [[0, 1], [1, 0]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_5:0", shape=(2, 2), dtype=string)

Tensor("Shape_7:0", shape=(2,), dtype=int32)

[['c0' 'd0']

 ['a1' 'b1']]

In [10]:

indices = [[0, 0, 1], [1, 0, 1]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_6:0", shape=(2,), dtype=string)

Tensor("Shape_8:0", shape=(1,), dtype=int32)

['b0' 'b1']

In [11]:

# Batched indexing into a 3-tensor:

indices = [[[1]], [[0]]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_7:0", shape=(2, 1, 2, 2), dtype=string)

Tensor("Shape_9:0", shape=(4,), dtype=int32)

[[[['a1' 'b1']

   ['c1' 'd1']]]

 [[['a0' 'b0']

   ['c0' 'd0']]]]

In [12]:

indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_8:0", shape=(2, 2, 2), dtype=string)

Tensor("Shape_10:0", shape=(3,), dtype=int32)

[[['c0' 'd0']

  ['a1' 'b1']]

 [['a0' 'b0']

  ['c1' 'd1']]]

In [13]:

indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]]

gn_const2 = tf.gather_nd(const2, indices)

print(gn_const2)

print(tf.shape(gn_const2))

tfutil.print_operation_value(gn_const2)

Tensor("GatherNd_9:0", shape=(2, 2), dtype=string)

Tensor("Shape_11:0", shape=(2,), dtype=int32)

[['b0' 'b1']

 ['d0' 'c1']]


tf.dynamic_partition(data, partitions, num_partitions, name=None)


partitions의 인덱스들을 이용해서 data를 num_partitions개의 텐서로 나눕니다.


각각의 크기 partitions.ndim인 인덱스 튜플 js에 대해, 슬라이스 data[js, ...]는 outputs[partitions[js]]의 부분이 됩니다. partitions[js] = i인 슬라이스는 outputs[i]에 js의 사전 순서대로 배열되고, outputs[i]의 첫 번째 차원은 partitions의 엔트리 중 i와 같은 것의 수입니다. 구체적으로,

outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:]

outputs[i] = pack([data[js, ...] for js if partitions[js] == i])

입니다. data.shape는 partitions.shape로 시작해야 합니다.


예시:

# 스칼라 분할

partitions = 1

num_partitions = 2

data = [10, 20]

outputs[0] = []  # Empty with shape [0, 2]

outputs[1] = [[10, 20]]


# 벡터 분할

partitions = [0, 0, 1, 1, 0]

num_partitions = 2

data = [10, 20, 30, 40, 50]

outputs[0] = [10, 20, 50]

outputs[1] = [30, 40]

 
인자:
  • dataTensor.
  • partitionsint32형 Tensor. 임의의 구조(shape)가 가능합니다. 범위 [0, num_partitions) 내의 인덱스들을 포함합니다.
  • num_partitionsint(>= 1). 분할의 수.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

num_partitions개 Tensor의 리스트.


출처: 텐서 변환


Tensorflow tf.dynamic_partition 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

# outputs[i].shape = [sum(partitions == i)] + data.shape[partitions.ndim:]

# outputs[i] = pack([data[js, ...] for js if partitions[js] == i])

 

x = [10, 20]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[10 20]

In [3]:

# Scalar partitions.

partitions = 1

num_partitions = 2

dyp_const1 = tf.dynamic_partition(const1, partitions, num_partitions)

print(dyp_const1[0])

print(tf.shape(dyp_const1[0]))

tfutil.print_operation_value(dyp_const1[0])

Tensor("DynamicPartition:0", shape=(?, 2), dtype=int64)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[]

In [4]:

print(dyp_const1[1])

print(tf.shape(dyp_const1[1]))

tfutil.print_operation_value(dyp_const1[1])

Tensor("DynamicPartition:1", shape=(?, 2), dtype=int64)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[10 20]]

In [5]:

print(dyp_const1)

print(tf.shape(dyp_const1))

tfutil.print_operation_value(dyp_const1)

[<tf.Tensor 'DynamicPartition:0' shape=(?, 2) dtype=int64>, <tf.Tensor 'DynamicPartition:1' shape=(?, 2) dtype=int64>]

Tensor("Shape_3:0", shape=(3,), dtype=int32)

[array([], shape=(0, 2), dtype=int64), array([[10, 20]])]

In [6]:

x = [10, 20, 30, 40, 50]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(5,), dtype=int64)

Tensor("Shape_4:0", shape=(1,), dtype=int32)

[10 20 30 40 50]

In [7]:

# Vector partitions.

partitions = [0, 0, 1, 1, 0]

num_partitions = 2

dyp_const2 = tf.dynamic_partition(const2, partitions, num_partitions)

print(dyp_const2[0])

print(tf.shape(dyp_const2[0]))

tfutil.print_operation_value(dyp_const2[0])

Tensor("DynamicPartition_1:0", shape=(?,), dtype=int64)

Tensor("Shape_5:0", shape=(1,), dtype=int32)

[10 20 50]

In [8]:

print(dyp_const2[1])

print(tf.shape(dyp_const2[1]))

tfutil.print_operation_value(dyp_const2[1])

Tensor("DynamicPartition_1:1", shape=(?,), dtype=int64)

Tensor("Shape_6:0", shape=(1,), dtype=int32)

[30 40]

In [9]:

print(dyp_const2)

print(tf.shape(dyp_const2))

tfutil.print_operation_value(dyp_const2)

[<tf.Tensor 'DynamicPartition_1:0' shape=(?,) dtype=int64>, <tf.Tensor 'DynamicPartition_1:1' shape=(?,) dtype=int64>]

Tensor("Shape_7:0", shape=(2,), dtype=int32)

[array([10, 20, 50]), array([30, 40])]


tf.dynamic_stitch(indices, data, name=None)


data 안의 텐서들 안의 값을 단일 텐서에 끼웁니다.

merged[indices[m][i, ..., j], ...] = data[m][i, ..., j, ...]

를 만족하는 merged 텐서를 구성합니다. 예로, 만약 각각의 indices[m]이 스칼라이거나 벡터라면, 다음이 성립합니다.

# Scalar indices
merged[indices[m], ...] = data[m][...]

# Vector indices
merged[indices[m][i], ...] = data[m][i, ...]

각각의 data[i].shape는 해당하는 indices[i].shape로 시작해야 하며, data[i].shape의 나머지는 i에 대해서 일정해야 합니다. 즉, data[i].shape = indices[i].shape + constant이어야 합니다. 이 constant에 대해, 출력 텐서의 구조(shape)는

merged.shape = [max(indices)] + constant

입니다. 값들은 순서대로 합쳐집니다. 즉, 인덱스가 indices[m][i]와 indices[n][j] 모두에서 나타나고 (m,i) < (n,j)인 경우 슬라이스 data[n][j]가 합쳐진 결과에 나타납니다.


예시:

indices[0] = 6

indices[1] = [4, 1]

indices[2] = [[5, 2], [0, 3]]

data[0] = [61, 62]

data[1] = [[41, 42], [11, 12]]

data[2] = [[[51, 52], [21, 22]], [[1, 2], [31, 32]]]

merged = [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42],

          [51, 52], [61, 62]]

 
인자:
  • indices: 2개 이상의 int32형 Tensor의 리스트.
  • data: 같은 자료형의 Tensor들의 리스트. indices의 텐서 개수와 리스트의 Tensor 수가 같아야 합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

data와 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.dynamic_stitch 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [[1, 2], [3, 4]]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(2, 2), dtype=int64)

Tensor("Shape:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]]

In [3]:

y = [1, 1]

row_to_add = tf.constant(np.array(y))

print(row_to_add)

print(tf.shape(row_to_add))

tfutil.print_constant(row_to_add)

Tensor("Const_1:0", shape=(2,), dtype=int64)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 1]

In [4]:

original_row = const1[0]

print(original_row)

print(tf.shape(original_row))

tfutil.print_constant(original_row)

Tensor("strided_slice:0", shape=(2,), dtype=int64)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[1 2]

In [5]:

updated_row = original_row + row_to_add

print(updated_row)

print(tf.shape(updated_row))

tfutil.print_operation_value(updated_row)

Tensor("add:0", shape=(2,), dtype=int64)

Tensor("Shape_3:0", shape=(1,), dtype=int32)

[2 3]

In [6]:

unchanged_indices = tf.range(tf.size(const1))

print(unchanged_indices)

print(tf.shape(unchanged_indices))

tfutil.print_operation_value(unchanged_indices)

Tensor("range:0", shape=(4,), dtype=int32)

Tensor("Shape_4:0", shape=(1,), dtype=int32)

[0 1 2 3]

In [7]:

changed_indices = tf.range(const1.get_shape()[0])

print(changed_indices)

print(tf.shape(changed_indices))

tfutil.print_operation_value(changed_indices)

Tensor("range_1:0", shape=(2,), dtype=int32)

Tensor("Shape_5:0", shape=(1,), dtype=int32)

[0 1]

In [8]:

a_flat = tf.reshape(const1, [-1])

print(a_flat)

print(tf.shape(a_flat))

tfutil.print_operation_value(a_flat)

Tensor("Reshape:0", shape=(4,), dtype=int64)

Tensor("Shape_6:0", shape=(1,), dtype=int32)

[1 2 3 4]

In [9]:

updated_a_flat = tf.dynamic_stitch([unchanged_indices, changed_indices], [a_flat, updated_row])

print(updated_a_flat)

print(tf.shape(updated_a_flat))

tfutil.print_operation_value(updated_a_flat)

Tensor("DynamicStitch:0", shape=(4,), dtype=int64)

Tensor("Shape_7:0", shape=(1,), dtype=int32)

[2 3 3 4]

In [10]:

updated_a = tf.reshape(updated_a_flat, const1.get_shape())

print(updated_a)

print(tf.shape(updated_a))

tfutil.print_operation_value(updated_a)

Tensor("Reshape_1:0", shape=(2, 2), dtype=int64)

Tensor("Shape_8:0", shape=(2,), dtype=int32)

[[2 3]

 [3 4]]

In [11]:

# Apply function (increments x_i) on elements for which a certain condition

# apply (x_i != -1 in this example).

x = [0.1, -1., 5.2, 4.3, -1., 7.4]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const_2:0", shape=(6,), dtype=float64)

Tensor("Shape_9:0", shape=(1,), dtype=int32)

[ 0.1 -1.   5.2  4.3 -1.   7.4]

In [12]:

condition_mask=tf.not_equal(x,tf.constant(-1.))

print(condition_mask)

print(tf.shape(condition_mask))

tfutil.print_constant(condition_mask)

Tensor("NotEqual:0", shape=(6,), dtype=bool)

Tensor("Shape_10:0", shape=(1,), dtype=int32)

[ True False  True  True False  True]

In [13]:

partitioned_data = tf.dynamic_partition(x,

    tf.cast(condition_mask, tf.int32) , 2)

print(partitioned_data)

print(tf.shape(partitioned_data))

[<tf.Tensor 'DynamicPartition:0' shape=(?,) dtype=float32>, <tf.Tensor 'DynamicPartition:1' shape=(?,) dtype=float32>]

Tensor("Shape_11:0", shape=(2,), dtype=int32)

In [14]:

partitioned_data[1] = partitioned_data[1] + 1.0

print(partitioned_data[1])

print(tf.shape(partitioned_data[1]))

tfutil.print_constant(partitioned_data[1])

Tensor("add_1:0", shape=(?,), dtype=float32)

Tensor("Shape_12:0", shape=(1,), dtype=int32)

[ 1.10000002  6.19999981  5.30000019  8.39999962]

In [15]:

condition_indices = tf.dynamic_partition(

    tf.range(tf.shape(x)[0]), tf.cast(condition_mask, tf.int32) , 2)

print(condition_indices)

print(tf.shape(condition_indices))

[<tf.Tensor 'DynamicPartition_1:0' shape=(?,) dtype=int32>, <tf.Tensor 'DynamicPartition_1:1' shape=(?,) dtype=int32>]

Tensor("Shape_14:0", shape=(2,), dtype=int32)

In [16]:

ds_const1 = tf.dynamic_stitch(condition_indices, partitioned_data)

print(ds_const1)

print(tf.shape(ds_const1))

tfutil.print_constant(ds_const1)

Tensor("DynamicStitch_1:0", shape=(?,), dtype=float32)

Tensor("Shape_15:0", shape=(1,), dtype=int32)

[ 1.10000002 -1.          6.19999981  5.30000019 -1.          8.39999962]


tf.boolean_mask(tensor, mask, name='boolean_mask')


텐서에 불리언 마스크(boolean mask)를 적용합니다. NumPy의 tensor[mask]와 동일합니다.

# 1-D 예시
tensor = [0, 1, 2, 3]
mask = [True, False, True, False]
boolean_mask(tensor, mask) ==> [0, 2]

일반적으로 0 < dim(mask) = K <= dim(tensor)이고, mask의 구조(shape)는 tensor 구조의 첫 K 차원이 일치해야 합니다. 그렇게 되면 boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd] 을 만족하며, (i1,...,iK)는 i번째 mask의 i번째 True인 원소입니다(행 우선 순서).

인자:
  • tensor: N-D 텐서.
  • mask: K-D 불리언 텐서, K <= N이고, K는 정적으로(statically) 알려져 있어야 합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

mask에서 True인 값들에 대한 tensor의 원소들로 이루어진 텐서.

예외:
  • ValueError: 모양이 일치하지 않는 경우.
예시:
# 2-D 예시
tensor = [[1, 2], [3, 4], [5, 6]]
mask = [True, False, True]
boolean_mask(tensor, mask) ==> [[1, 2], [5, 6]]


출처: 텐서 변환


Tensorflow tf.boolean_mask 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [0, 1, 2, 3]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(4,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[0 1 2 3]

In [3]:

mask = np.array([True, False, True, False])

bm_const1 = tf.boolean_mask(const1, mask)

print(bm_const1)

print(tf.shape(bm_const1))

tfutil.print_operation_value(bm_const1)

Tensor("boolean_mask/Gather:0", shape=(?,), dtype=int64)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[0 2]

In [4]:

x = [[1, 2], [3, 4], [5, 6]]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(3, 2), dtype=int64)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]

 [5 6]]

In [5]:

mask = np.array([True, False, True])

bm_const2 = tf.boolean_mask(const2, mask)

print(bm_const2)

print(tf.shape(bm_const2))

tfutil.print_operation_value(bm_const2)

Tensor("boolean_mask_1/Gather:0", shape=(?, 2), dtype=int64)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2]

 [5 6]]


tf.one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)


One-hot 텐서를 반환합니다.


indices의 인덱스에 있는 위치는 on_value, 아닌 위치는 off_value의 값을 가집니다.

on_value와 off_value는 같은 자료형을 가져야 합니다. 만약 dtype이 주어진 경우, 그들은 dtype에 의해 정해진 자료형이어야 합니다.

만약 on_value가 주어지지 않으면, dtype형의 1이 기본값으로 정해집니다.

비슷하게 off_value가 주어지지 않은 경우 dtype 형의 0이 기본값입니다.

입력 indices가 랭크 N인 경우, 출력은 랭크 N+1을 가집니다. 새로운 축이 차원 axis에 추가됩니다(기본적으로 새 축은 끝에 추가됩니다).

만약 indices가 스칼라라면 출력의 구조(shape)는 길이 depth의 벡터가 됩니다.


만약 indices가 길이 features의 벡터라면, 출력의 구조는 다음과 같습니다.

features x depth if axis == -1
depth x features if axis == 0

만약 indices가 구조 [batch, features]의 행렬(또는 배치)이라면, 출력의 구조는 다음과 같습니다.

batch x features x depth if axis == -1
batch x depth x features if axis == 1
depth x batch x features if axis == 0

dtype가 주어지지 않은 경우, on_value 또는 off_value가 주어졌다면 그들로부터 자료형을 추측합니다. 만약 셋 모두 주어지지 않았다면 기본 자료형은 tf.float32형 입니다.


참고: 수가 아닌 출력 자료형이 요구되는 경우(tf.stringtf.bool 등), on_value와 off_value 모두 주어져야 합니다.

예시:

다음이 주어진 경우

indices = [0, 2, -1, 1]
depth = 3
on_value = 5.0
off_value = 0.0
axis = -1

출력은 다음의 [4 x 3]입니다.

output =
[5.0 0.0 0.0]  // one_hot(0)
[0.0 0.0 5.0]  // one_hot(2)
[0.0 0.0 0.0]  // one_hot(-1)
[0.0 5.0 0.0]  // one_hot(1)

다음이 주어진 경우

indices = [[0, 2], [1, -1]]
depth = 3
on_value = 1.0
off_value = 0.0
axis = -1

출력은 다음의 [2 x 2 x 3]입니다.

  output =
  [
    [1.0, 0.0, 0.0]  // one_hot(0)
    [0.0, 0.0, 1.0]  // one_hot(2)
  ][
    [0.0, 1.0, 0.0]  // one_hot(1)
    [0.0, 0.0, 0.0]  // one_hot(-1)
  ]

다음과 강티 on_value와 off_value의 기본값을 이용하는 경우,

  indices = [0, 1, 2]
  depth = 3

출력은 다음과 같습니다.

  output =
  [[1., 0., 0.],
   [0., 1., 0.],
   [0., 0., 1.]]
인자:
  • indices: 인덱스들의 Tensor.
  • depth: One-hot 차원의 깊이(depth)를 결정하는 스칼라 값.
  • on_valueindices[j] = i인 경우 채울 스칼라 값. (기본값: 1, 선택사항)
  • off_valueindices[j] != i인 경우 채울 스칼라 값. (기본값: 0, 선택사항)
  • axis: 채워질 축 (기본값: -1, 선택사항).
  • dtype: 출력 텐서의 자료형.
반환값:
  • output: One-hot 텐서.
예외:
  • TypeErroron_value 또는 off_value의 자료형이 dtype과 다른 경우
  • TypeErroron_value와 off_value의 자료형이 서로 다른 경우

출처: 텐서 변환


Tensorflow tf.one_hot 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [0, 1, 2]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(3,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[0 1 2]

In [3]:

depth = 3

oh_const1 = tf.one_hot(const1, depth)

print(oh_const1)

print(tf.shape(oh_const1))

tfutil.print_operation_value(oh_const1)

Tensor("one_hot:0", shape=(3, 3), dtype=float32)

Tensor("Shape_1:0", shape=(2,), dtype=int32)

[[ 1.  0.  0.]

 [ 0.  1.  0.]

 [ 0.  0.  1.]]

In [4]:

x = [0, 2, -1, 1]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(4,), dtype=int64)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[ 0  2 -1  1]

In [5]:

depth = 3

bm_const2 = tf.one_hot(const2, depth,

    on_value=5.0, off_value=0.0, axis=-1)

print(bm_const2)

print(tf.shape(bm_const2))

tfutil.print_operation_value(bm_const2)

Tensor("one_hot_1:0", shape=(4, 3), dtype=float32)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[ 5.  0.  0.]

 [ 0.  0.  5.]

 [ 0.  0.  0.]

 [ 0.  5.  0.]]

In [6]:

x = [[0, 2], [1, -1]]

const3 = tf.constant(np.array(x))

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int64)

Tensor("Shape_4:0", shape=(2,), dtype=int32)

[[ 0  2]

 [ 1 -1]]

In [7]:

depth = 3

bm_const3 = tf.one_hot(const3, depth,

    on_value=1.0, off_value=0.0, axis=-1)

print(bm_const3)

print(tf.shape(bm_const3))

tfutil.print_operation_value(bm_const3)

Tensor("one_hot_2:0", shape=(2, 2, 3), dtype=float32)

Tensor("Shape_5:0", shape=(3,), dtype=int32)

[[[ 1.  0.  0.]

  [ 0.  0.  1.]]

 [[ 0.  1.  0.]

  [ 0.  0.  0.]]]


기타 함수 및 클래스


tf.bitcast(input, type, name=None)


텐서를 다른 자료형으로 데이터 복사 없이 비트캐스트(bitcast)합니다.


input 텐서가 주어질 때, 이 함수는 input과 같은 버퍼 데이터를 가진 자료형 type의 텐서를 반환합니다.

만약 입력의 자료형 T가 출력의 자료형 type에 비해 더 큰 경우, 구조(shape)가 [...]에서 [..., sizeof(T)/sizeof(type)]으로 변형됩니다.

만약 T가 type에 비해 더 작은 경우, 가장 오른쪽의 차원이 sizeof(type)/sizeof(T)와 같아야 합니다. 구조는 [..., sizeof(type)/sizeof(T)] to [...]으로 변형됩니다.

인자:
  • inputTensor. 다음의 자료형이 가능합니다: float32float64int64int32uint8uint16int16int8complex64complex128qint8quint8qint32half.
  • typetf.DType. 다음 중 하나가 가능합니다: tf.float32, tf.float64, tf.int64, tf.int32, tf.uint8, tf.uint16, tf.int16, tf.int8, tf.complex64, tf.complex128, tf.qint8, tf.quint8, tf.qint32, tf.half.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

type 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.bitcast 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = 37.0

const1 = tf.constant(x) 

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(), dtype=float32)

Tensor("Shape:0", shape=(0,), dtype=int32)

37.0

In [3]:

bc_const1 = tf.bitcast(const1, tf.int32)

print(bc_const1)

print(tf.shape(bc_const1))

tfutil.print_operation_value(bc_const1)

Tensor("Bitcast:0", shape=(), dtype=int32)

Tensor("Shape_1:0", shape=(0,), dtype=int32)

1108606976

In [4]:

x = -1

invert_bits = tf.constant(x) - bc_const1

print(invert_bits)

print(tf.shape(invert_bits))

tfutil.print_operation_value(invert_bits)

Tensor("sub:0", shape=(), dtype=int32)

Tensor("Shape_2:0", shape=(0,), dtype=int32)

-1108606977

In [5]:

bc_to_float = tf.bitcast(invert_bits, tf.float32)

print(bc_to_float)

print(tf.shape(bc_to_float))

tfutil.print_operation_value(bc_to_float)

Tensor("Bitcast_1:0", shape=(), dtype=float32)

Tensor("Shape_3:0", shape=(0,), dtype=int32)

-0.115234


tf.shape_n(input, name=None)


텐서의 구조(shape)를 반환합니다.


이 함수는 input[i]들의 구조를 나타내는 N개의 1-D 정수 텐서를 반환합니다.

인자:
  • input: 같은 자료형의 1개 이상의 Tensor의 리스트.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input의 텐서와 같은 개수의 int32형 Tensor의 리스트.


출처: 텐서 변환


Tensorflow tf.shape_n 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [1]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1]

In [3]:

sn_const1 = tf.shape_n([const1])

print(sn_const1)

tfutil.print_operation_value(sn_const1)

[<tf.Tensor 'ShapeN:0' shape=(1,) dtype=int32>]

[array([1], dtype=int32)]

In [4]:

x = [1, 2]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2,), dtype=int64)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 2]

In [5]:

sn_const2 = tf.shape_n([const2])

print(sn_const2)

tfutil.print_operation_value(sn_const2)

[<tf.Tensor 'ShapeN_1:0' shape=(1,) dtype=int32>]

[array([2], dtype=int32)]

In [6]:

x = [[1, 2], [3, 4]]

const3 = tf.constant(np.array(x))

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int64)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]]

In [7]:

sn_const3 = tf.shape_n([const3])

print(sn_const3)

tfutil.print_operation_value(sn_const3)

[<tf.Tensor 'ShapeN_2:0' shape=(2,) dtype=int32>]

[array([2, 2], dtype=int32)]

In [8]:

x = [[1, 2], [3, 4], [5, 6]]

const4 = tf.constant(np.array(x))

print(const4)

print(tf.shape(const4))

tfutil.print_constant(const4)

Tensor("Const_3:0", shape=(3, 2), dtype=int64)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]

 [5 6]]

In [9]:

sn_const4 = tf.shape_n([const4])

print(sn_const4)

tfutil.print_operation_value(sn_const4)

[<tf.Tensor 'ShapeN_3:0' shape=(2,) dtype=int32>]

[array([3, 2], dtype=int32)]

In [10]:

x = [[[1], [2]], [[3], [4]]]

const5 = tf.constant(np.array(x))

print(const5)

print(tf.shape(const5))

tfutil.print_constant(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int64)

Tensor("Shape_4:0", shape=(3,), dtype=int32)

[[[1]

  [2]]

 [[3]

  [4]]]

In [11]:

sn_const5 = tf.shape_n([const5])

print(sn_const5)

tfutil.print_operation_value(sn_const5)

[<tf.Tensor 'ShapeN_4:0' shape=(3,) dtype=int32>]

[array([2, 2, 1], dtype=int32)]

In [12]:

x = [[[1], [2]], [[3], [4]], [[5], [6]]]

const6 = tf.constant(np.array(x))

print(const6)

print(tf.shape(const6))

tfutil.print_constant(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int64)

Tensor("Shape_5:0", shape=(3,), dtype=int32)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [13]:

sn_const6 = tf.shape_n([const6])

print(sn_const6)

tfutil.print_operation_value(sn_const6)

[<tf.Tensor 'ShapeN_5:0' shape=(3,) dtype=int32>]

[array([3, 2, 1], dtype=int32)]

In [14]:

sn_const6 = tf.shape_n([[const6]])

print(sn_const6)

tfutil.print_operation_value(sn_const6)

[<tf.Tensor 'ShapeN_6:0' shape=(4,) dtype=int32>]

[array([1, 3, 2, 1], dtype=int32)]


tf.unique_with_counts(x, name=None)


1-D 텐서에서 서로 다른 원소를 찾습니다.


이 함수는 텐서 x의 모든 서로 다른 원소를 x에서 나타나는 순서대로 나열한 텐서 y를 반환합니다. 이 함수는 크기가 x와 같고, x의 각 원소에 대해 y에서의 인덱서를 원소를 가지는 텐서 idx도 반환합니다. y의 각 원소가 x에서 몇 번 나타나는지에 대한 텐서 count도 반환합니다. 즉,

y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]

입니다.


예시:

# tensor 'x'는 [1, 1, 2, 4, 4, 4, 7, 8, 8]

y, idx, count = unique_with_counts(x)

y ==> [1, 2, 4, 7, 8]

idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4]

count ==> [2, 1, 3, 1, 2]

인자:
  • x: 1-D Tensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

Tensor의 튜플 (y, idx, count).

  • yx와 자료형이 같은 1-D Tensor.
  • idxint32형 1-D Tensor.
  • countint32형 1-D Tensor.

출처: 텐서 변환


Tensorflow tf.unique_with_counts 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

x = [1, 1, 2, 4, 4, 4, 7, 8, 8]

 

const1 = tf.constant(np.array(x), dtype=tf.int32)

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(9,), dtype=int32)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1 1 2 4 4 4 7 8 8]

In [3]:

y, idx, count = tf.unique_with_counts(const1)

print(y)

print(tf.shape(y))

tfutil.print_constant(y)

Tensor("UniqueWithCounts:0", shape=(?,), dtype=int32)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 2 4 7 8]

In [4]:

print(idx)

print(tf.shape(idx))

tfutil.print_constant(idx)

Tensor("UniqueWithCounts:1", shape=(9,), dtype=int32)

Tensor("Shape_2:0", shape=(1,), dtype=int32)

[0 0 1 2 2 2 3 4 4]

In [5]:

print(count)

print(tf.shape(count))

tfutil.print_constant(count)

Tensor("UniqueWithCounts:2", shape=(?,), dtype=int32)

Tensor("Shape_3:0", shape=(1,), dtype=int32)

[2 1 3 1 2]



이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Convert to Tensor - Shape and Shaping

(텐서플로우 텐서 변환 - 구조 및 구조 변형)



구조(Shape) 및 구조 변형(Shaping)

TensorFlow는 텐서의 구조(shape)를 확인하거나 구조를 변형하는 데 사용할 수 있는 몇 가지 함수를 제공합니다.


tf.shape(input, name=None)


텐서의 구조(shape)를 반환합니다.


이 함수는 input 텐서의 구조(shape)를 1-D 정수형 텐서로 반환합니다.


예시:

# 't'는 [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]

shape(t) ==> [2, 2, 3]

인자:
  • inputTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

int32형 Tensor.


출처: 텐서 변환


Tensorflow tf.tf.shape 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: tfutil.print_operation_value(tf.shape(const1))

[]

In [7]: const2 = tf.constant([12])

In [8]: tfutil.print_constant(const2)

[1 2]

In [9]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [10]: tfutil.print_operation_value(tf.shape(const2))

[2]

In [11]: const3 = tf.constant([[12], [34]])

In [12]: tfutil.print_constant(const3)

[[1 2]

 [3 4]]

In [13]: print(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int32)

In [14]: tfutil.print_operation_value(tf.shape(const3))

[2 2]

In [15]: const3 = tf.constant([[12], [34], [56]])

In [16]: tfutil.print_constant(const3)

[[1 2]

 [3 4]

 [5 6]]

In [17]: print(const3)

Tensor("Const_3:0", shape=(3, 2), dtype=int32)

In [18]: tfutil.print_operation_value(tf.shape(const3))

[3 2]

In [19]: const5 = tf.constant([[[1], [2]], [[3], [4]]])

In [20]: tfutil.print_constant(const5)

[[[1]

  [2]]

 [[3]

  [4]]]

In [21]: print(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int32)

In [22]: tfutil.print_operation_value(tf.shape(const5))

[2 2 1]

In [23]: const6 = tf.constant([[[1], [2]], [[3], [4]], [[5], [6]]])

In [24]: tfutil.print_constant(const6)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [25]: print(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int32)

In [26]: tfutil.print_operation_value(tf.shape(const6))

[3 2 1]


tf.shape_n(input, name=None)


텐서의 구조(shape)를 반환합니다.


이 함수는 input[i]들의 구조를 나타내는 N개의 1-D 정수 텐서를 반환합니다.

인자:
  • input: 같은 자료형의 1개 이상의 Tensor의 리스트.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input의 텐서와 같은 개수의 int32형 Tensor의 리스트.


출처: 텐서 변환


Tensorflow tf.shape_n 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

= [1]

const1 = tf.constant(np.array(x))

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(1,), dtype=int64)

Tensor("Shape:0", shape=(1,), dtype=int32)

[1]

In [3]:

sn_const1 = tf.shape_n([const1])

print(sn_const1)

tfutil.print_operation_value(sn_const1)

[<tf.Tensor 'ShapeN:0' shape=(1,) dtype=int32>]

[array([1], dtype=int32)]

In [4]:

= [12]

const2 = tf.constant(np.array(x))

print(const2)

print(tf.shape(const2))

tfutil.print_constant(const2)

Tensor("Const_1:0", shape=(2,), dtype=int64)

Tensor("Shape_1:0", shape=(1,), dtype=int32)

[1 2]

In [5]:

sn_const2 = tf.shape_n([const2])

print(sn_const2)

tfutil.print_operation_value(sn_const2)

[<tf.Tensor 'ShapeN_1:0' shape=(1,) dtype=int32>]

[array([2], dtype=int32)]

In [6]:

= [[12], [34]]

const3 = tf.constant(np.array(x))

print(const3)

print(tf.shape(const3))

tfutil.print_constant(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int64)

Tensor("Shape_2:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]]

In [7]:

sn_const3 = tf.shape_n([const3])

print(sn_const3)

tfutil.print_operation_value(sn_const3)

[<tf.Tensor 'ShapeN_2:0' shape=(2,) dtype=int32>]

[array([2, 2], dtype=int32)]

In [8]:

= [[12], [34], [56]]

const4 = tf.constant(np.array(x))

print(const4)

print(tf.shape(const4))

tfutil.print_constant(const4)

Tensor("Const_3:0", shape=(3, 2), dtype=int64)

Tensor("Shape_3:0", shape=(2,), dtype=int32)

[[1 2]

 [3 4]

 [5 6]]

In [9]:

sn_const4 = tf.shape_n([const4])

print(sn_const4)

tfutil.print_operation_value(sn_const4)

[<tf.Tensor 'ShapeN_3:0' shape=(2,) dtype=int32>]

[array([3, 2], dtype=int32)]

In [10]:

= [[[1], [2]], [[3], [4]]]

const5 = tf.constant(np.array(x))

print(const5)

print(tf.shape(const5))

tfutil.print_constant(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int64)

Tensor("Shape_4:0", shape=(3,), dtype=int32)

[[[1]

  [2]]

 [[3]

  [4]]]

In [11]:

sn_const5 = tf.shape_n([const5])

print(sn_const5)

tfutil.print_operation_value(sn_const5)

[<tf.Tensor 'ShapeN_4:0' shape=(3,) dtype=int32>]

[array([2, 2, 1], dtype=int32)]

In [12]:

= [[[1], [2]], [[3], [4]], [[5], [6]]]

const6 = tf.constant(np.array(x))

print(const6)

print(tf.shape(const6))

tfutil.print_constant(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int64)

Tensor("Shape_5:0", shape=(3,), dtype=int32)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [13]:

sn_const6 = tf.shape_n([const6])

print(sn_const6)

tfutil.print_operation_value(sn_const6)

[<tf.Tensor 'ShapeN_5:0' shape=(3,) dtype=int32>]

[array([3, 2, 1], dtype=int32)]

In [14]:

sn_const6 = tf.shape_n([[const6]])

print(sn_const6)

tfutil.print_operation_value(sn_const6)

[<tf.Tensor 'ShapeN_6:0' shape=(4,) dtype=int32>]

[array([1, 3, 2, 1], dtype=int32)]


tf.size(input, name=None)


텐서의 크기(size)를 반환합니다.


이 함수는 input 텐서의 원소의 수를 정수로 반환합니다.


예시:

# 't'는 [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]]

size(t) ==> 12

인자:
  • inputTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

int32형 Tensor.


출처: 텐서 변환


Tensorflow tf.size 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: tfutil.print_operation_value(tf.size(const1))

1

In [7]: const2 = tf.constant([12])

In [8]: tfutil.print_constant(const2)

[1 2]

In [9]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [10]: tfutil.print_operation_value(tf.size(const2))

2

In [11]: const3 = tf.constant([[12], [34]])

In [12]: tfutil.print_constant(const3)

[[1 2]

 [3 4]]

In [13]: print(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int32)

In [14]: tfutil.print_operation_value(tf.size(const3))

4

In [15]: const4 = tf.constant([[12], [34], [56]])

In [16]: tfutil.print_constant(const4)

[[1 2]

 [3 4]

 [5 6]]

In [17]: print(const4)

Tensor("Const_3:0", shape=(3, 2), dtype=int32)

In [18]: tfutil.print_operation_value(tf.size(const4))

6

In [19]: const5 = tf.constant([[[1], [2]], [[3], [4]]])

In [20]: tfutil.print_constant(const5)

[[[1]

  [2]]

 [[3]

  [4]]]

In [21]: print(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int32)

In [22]: tfutil.print_operation_value(tf.size(const5))

4

In [23]: const6 = tf.constant([[[1], [2]], [[3], [4]], [[5], [6]]])

In [24]: tfutil.print_constant(const6)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [25]: print(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int32)

In [26]: tfutil.print_operation_value(tf.size(const6))

6


tf.rank(input, name=None) 


텐서의 랭크(rank)를 반환합니다.


이 함수는  input  텐서의 랭크를 정수로 반환합니다.


예시:

# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]

# shape of tensor 't' is [2, 2, 3]

rank(t) ==> 3


참고: 텐서의 랭크는 행렬의 랭크와는 다른 개념입니다. 텐서의 랭크는 텐서의 각 원소를 선택하기 위해 필요한 인덱스의 수입니다. 랭크는 order, degree, ndims 등으로 부르기도 합니다.


인자:

• input :  Tensor  또는  SparseTensor .

• name : 오퍼레이션의 명칭. (선택사항)


반환값:


 int32 형  Tensor .


출처: 텐서 변환


Tensorflow tf.rank 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: tfutil.print_operation_value(tf.rank(const1))

0

In [7]: const2 = tf.constant([12])

In [8]: tfutil.print_constant(const2)

[1 2]

In [9]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [10]: tfutil.print_operation_value(tf.rank(const2))

1

In [11]: const3 = tf.constant([[12], [34]])

In [12]: tfutil.print_constant(const3)

[[1 2]

 [3 4]]

In [13]: print(const3)

Tensor("Const_2:0", shape=(2, 2), dtype=int32)

In [14]: tfutil.print_operation_value(tf.rank(const3))

2

In [15]: const4 = tf.constant([[12], [34], [56]])

In [16]: tfutil.print_constant(const4)

[[1 2]

 [3 4]

 [5 6]]

In [17]: print(const4)

Tensor("Const_3:0", shape=(3, 2), dtype=int32)

In [18]: tfutil.print_operation_value(tf.rank(const4))

2

In [19]: const5 = tf.constant([[[1], [2]], [[3], [4]]])

In [20]: tfutil.print_constant(const5)

[[[1]

  [2]]

 [[3]

  [4]]]

In [21]: print(const5)

Tensor("Const_4:0", shape=(2, 2, 1), dtype=int32)

In [22]: tfutil.print_operation_value(tf.rank(const5))

3

In [23]: const6 = tf.constant([[[1], [2]], [[3], [4]], [[5], [6]]])

In [24]: tfutil.print_constant(const6)

[[[1]

  [2]]

 [[3]

  [4]]

 [[5]

  [6]]]

In [25]: print(const6)

Tensor("Const_5:0", shape=(3, 2, 1), dtype=int32)

In [26]: tfutil.print_operation_value(tf.rank(const6))

3


tf.reshape(tensor, shape, name=None)


텐서의 구조를 변형합니다.


tensor가 주어졌을 때, 이 함수는 해당 텐서와 같은 원소들을 가지며 구조가 shape인 텐서를 반환합니다.


만약 shape의 한 원소가 -1이라면, 전체 크기가 일정하게 유지되도록 해당 차원의 길이가 자동으로 계산됩니다. 특별히, shape가 [-1]이라면, 텐서는 1-D로 펴지게 됩니다. shape에서 최대 한 개의 원소만 -1이 될 수 있습니다.


만약 shape가 1-D이거나 그 이상이라면, 오퍼레이션은 tensor의 원소로 shape의 구조가 채워진 텐서를 반환합니다. 이 경우, shape에 의해 지정된 원소의 전체 수는 tensor의 원소의 전체 수와 동일해야 합니다.


예시:

# tensor 't'는 [1, 2, 3, 4, 5, 6, 7, 8, 9]

# tensor 't'의 구조(shape)는 [9]

reshape(t, [3, 3]) ==> [[1, 2, 3],

                        [4, 5, 6],

                        [7, 8, 9]]


# tensor 't'는 [[[1, 1], [2, 2]],

#               [[3, 3], [4, 4]]]

# tensor 't'의 구조(shape)는 [2, 2, 2]

reshape(t, [2, 4]) ==> [[1, 1, 2, 2],

                        [3, 3, 4, 4]]


# tensor 't'는 [[[1, 1, 1],

#                [2, 2, 2]],

#               [[3, 3, 3],

#                [4, 4, 4]],

#               [[5, 5, 5],

#                [6, 6, 6]]]

# tensor 't'의 구조(shape)는 [3, 2, 3]

# shape를 '[-1]'로 하여 't'를 1-D로 펴기

reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]


# 구조를 암시(infer)하기 위한 -1의 사용


# -1은 9를 의미:

reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],

                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]

# -1은 2를 의미:

reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],

                         [4, 4, 4, 5, 5, 5, 6, 6, 6]]

# -1은 3을 의미:

reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],

                              [2, 2, 2],

                              [3, 3, 3]],

                             [[4, 4, 4],

                              [5, 5, 5],

                              [6, 6, 6]]]


# tensor 't'는 [7]

# shape를 `[]`로 하면 스칼라(scalar)로 구조 변환

reshape(t, []) ==> 7

인자:
  • tensorTensor.
  • shapeint32형 Tensor. 출력 텐서의 구조(shape) 지정.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

tensor와 같은 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.reshape 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant([123456789])

In [4]: print(const1)

Tensor("Const:0", shape=(9,), dtype=int32)

In [5]: tfutil.print_constant(const1)

[1 2 3 4 5 6 7 8 9]

In [6]: rs_const1 = tf.reshape(const1, [33])

In [7]: print(rs_const1)

Tensor("Reshape:0", shape=(3, 3), dtype=int32)

In [8]: tfutil.print_operation_value(rs_const1)

[[1 2 3]

 [4 5 6]

 [7 8 9]]

In [9]: const2 = tf.constant([[[11], [22]], [[33], [44]]])

In [10]: print(const2)

Tensor("Const_1:0", shape=(2, 2, 2), dtype=int32)

In [11]: tfutil.print_constant(const2)

[[[1 1]

  [2 2]]

 [[3 3]

  [4 4]]]

In [12]: rs_const2 = tf.reshape(const2, [24])

In [13]: print(rs_const2)

Tensor("Reshape_1:0", shape=(2, 4), dtype=int32)

In [14]: tfutil.print_operation_value(rs_const2)

[[1 1 2 2]

 [3 3 4 4]]

In [15]: const3 = tf.constant([[[111], [222]], [[333], [444]], [[555], [666]]])

In [16]: print(const3)

Tensor("Const_2:0", shape=(3, 2, 3), dtype=int32)

In [17]: tfutil.print_constant(const3)

[[[1 1 1]

  [2 2 2]]

 [[3 3 3]

  [4 4 4]]

 [[5 5 5]

  [6 6 6]]]

In [18]: rs_const3 = tf.reshape(const3, [-1])

In [19]: print(rs_const3)

Tensor("Reshape_2:0", shape=(18,), dtype=int32)

In [20]: tfutil.print_operation_value(rs_const3)

[1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6]

In [21]: const4 = tf.constant([111222333444555666])

In [22]: print(const4)

Tensor("Const_3:0", shape=(18,), dtype=int32)

In [23]: tfutil.print_constant(const4)

[1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6]

In [24]: rs_const4 = tf.reshape(const4, [2-1])

In [25]: print(rs_const4)

Tensor("Reshape_3:0", shape=(2, 9), dtype=int32)

In [26]: tfutil.print_operation_value(rs_const4)

[[1 1 1 2 2 2 3 3 3]

 [4 4 4 5 5 5 6 6 6]]

In [27]: const5 = tf.constant([[111222333], [444555666]])

In [28]: print(const5)

Tensor("Const_4:0", shape=(2, 9), dtype=int32)

In [29]: tfutil.print_constant(const5)

[[1 1 1 2 2 2 3 3 3]

 [4 4 4 5 5 5 6 6 6]]

In [30]: rs_const5 = tf.reshape(const5, [2-13])

In [31]: print(rs_const5)

Tensor("Reshape_4:0", shape=(2, 3, 3), dtype=int32)

In [32]: tfutil.print_operation_value(rs_const5)

[[[1 1 1]

  [2 2 2]

  [3 3 3]]

 [[4 4 4]

  [5 5 5]

  [6 6 6]]]

In [33]: const6 = tf.constant([7])

In [34]: print(const6)

Tensor("Const_5:0", shape=(1,), dtype=int32)

In [35]: tfutil.print_constant(const6)

[7]

In [36]: rs_const6 = tf.reshape(const6, [])

In [37]: print(rs_const6)

Tensor("Reshape_5:0", shape=(), dtype=int32)

In [38]: tfutil.print_operation_value(rs_const6)

7


tf.squeeze(input, squeeze_dims=None, name=None)


텐서에서 크기 1인 차원을 제거합니다.


input 텐서가 주어졌을 때, 이 함수는 그와 같은 자료형의 크기 1인 차원이 모두 제거된 텐서를 반환합니다. 만약 모든 크기 1인 차원을 제거하고 싶은 것이 아니라면, 제거하고 싶은 특정한 크기 1인 차원들을 squeeze_dims으로 지정할 수 있습니다.


예시:

# 't'는 구조(shape) [1, 2, 1, 3, 1, 1]의 텐서

shape(squeeze(t)) ==> [2, 3]


제거할 크기 1인 차원들을 squeeze_dims으로 지정하기:

# 't'는 구조(shape) [1, 2, 1, 3, 1, 1]의 텐서
shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1]
인자:
  • inputTensor.
  • squeeze_dimsint의 리스트. 기본값은 []. 지정된 경우, 리스트 안의 차원만 제거합니다. 크기가 1이 아닌 차원을 제거하는 것은 오류입니다. (선택사항)
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensorinput과 같은 원소를 포함하지만, 하나 이상의 크기 1인 차원이 제거되어 있습니다.


출처: 텐서 변환


Tensorflow tf.squeeze 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: # [1, 2, 1, 3, 1, 1]

In [4]: const1 = tf.constant([[ [[ [[1]], [[2]], [[3]] ]], [[ [[4]], [[5]], [[6]] ]] ]])

In [5]: print(const1)

Tensor("Const:0", shape=(1, 2, 1, 3, 1, 1), dtype=int32)

In [6]: print(tf.shape(const1))

Tensor("Shape:0", shape=(6,), dtype=int32)

In [7]: tfutil.print_constant(const1)

[[[[[[1]]

    [[2]]

    [[3]]]]

  [[[[4]]

    [[5]]

    [[6]]]]]]

In [8]: sq_const1 = tf.squeeze(const1)

In [9]: print(sq_const1)

Tensor("Squeeze:0", shape=(2, 3), dtype=int32)

In [10]: print(tf.shape(sq_const1))

Tensor("Shape_1:0", shape=(2,), dtype=int32)

In [11]: tfutil.print_operation_value(sq_const1)

[[1 2 3]

 [4 5 6]]

In [12]: # [1, 2, 1, 3, 1, 1]

In [13]: const2 = tf.constant([[ [[ [[1]], [[2]], [[3]] ]], [[ [[4]], [[5]], [[6]] ]] ]])

In [14]: print(const2)

Tensor("Const_1:0", shape=(1, 2, 1, 3, 1, 1), dtype=int32)

In [15]: print(tf.shape(const2))

Tensor("Shape_2:0", shape=(6,), dtype=int32)

In [16]: tfutil.print_constant(const2)

[[[[[[1]]

    [[2]]

    [[3]]]]

  [[[[4]]

    [[5]]

    [[6]]]]]]

In [17]: sq_const2 = tf.squeeze(const2, [0])

In [18]: print(sq_const2)

Tensor("Squeeze_1:0", shape=(2, 1, 3, 1, 1), dtype=int32)

In [19]: print(tf.shape(sq_const2))

Tensor("Shape_3:0", shape=(5,), dtype=int32)

In [20]: tfutil.print_operation_value(sq_const2)

[[[[[1]]

   [[2]]

   [[3]]]]

 [[[[4]]

   [[5]]

   [[6]]]]]

In [21]: sq_const2 = tf.squeeze(const2, [2])

In [22]: print(sq_const2)

Tensor("Squeeze_2:0", shape=(1, 2, 3, 1, 1), dtype=int32)

In [23]: print(tf.shape(sq_const2))

Tensor("Shape_4:0", shape=(5,), dtype=int32)

In [24]: tfutil.print_operation_value(sq_const2)

[[[[[1]]

   [[2]]

   [[3]]]

  [[[4]]

   [[5]]

   [[6]]]]]

In [25]: sq_const2 = tf.squeeze(const2, [02])

In [26]: print(sq_const2)

Tensor("Squeeze_3:0", shape=(2, 3, 1, 1), dtype=int32)

In [27]: print(tf.shape(sq_const2))

Tensor("Shape_5:0", shape=(4,), dtype=int32)

In [28]: tfutil.print_operation_value(sq_const2)

[[[[1]]

  [[2]]

  [[3]]]

 [[[4]]

  [[5]]

  [[6]]]]

In [29]: sq_const2 = tf.squeeze(const2, [24])

In [30]: print(sq_const2)

Tensor("Squeeze_4:0", shape=(1, 2, 3, 1), dtype=int32)

In [31]: print(tf.shape(sq_const2))

Tensor("Shape_6:0", shape=(4,), dtype=int32)

In [32]: tfutil.print_operation_value(sq_const2)

[[[[1]

   [2]

   [3]]

  [[4]

   [5]

   [6]]]]

In [33]: sq_const2 = tf.squeeze(const2, [024])

In [34]: print(sq_const2)

Tensor("Squeeze_5:0", shape=(2, 3, 1), dtype=int32)

In [35]: print(tf.shape(sq_const2))

Tensor("Shape_7:0", shape=(3,), dtype=int32)

In [36]: tfutil.print_operation_value(sq_const2)

[[[1]

  [2]

  [3]]

 [[4]

  [5]

  [6]]]

In [37]: sq_const2 = tf.squeeze(const2, [0245])

In [38]: print(sq_const2)

Tensor("Squeeze_6:0", shape=(2, 3), dtype=int32)

In [39]: print(tf.shape(sq_const2))

Tensor("Shape_8:0", shape=(2,), dtype=int32)

In [40]: tfutil.print_operation_value(sq_const2)

[[1 2 3]

 [4 5 6]]


tf.expand_dims(input, dim, name=None)


크기 1인 차원을 텐서의 구조(shape)에 삽입합니다.


input 텐서가 주어졌을 때, 이 함수는 크기가 1인 차원을 input의 구조에서 차원 인덱스 dim에 삽입합니다. 차원 인덱스 dim은 0부터 시작합니다. 만약 dim에 음수가 지정된다면, 끝에서부터 역으로 계산됩니다.


이 함수는 단일 원소에 배치 차원(batch dimension)을 추가할 때 유용합니다. 예로, 만약 구조 [height, width, channels]의 단일 이미지가 있는 경우, 이것에 expand_dims(image, 0)을 적용해 구조 [1, height, width, channels]인 하나의 이미지로 구성된 배치(batch)를 구성할 수 있습니다.


다른 예시들:

# 't'는 구조(shape) [2]의 텐서
shape(expand_dims(t, 0)) ==> [1, 2]
shape(expand_dims(t, 1)) ==> [2, 1]
shape(expand_dims(t, -1)) ==> [2, 1]

# 't2'는 구조(shape) [2, 3, 5]의 텐서
shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]


이 함수는 다음의 조건이 만족되어야 합니다:


-1-input.dims() <= dim <= input.dims()


이 함수는 크기 1인 차원을 제거하는 함수인 squeeze()와 연관되어 있습니다.

인자:
  • inputTensor.
  • dimint32형 Tensor. 0-D (스칼라). input의 구조에서 어떤 차원 인덱스에 삽입할 것인지 지정합니다.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input과 같은 자료형의 Tensorinput과 같은 원소를 포함하지만, 하나 이상의 크기 1인 차원이 추가되어 있습니다.


출처: 텐서 변환


Tensorflow tf.expand_dims 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant([123])

In [4]: print(const1)

Tensor("Const:0", shape=(3,), dtype=int32)

In [5]: print(tf.shape(const1))

Tensor("Shape:0", shape=(1,), dtype=int32)

In [6]: tfutil.print_constant(const1)

[1 2 3]

In [7]: ed_const1 = tf.expand_dims(const1, 0)

In [8]: print(ed_const1)

Tensor("ExpandDims:0", shape=(1, 3), dtype=int32)

In [9]: tfutil.print_operation_value(ed_const1)

[[1 2 3]]

In [10]: print(tf.shape(ed_const1))

Tensor("Shape_1:0", shape=(2,), dtype=int32)

In [11]: ed_const1 = tf.expand_dims(const1, 1)

In [12]: print(ed_const1)

Tensor("ExpandDims_1:0", shape=(3, 1), dtype=int32)

In [13]: tfutil.print_operation_value(ed_const1)

[[1]

 [2]

 [3]]

In [14]: print(tf.shape(ed_const1))

Tensor("Shape_2:0", shape=(2,), dtype=int32)

In [15]: ed_const1 = tf.expand_dims(const1, 1)

In [16]: print(ed_const1)

Tensor("ExpandDims_2:0", shape=(3, 1), dtype=int32)

In [17]: tfutil.print_operation_value(ed_const1)

[[1]

 [2]

 [3]]

In [18]: print(tf.shape(ed_const1))

Tensor("Shape_3:0", shape=(2,), dtype=int32)

In [19]: ed_const1 = tf.expand_dims(const1, -1)

In [20]: print(ed_const1)

Tensor("ExpandDims_3:0", shape=(3, 1), dtype=int32)

In [21]: tfutil.print_operation_value(ed_const1)

[[1]

 [2]

 [3]]

In [22]: print(tf.shape(ed_const1))

Tensor("Shape_4:0", shape=(2,), dtype=int32)

In [23]: const2 = tf.constant([[[12345], [678910], [1112131415]], [[1617181920], [2122232425], [2627282930]]])

In [24]: print(const2)

Tensor("Const_1:0", shape=(2, 3, 5), dtype=int32)

In [25]: print(tf.shape(const2))

Tensor("Shape_5:0", shape=(3,), dtype=int32)

In [26]: tfutil.print_constant(const2)

[[[ 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]]]

In [27]: ed_const2 = tf.expand_dims(const2, 0)

In [28]: print(ed_const2)

Tensor("ExpandDims_4:0", shape=(1, 2, 3, 5), dtype=int32)

In [29]: tfutil.print_operation_value(ed_const2)

[[[[ 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]]]]

In [30]: print(tf.shape(ed_const2))

Tensor("Shape_6:0", shape=(4,), dtype=int32)

In [31]: ed_const2 = tf.expand_dims(const2, 1)

In [32]: print(ed_const2)

Tensor("ExpandDims_5:0", shape=(2, 1, 3, 5), dtype=int32)

In [33]: tfutil.print_operation_value(ed_const2)

[[[[ 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]]]]

In [34]: print(tf.shape(ed_const2))

Tensor("Shape_7:0", shape=(4,), dtype=int32)

In [35]: ed_const2 = tf.expand_dims(const2, 2)

In [36]: print(ed_const2)

Tensor("ExpandDims_6:0", shape=(2, 3, 1, 5), dtype=int32)

In [37]: tfutil.print_operation_value(ed_const2)

[[[[ 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]]]]

In [38]: print(tf.shape(ed_const2))

Tensor("Shape_8:0", shape=(4,), dtype=int32)

In [39]: ed_const2 = tf.expand_dims(const2, 3)

In [40]: print(ed_const2)

Tensor("ExpandDims_7:0", shape=(2, 3, 5, 1), dtype=int32)

In [41]: tfutil.print_operation_value(ed_const2)

[[[[ 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]]]]

In [42]: print(tf.shape(ed_const2))

Tensor("Shape_9:0", shape=(4,), dtype=int32)

In [43]: ed_const2 = tf.expand_dims(const2, -1)

In [44]: print(ed_const2)

Tensor("ExpandDims_8:0", shape=(2, 3, 5, 1), dtype=int32)

In [45]: tfutil.print_operation_value(ed_const2)

[[[[ 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]]]]

In [46]: print(tf.shape(ed_const2))

Tensor("Shape_10:0", shape=(4,), dtype=int32)


이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Convert to Tensor - Casting

(텐서플로우 텐서 변환 - 형변환)

참고: Tensor를 인자로 받는 함수들은, tf.convert_to_tensor의 인자가 될 수 있는 것들 또한 인자로 받을 수 있습니다.


형변환 (Casting)

TensorFlow는 그래프에 사용되는 텐서 자료형들을 형변환(cast)할 수 있는 몇 가지 함수를 제공합니다.


tf.string_to_number(string_tensor, out_type=None, name=None)


입력 텐서의 각 문자열(string)을 지정된 자료형의 값으로 변환합니다.


(참고로, int32 오버플로우는 에러를 내며, float 오버플로우는 반올림한 결과를 냅니다.)


인자:
  • string_tensor: stringTensor.
  • out_type: tf.DType 오브젝트. tf.float32 또는 tf.int32이어야 하며, 기본값은 tf.float32입니다. 이 자료형으로 string_tensor의 문자열이 변환됩니다. (선택사항)
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

out_type형의 Tensor. 출력 텐서는 입력 텐서 string_tensor와 같은 구조(shape)를 가집니다.


출처: 텐서 변환


Tensorflow tf.string_to_number 결과

In [1]: import tensorflow as tf

In [2]: import tfutil
In [3]: var = tf.Variable("500", dtype=tf.string)
In [4]: tfutil.print_variable(var)
500
In [5]: print(var)
<tf.Variable 'Variable:0' shape=() dtype=string_ref>
In [6]: num1 = tf.string_to_number(var, out_type=tf.int32)
In [7]: tfutil.print_operation_value(num1)
500
In [8]: print(num1)
Tensor("StringToNumber:0", shape=(), dtype=int32)

tf.to_double(x, name='ToDouble')


텐서를 float64형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 float64형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xfloat64형으로 변환될 수 없는 경우.


출처: 텐서 변환


Tensorflow tf.to_double 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: double1 = tf.to_double(const1)

In [7]: tfutil.print_operation_value(double1)

1.0

In [8]: print(double1)

Tensor("ToDouble:0", shape=(), dtype=float64)

In [9]: const2 = tf.constant([2, 3])

In [10]:tfutil.print_constant(const2)

[2 3]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [12]: double2 = tf.to_double(const2)

In [13]: tfutil.print_operation_value(double2)

[ 2.  3.]

In [14]: print(double2)

Tensor("ToDouble_1:0", shape=(2,), dtype=float64)


tf.to_float(x, name='ToFloat')


텐서를 float32형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 float32형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xfloat32형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.to_float 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1)

In [4]: tfutil.print_constant(const1)

1

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: float1 = tf.to_float(const1)

In [7]: tfutil.print_operation_value(float1)

1.0

In [8]: print(float1)

Tensor("ToFloat:0", shape=(), dtype=float32)

In [9]: const2 = tf.constant([23])

In [10]: tfutil.print_constant(const2)

[2 3]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [12]: float2 = tf.to_float(const2)

In [13]: tfutil.print_operation_value(float2)

[ 2.  3.]

In [14]: print(float2)

Tensor("ToFloat_1:0", shape=(2,), dtype=float32)


tf.to_bfloat16(x, name='ToBFloat16')


텐서를 bfloat16형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 bfloat16형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xbfloat16형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.to_bfloat16 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1, dtype=tf.float32)

In [4]: tfutil.print_constant(const1)

1.0

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=float32)

In [6]: bfloat1 = tf.to_bfloat16(const1)

In [7]: tfutil.print_operation_value(bfloat1)

16256

In [8]: print(bfloat1)

Tensor("ToBFloat16:0", shape=(), dtype=bfloat16)

In [9]: const2 = tf.constant([23], dtype=tf.float32)

In [10]: tfutil.print_constant(const2)

[ 2.  3.]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=float32)

In [12]: bfloat2 = tf.to_bfloat16(const2)

In [13]: tfutil.print_operation_value(bfloat2)

[16384 16448]

In [14]: print(bfloat2)

Tensor("ToBFloat16_1:0", shape=(2,), dtype=bfloat16)


tf.to_int32(x, name='ToInt32')


텐서를 int32형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 int32형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xint32형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.to_int32 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1, dtype=tf.float32)

In [4]: tfutil.print_constant(const1)

1.0

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=float32)

In [6]: int32_1 = tf.to_int32(const1)

In [7]: tfutil.print_operation_value(int32_1)

1

In [8]: print(int32_1)

Tensor("ToInt32:0", shape=(), dtype=int32)

In [9]: const2 = tf.constant([2, 3], dtype=tf.float32)

In [10]: tfutil.print_constant(const2)

[ 2.  3.]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=float32)

In [12]: int32_2 = tf.to_int32(const2)

In [13]: tfutil.print_operation_value(int32_2)

[2 3]

In [14]: print(int32_2)

Tensor("ToInt32_1:0", shape=(2,), dtype=int32)


tf.to_int64(x, name='ToInt64')


텐서를 int64형으로 변환합니다.

인자:
  • x: Tensor 또는 SparseTensor.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 int64형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xint64형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.to_int64 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(1, dtype=tf.float32)

In [4]: tfutil.print_constant(const1)

1.0

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=float32)

In [6]: int64_1 = tf.to_int64(const1)

In [7]: tfutil.print_operation_value(int64_1)

1

In [8]: print(int64_1)

Tensor("ToInt64:0", shape=(), dtype=int64)

In [9]: const2 = tf.constant([2, 3], dtype=tf.float32)

In [10]: tfutil.print_constant(const2)

[ 2.  3.]

In [11]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=float32)

In [12]: int64_2 = tf.to_int64(const2)

In [13]: tfutil.print_operation_value(int64_2)

[2 3]

In [14]: print(int64_2)

Tensor("ToInt64_1:0", shape=(2,), dtype=int64)


tf.cast(x, dtype, name=None)


텐서를 새로운 자료형으로 변환합니다.


x(Tensor의 경우) 또는 x.values(SparseTensor의 경우)를 dtype형으로 변환합니다.


예시:

# 텐서 `a`는 [1.8, 2.2], 자료형은 tf.float

tf.cast(a, tf.int32) ==> [1, 2]  # dtype=tf.int32

인자:
  • x: Tensor 또는 SparseTensor.
  • dtype: 변환될 자료형.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

x와 구조(shape)가 같은 int64형의 Tensor 또는 SparseTensor.

예외:
  • TypeError: xdtype형으로 변환될 수 없는 경우.

출처: 텐서 변환


Tensorflow tf.cast 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(127, dtype=tf.int32)

In [4]: tfutil.print_constant(const1)

127

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: f32 = tf.cast(const1, tf.float32)

In [7]: tfutil.print_operation_value(f32)

127.0

In [8]: print(f32)

Tensor("Cast:0", shape=(), dtype=float32)

In [9]: f64 = tf.cast(const1, tf.float64)

In [10]: tfutil.print_operation_value(f64)

127.0

In [11]: print(f64)

Tensor("Cast_1:0", shape=(), dtype=float64)

In [12]: i8 = tf.cast(const1, tf.int8)

In [13]: tfutil.print_operation_value(i8)

127

In [14]: print(i8)

Tensor("Cast_2:0", shape=(), dtype=int8)

In [15]: i16 = tf.cast(const1, tf.int16)

In [16]: tfutil.print_operation_value(i16)

127

In [17]: print(i16)

Tensor("Cast_3:0", shape=(), dtype=int16)

In [18]: i64 = tf.cast(const1, tf.int64)

In [19]: tfutil.print_operation_value(i64)

127

In [20]: print(i64)

Tensor("Cast_4:0", shape=(), dtype=int64)

In [21]: u8 = tf.cast(const1, tf.uint8)

In [22]: tfutil.print_operation_value(u8)

127

In [23]: print(u8)

Tensor("Cast_5:0", shape=(), dtype=uint8)

In [24]: const2 = tf.constant([127, 255])

In [25]: tfutil.print_constant(const2)

[127 255]

In [26]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [27]: f32 = tf.cast(const2, tf.float32)

In [28]: tfutil.print_operation_value(f32)

[ 127.  255.]

In [29]: print(f32)

Tensor("Cast_6:0", shape=(2,), dtype=float32)

In [30]: f64 = tf.cast(const2, tf.float64)

In [31]: tfutil.print_operation_value(f64)

[ 127.  255.]

In [32]: print(f64)

Tensor("Cast_7:0", shape=(2,), dtype=float64)

In [33]: i8 = tf.cast(const2, tf.int8)

In [34]: tfutil.print_operation_value(i8)

[127  -1]

In [35]: print(i8)

Tensor("Cast_8:0", shape=(2,), dtype=int8)

In [36]: i16 = tf.cast(const2, tf.int16)

In [37]: tfutil.print_operation_value(i16)

[127 255]

In [38]: print(i16)

Tensor("Cast_9:0", shape=(2,), dtype=int16)

In [39]: i64 = tf.cast(const2, tf.int64)

In [40]: tfutil.print_operation_value(i64)

[127 255]

In [41]: print(i64)

Tensor("Cast_10:0", shape=(2,), dtype=int64)

In [42]: u8 = tf.cast(const2, tf.uint8)

In [43]: tfutil.print_operation_value(u8)

[127 255]

In [44]: print(u8)

Tensor("Cast_11:0", shape=(2,), dtype=uint8)


tf.saturate_cast(value, dtype, name=None)


valuedtype 형으로 안전하게 포화 형변환(saturating cast)합니다.


이 함수는 입력을 dtype으로 스케일링(scaling) 없이 변환합니다. 형변환 시 오버플로우나 언더플로우가 발생할 수 있는 값들에 대해, 이 함수는 해당 값들을 허용되는 값 범위로 넣은 뒤 형변환을 진행합니다.

인자:
  • value: Tensor.
  • dtype: DType 오브젝트. 변환될 자료형.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

dtype형으로 안전하게 변환된 value.


출처: 텐서 변환


Tensorflow tf.saturate_cast 결과

In [1]: import tensorflow as tf

In [2]: import tfutil

In [3]: const1 = tf.constant(127, dtype=tf.int32)

In [4]: tfutil.print_constant(const1)

127

In [5]: print(const1)

Tensor("Const:0", shape=(), dtype=int32)

In [6]: f32 = tf.saturate_cast(const1, tf.float32)

In [7]: tfutil.print_operation_value(f32)

127.0

In [8]: print(f32)

Tensor("saturate_cast:0", shape=(), dtype=float32)

In [9]: f64 = tf.saturate_cast(const1, tf.float64)

In [10]: tfutil.print_operation_value(f64)

127.0

In [11]: print(f64)

Tensor("saturate_cast_1:0", shape=(), dtype=float64)

In [12]: i8 = tf.saturate_cast(const1, tf.int8)

In [13]: tfutil.print_operation_value(i8)

127

In [14]: print(i8)

Tensor("saturate_cast_2:0", shape=(), dtype=int8)

In [15]: i16 = tf.saturate_cast(const1, tf.int16)

In [16]: tfutil.print_operation_value(i16)

127

In [17]: print(i16)

Tensor("saturate_cast_3:0", shape=(), dtype=int16)

In [18]: i64 = tf.saturate_cast(const1, tf.int64)

In [19]: tfutil.print_operation_value(i64)

127

In [20]: print(i64)

Tensor("saturate_cast_4:0", shape=(), dtype=int64)

In [21]: u8 = tf.saturate_cast(const1, tf.uint8)

In [22]: tfutil.print_operation_value(u8)

127

In [23]: print(u8)

Tensor("saturate_cast_5:0", shape=(), dtype=uint8)

In [24]: const2 = tf.constant([127, 255])

In [25]: tfutil.print_constant(const2)

[127 255]

In [26]: print(const2)

Tensor("Const_1:0", shape=(2,), dtype=int32)

In [27]: f32 = tf.saturate_cast(const2, tf.float32)

In [28]: tfutil.print_operation_value(f32)

[ 127.  255.]

In [29]: print(f32)

Tensor("saturate_cast_6:0", shape=(2,), dtype=float32)

In [30]: f64 = tf.saturate_cast(const2, tf.float64)

In [31]: tfutil.print_operation_value(f64)

[ 127.  255.]

In [32]: print(f64)

Tensor("saturate_cast_7:0", shape=(2,), dtype=float64)

In [33]: i8 = tf.saturate_cast(const2, tf.int8)

In [34]: tfutil.print_operation_value(i8)

[127 127]

In [35]: print(i8)

Tensor("saturate_cast_8:0", shape=(2,), dtype=int8)

In [36]: i16 = tf.saturate_cast(const2, tf.int16)

In [37]: tfutil.print_operation_value(i16)

[127 255]

In [38]: print(i16)

Tensor("saturate_cast_9:0", shape=(2,), dtype=int16)

In [39]: i64 = tf.saturate_cast(const2, tf.int64)

In [40]: tfutil.print_operation_value(i64)

[127 255]

In [41]: print(i64)

Tensor("saturate_cast_10:0", shape=(2,), dtype=int64)

In [42]: u8 = tf.saturate_cast(const2, tf.uint8)

In [43]: tfutil.print_operation_value(u8)

[127 255]

In [44]: print(u8)

Tensor("saturate_cast_11:0", shape=(2,), dtype=uint8)


tf.bitcast(input, type, name=None)


텐서를 다른 자료형으로 데이터 복사 없이 비트캐스트(bitcast)합니다.


input 텐서가 주어질 때, 이 함수는 input과 같은 버퍼 데이터를 가진 자료형 type의 텐서를 반환합니다.

만약 입력의 자료형 T가 출력의 자료형 type에 비해 더 큰 경우, 구조(shape)가 [...]에서 [..., sizeof(T)/sizeof(type)]으로 변형됩니다.

만약 T가 type에 비해 더 작은 경우, 가장 오른쪽의 차원이 sizeof(type)/sizeof(T)와 같아야 합니다. 구조는 [..., sizeof(type)/sizeof(T)] to [...]으로 변형됩니다.

인자:
  • inputTensor. 다음의 자료형이 가능합니다: float32float64int64int32uint8uint16int16int8complex64complex128qint8quint8qint32half.
  • typetf.DType. 다음 중 하나가 가능합니다: tf.float32, tf.float64, tf.int64, tf.int32, tf.uint8, tf.uint16, tf.int16, tf.int8, tf.complex64, tf.complex128, tf.qint8, tf.quint8, tf.qint32, tf.half.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

type 자료형의 Tensor.


출처: 텐서 변환


Tensorflow tf.bitcast 결과

In [1]:

import tensorflow as tf

import numpy as np

import tfutil

In [2]:

= 37.0

const1 = tf.constant(x) 

print(const1)

print(tf.shape(const1))

tfutil.print_constant(const1)

Tensor("Const:0", shape=(), dtype=float32)

Tensor("Shape:0", shape=(0,), dtype=int32)

37.0

In [3]:

bc_const1 = tf.bitcast(const1, tf.int32)

print(bc_const1)

print(tf.shape(bc_const1))

tfutil.print_operation_value(bc_const1)

Tensor("Bitcast:0", shape=(), dtype=int32)

Tensor("Shape_1:0", shape=(0,), dtype=int32)

1108606976

In [4]:

= -1

invert_bits = tf.constant(x) - bc_const1

print(invert_bits)

print(tf.shape(invert_bits))

tfutil.print_operation_value(invert_bits)

Tensor("sub:0", shape=(), dtype=int32)

Tensor("Shape_2:0", shape=(0,), dtype=int32)

-1108606977

In [5]:

bc_to_float = tf.bitcast(invert_bits, tf.float32)

print(bc_to_float)

print(tf.shape(bc_to_float))

tfutil.print_operation_value(bc_to_float)

Tensor("Bitcast_1:0", shape=(), dtype=float32)

Tensor("Shape_3:0", shape=(0,), dtype=int32)

-0.115234


tf.shape_n(input, name=None)


텐서의 구조(shape)를 반환합니다.


이 함수는 input[i]들의 구조를 나타내는 N개의 1-D 정수 텐서를 반환합니다.

인자:
  • input: 같은 자료형의 1개 이상의 Tensor의 리스트.
  • name: 오퍼레이션의 명칭. (선택사항)
반환값:

input의 텐서와 같은 개수의 int32형 Tensor의 리스트.


출처: 텐서 변환



이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[API] Tensorflow Variables

(텐서플로우 변수)

Note: 함수의 Tensor 인자는 tf.convert_to_tensor에 의한 것도 가능합니다.


class tf.Variable


class tf.Variable

Variables How To에서 자세한 개요를 확인할 수 있습니다.


변수는 graph에서 run()의 호출로 상태를 유지합니다. Variable의 객체를 만들어 graph에 변수를 추가합니다.


Variable() 생성자는 변수의 초기값으로 Tensor의 type과 shape이 필요합니다. 초기값은 변수의 type과 shape를 정의합니다. 생성 후, 변수의 type과 shape은 고정됩니다. 변수의 값은 assign 메소드를 사용해 변경할 수 있습니다.


후에 변수의 shape를 변경하고 싶다면 assign에서 validate_shape=False로 해야합니다.


Tensor의 경우, Variable()로 만들어진 변수는 graph의 ops의 input으로 사용될 수 있습니다. 추가적으로, Tensor 클래스로 오버로드 되는 모든 연산(operators)은 변수로 넘겨집니다. 그래서 변수의 산술연산만으로도 graph에 노드를 추가할 수 있습니다.

import tensorflow as tf

# Create a variable.
w = tf.Variable(<initial-value>, name=<optional-name>)

# Use the variable in the graph like any Tensor.
y = tf.matmul(w, ...another variable or tensor...)

# The overloaded operators are available too.
z = tf.sigmoid(w + y)

# Assign a new value to the variable with `assign()` or a related method.
w.assign(w + 1.0)
w.assign_add(1.0)


graph를 실행할 때, 변수는 그 값을 사용하는 ops를 실행하기 전에 명시적으로 초기화해야 합니다. 변수는 1)initializer op를 실행하거나, 2)저장된 파일로부터 변수를 다시 저장(restoring)하거나, 3)간단하게 변수에 값을 할당하는 assign Op을 실행하여 초기화 할 수 있습니다. 사실, 변수 initializer op는 단지 변수의 초기값을 할당하는 assign Op 입니다.

# Launch the graph in a session.
with tf.Session() as sess:
    # Run the variable initializer.
    sess.run(w.initializer)
    # ...you now can run ops that use the value of 'w'...


가장 일반적인 초기화 방법은 모든 변수를 초기화 할 graph에 편의 함수인 initialize_all_variables()으로 Op를 추가하는 것 입니다. 그런 다음 graph를 실행한 후 Op를 실행합니다.

# Add an Op to initialize all variables.
init_op = tf.initialize_all_variables()

# Launch the graph in a session.
with tf.Session() as sess:
    # Run the Op that initializes all variables.
    sess.run(init_op)
    # ...you can now run any Op that uses variable values...


다른 변수의 결과로 초기되는 변수를 만들어야한다면, 다른 변수의 initialized_value()를 사용합니다. 이것은 변수가 올바는 순서로 초기화되도록 합니다.


모든 변수들은 자동적으로 그들이 만들어진 graph에 쌓입니다. 기본적으로, 생성자는 그래프 컬렉션(graph collection) GraphKeys.VARIABLES에 변수를 추가합니다. 편의 함수인 all_variables()은 컬렉션의 내용을 반환합니다.


머신 러닝 모델을 만들 때, 학습 가능한 모델 매개변수를 가지고 있는 변수와 global step 변수과 같이 학습 단계를 계산하기 위한 다른 변수로 구분하는 것은 종종 편리합니다. 이것을 더 쉽게 하기위해, 변수 생성자는 trainable=<bool> 매개변수를 지원합니다. True일 때 새로운 변수는 그래프 컬렉션 GraphKeys.TRAINABLE_VARIABLES에 추가됩니다. 편의 함수 trainable_variables()는 이 컬렉션의 내용을 반환합니다. 다양한 Optimizer 클래스는 이 컬렉션을 최적화(optimize) 변수의 기본 리스트로 사용합니다.


Creating a variable.


출처: Variables



이 포스팅은 머신러닝/딥러닝 오픈소스 Tensorflow 개발을 위한 선행학습으로 Tensorflow API Document의 Python API 대한 학습노트입니다.

Posted by 이성윤

[Part2. Unit 14] 

패턴 073(~할 수 있는 곳이 어디죠? [Where Can I]

~ 076(어디에 ~인지 알려 주실래요? [Could you please tell me where])


패턴 073 ~할 수 있는 곳이 어디죠? [Where can I]

'물건을 어디에 놓을까요??'라는 말을 영어로 표현할 때 Where can I put...?패턴을 쓰면 편하듯이 where와 can I가 만나면 '내가 어디(에서) ~을 할까?' 라는 의미가 됩니다.

1. 그 사람 어디에 있어요?
★ Where can I find him?

2. 가장 싸게 파는 곳은 어디예요?
★ Where ca I find a good deal?

3. 내 코트를 어디에 걸까요?
★ Where can I hang my coat?

4. 어디에 앉을 수 있죠?
★ Where can I sit?

5. 제 차를 어디에 주차할 수 있나요?

★ Where can I park my car?

패턴 074 ~하기에 가장 좋을 곳이 어디죠? [Where's the best place to]

the best way가 가장 좋은 방법이라면 the best place는 가장 좋은 장소를 가리킵니다. 이 패턴은 쇼핑을 할 때나 호텔을 예약할 때, 여행할 때 등 두루두루 쓸 수 있죠.

1. 식료품을 가장 싸게 살 수 있는 곳이 어디야?
★ Where's the best place to buy groceries?

2. 비디오를 가장 싸게 빌릴 수 있는 곳이 어디야?
★ Where's the best place to rent a movie?

3. 신발을 가장 잘 살 수 있는 곳은 어디죠?
★ Where's the best place to shop for shoes?

4. 휴가 여행지로 가장 좋은 곳은 어디예요?
★ Where's the best place to go on vacation?

5. 신선한 과일을 살 수 있는 가장 좋은 가계는 어디예요?

★ Where's the best place to buy fresh fruit?

패턴 075 ~를 어디서 해야 할까요? [Where do you think I should]

이 패턴은 Where + do you think + I should가 만나서 이루어진 복합 응용 패턴이에요. 직역을 하면 '내가 어디에서 ~를 해야 한다고 넌 생각해?'가 되겠죠?

1. 결혼 피로연은 어디서 해야 할까?
★ Where do you think I should hold the wedding reception?

2. 어디로 이사를 해야 할까요?
★ Where do you think I should move?

3. 여름 휴가를 어디로 가야 할까요?
★ Where do you think I should go for my summer trip?

4. 어디서 먹어야 하지?
★ Where do you think I should eat?

5. 내가 어디에서 파티를 해야 한다고 생각해?

★ Where do you think I should have my party?

패턴 076 어디에 ~인지 알려 주실래요? [Could you please tell me where]

Would you...로 바꾸어 표현할 수 있는 이 패턴은 주로 어떤 위치나 장소를 물어볼 때 쓸 수 있어요. 이렇게 물어볼 때는 where뒤에 주어+동사의 순서가 된다는 것 잊지 마세요. 물론 구어체에선 동사+주어가 돼도 큰 상관은 없어요.

1. 그분이 어디에 있는지 말씀해 주실래요?
★ Could you please tell me where he is?

2. 너 어디에 가니?
★ Could you please tell me where you're going?

3. 화장실이 어딘지 알려 주시겠어요?
★ Could you please tell me where the bathroom is?

4. 존슨 스트릿이 어디죠?
★ Could you please tell me where Johnson Street is?

5. 주차장이 어디에 있나요?

★ Could you tell me where the parking garage is?


이 포스팅은 영어회화 핵심패턴 233 교재의 Unit 14(패턴 073 ~ 패턴 076)대한 학습노트입니다.

Posted by 이성윤