처음에 numpy 배열이 2차원을 넘어가면 엄청 엄청 햇갈렸다 ! 2 차원은 그래도 행렬 느낌인데 그 이상은 😨😨

나만의 이해한 방식이 있는데 이렇게 생각하는게 맞는지 모르겠지만 내가 이해했으면 된거지 !

KakaoTalk_Photo_2021-04-07-22-43-12

>>> a=tf.reshape(a,(2,3,4))
>>> a
<tf.Tensor: shape=(2, 3, 4), dtype=int32, numpy=
array([[[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]],

       [[13, 14, 15, 16],
        [17, 18, 19, 20],
        [21, 22, 23, 24]]], dtype=int32)>
  • squeeze / unsqueeze / expand_dims
  • stack
  • concatenate
  • Add
  • Multiply
1) squeeze

차원 중 사이즈가 1인 것을 다 제거해버린다.

>>> b=tf.reshape(b,(1,2,3))
>>> b
<tf.Tensor: shape=(1, 2, 3), dtype=int32, numpy=
array([[[1, 2, 3],
        [4, 5, 6]]], dtype=int32)>

우선 dim 0 의 사이즈가 1이기 때문에 아이템

​ [[1, 2, 3], ​ [4, 5, 6]] 이 1개 딱 들어있어서 바로 세번째 뚜껑을 덮어버렸다.

squeeze 를 해주게 되면, 세번째 뚜껑이 없어진다.

>>> tf.squeeze(b)
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)>

2) unsqeeze 같은 메소드가 프레임워크에 따라서 이름만 다르다. torch, numpy 는 unsqueeze 인 것 같고, 텐플은 expand_dims 이다.

지정하는 위치에 사이즈가 1인 차원을 추가해준다.

>>> b=tf.expand_dims(b,0)
>>> b
<tf.Tensor: shape=(1, 1, 2, 3), dtype=int32, numpy=
array([[[[1, 2, 3],
         [4, 5, 6]]]], dtype=int32)>
3) stack

단어 그대로 텐서들을 차곡차곡 지정한 축을 기준으로 쌓아준다. 단, 새로운 축을 만들어서 쌓는다.

>>> a=tf.constant([1,2,3])
>>> b=tf.constant([4,5,6])
>>> c=tf.stack([a,b],0)
>>> c
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)>

“0차원에 스택해달라” 시켰기 때문에 총 텐서 갯수가 0차원의 사이즈가 되었다.

4) concatenate

concatenate 도 텐서를 쌓는데, 차원을 새로 만들지 않는다.

>>> d=tf.concat([a,b],0)
>>> d
<tf.Tensor: shape=(6,), dtype=int32, numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>
5) Add

이건 add& norm 때문에 엄청 자주 쓰이는 것 같다. element-wise adding 을 한다.

def add_and_norm(x_list):
  """Applies skip connection followed by layer normalisation.
  Args:
    x_list: List of inputs to sum for skip connection
  Returns:
    Tensor output from layer.
  """
  tmp = Add()(x_list)
  tmp = LayerNorm()(tmp)
  return tmp
6) Multiply

element-wise 곱셈

>>> tf.keras.layers.Multiply()([np.arange(5).reshape(5, 1),
...                             np.arange(5, 10).reshape(5, 1)])
<tf.Tensor: shape=(5, 1), dtype=int64, numpy=
array([[ 0],
       [ 6],
       [14],
       [24],
       [36]])>

이게 텐플 공식 예시 코드인데 텐서말고 넘파이 넣어도 연산이 되는 줄 처음 알았다. 오 좋은 걸 👀

내일 faster r-cnn 파이토치 실습을 해보려고 하는데 좀 걱정도 된다 ! 잘할 수 있겠지.. ?