강의노트

import

import tensorflow as tf
import numpy as np
tf.config.experimental.list_physical_devices('GPU')
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

tf.constant

예비학습: 중첩리스트

- 리스트

lst = [1,2,4,5,6]
lst 
[1, 2, 4, 5, 6]
lst[1] # 두번쨰원소 
2
lst[-1] # 마지막원소 
6

- (2,2) matrix 느낌의 list

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

위를 아래와 같은 매트릭스로 생각할수 있다.

1 2 
3 4
print(lst[0][0]) # (1,1) 
print(lst[0][1]) # (1,2) 
print(lst[1][0]) # (2,1) 
print(lst[1][1]) # (2,2) 
1
2
3
4

- (4,1) matrix 느낌의 list

lst=[[1],[2],[3],[4]] # (4,1) matrix = 길이가 4인 col-vector
lst
[[1], [2], [3], [4]]

- (1,4) matrix 느낌의 list

lst=[[1,2,3,4]] # (1,4) matrix = 길이가 4인 row-vector 
lst
[[1, 2, 3, 4]]

선언

- 스칼라

tf.constant(3.14)
<tf.Tensor: shape=(), dtype=float32, numpy=3.14>
tf.constant(3.14)+tf.constant(3.14)
<tf.Tensor: shape=(), dtype=float32, numpy=6.28>

- 벡터

_vector=tf.constant([1,2,3])
_vector[-1]
<tf.Tensor: shape=(), dtype=int32, numpy=3>

- 매트릭스

_matrix= tf.constant([[1,0],[0,1]])
_matrix
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 0],
       [0, 1]], dtype=int32)>

- array

tf.constant([[[0,1,1],[1,2,-1]],[[0,1,2],[1,2,-1]]])
<tf.Tensor: shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 0,  1,  1],
        [ 1,  2, -1]],

       [[ 0,  1,  2],
        [ 1,  2, -1]]], dtype=int32)>

타입

type(tf.constant(3.14))
tensorflow.python.framework.ops.EagerTensor

인덱싱

_matrix = tf.constant([[1,2],[3,4]])
_matrix
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
       [3, 4]], dtype=int32)>
_matrix[0][0]
<tf.Tensor: shape=(), dtype=int32, numpy=1>
_matrix[0]
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 2], dtype=int32)>
_matrix[0,:]
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 2], dtype=int32)>
_matrix[:,0]
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 3], dtype=int32)>

tf.constant는 불편하다.

- 불편한점

  1. 모든 원소가 같은 dtype을 가지고 있어야함.
  2. 원소 수정이 불가능함.
  3. 묵시적 형변환이 불가능하다.

- 원소수정이 불가능함

a=tf.constant([1,22,33])
a
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([ 1, 22, 33], dtype=int32)>
a[0]=11
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [24], in <cell line: 1>()
----> 1 a[0]=11

TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment

- 묵시적 형변환이 불가능하다

tf.constant(1)+tf.constant(3.14)
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
Input In [25], in <cell line: 1>()
----> 1 tf.constant(1)+tf.constant(3.14)

File ~/anaconda3/envs/py310/lib/python3.10/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    151 except Exception as e:
    152   filtered_tb = _process_traceback_frames(e.__traceback__)
--> 153   raise e.with_traceback(filtered_tb) from None
    154 finally:
    155   del filtered_tb

File ~/anaconda3/envs/py310/lib/python3.10/site-packages/tensorflow/python/framework/ops.py:7107, in raise_from_not_ok_status(e, name)
   7105 def raise_from_not_ok_status(e, name):
   7106   e.message += (" name: " + name if name is not None else "")
-> 7107   raise core._status_to_exception(e) from None

InvalidArgumentError: cannot compute AddV2 as input #1(zero-based) was expected to be a int32 tensor but is a float tensor [Op:AddV2]
tf.constant(1.0)+tf.constant(3.14)
<tf.Tensor: shape=(), dtype=float32, numpy=4.1400003>

- 같은 float도 안되는 경우가 있음

tf.constant(1.0,dtype=tf.float64)
<tf.Tensor: shape=(), dtype=float64, numpy=1.0>
tf.constant(3.14)
<tf.Tensor: shape=(), dtype=float32, numpy=3.14>
tf.constant(1.0,dtype=tf.float64)+tf.constant(3.14)
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
Input In [29], in <cell line: 1>()
----> 1 tf.constant(1.0,dtype=tf.float64)+tf.constant(3.14)

File ~/anaconda3/envs/py310/lib/python3.10/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    151 except Exception as e:
    152   filtered_tb = _process_traceback_frames(e.__traceback__)
--> 153   raise e.with_traceback(filtered_tb) from None
    154 finally:
    155   del filtered_tb

File ~/anaconda3/envs/py310/lib/python3.10/site-packages/tensorflow/python/framework/ops.py:7107, in raise_from_not_ok_status(e, name)
   7105 def raise_from_not_ok_status(e, name):
   7106   e.message += (" name: " + name if name is not None else "")
-> 7107   raise core._status_to_exception(e) from None

InvalidArgumentError: cannot compute AddV2 as input #1(zero-based) was expected to be a double tensor but is a float tensor [Op:AddV2]

tf.constant $\to$ 넘파이

np.array(tf.constant(1)) # 방법1
array(1, dtype=int32)
a=tf.constant([3.14,-3.14])
type(a)
tensorflow.python.framework.ops.EagerTensor
a.numpy()
array([ 3.14, -3.14], dtype=float32)

연산

- 더하기

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

- 곱하기

a=tf.constant([[1,2],[3,4]])
b=tf.constant([[5,6],[7,8]])
a*b
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 5, 12],
       [21, 32]], dtype=int32)>
tf.multiply(a,b)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 5, 12],
       [21, 32]], dtype=int32)>

- 매트릭스의곱

a=tf.constant([[1,0],[0,1]]) # (2,2)
b=tf.constant([[5],[7]]) # (2,1) 
a@b
<tf.Tensor: shape=(2, 1), dtype=int32, numpy=
array([[5],
       [7]], dtype=int32)>
tf.matmul(a,b)
<tf.Tensor: shape=(2, 1), dtype=int32, numpy=
array([[5],
       [7]], dtype=int32)>

- 역행렬

a=tf.constant([[1,0],[0,2]])
a
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 0],
       [0, 2]], dtype=int32)>
tf.linalg.inv(a)
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
Input In [40], in <cell line: 1>()
----> 1 tf.linalg.inv(a)

File ~/anaconda3/envs/py310/lib/python3.10/site-packages/tensorflow/python/ops/gen_linalg_ops.py:1506, in matrix_inverse(input, adjoint, name)
   1504   return _result
   1505 except _core._NotOkStatusException as e:
-> 1506   _ops.raise_from_not_ok_status(e, name)
   1507 except _core._FallbackException:
   1508   pass

File ~/anaconda3/envs/py310/lib/python3.10/site-packages/tensorflow/python/framework/ops.py:7107, in raise_from_not_ok_status(e, name)
   7105 def raise_from_not_ok_status(e, name):
   7106   e.message += (" name: " + name if name is not None else "")
-> 7107   raise core._status_to_exception(e) from None

InvalidArgumentError: Value for attr 'T' of int32 is not in the list of allowed values: double, float, half, complex64, complex128
	; NodeDef: {{node MatrixInverse}}; Op<name=MatrixInverse; signature=input:T -> output:T; attr=adjoint:bool,default=false; attr=T:type,allowed=[DT_DOUBLE, DT_FLOAT, DT_HALF, DT_COMPLEX64, DT_COMPLEX128]> [Op:MatrixInverse]
a=tf.constant([[1.0,0.0],[0.0,2.0]])
tf.linalg.inv(a)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1. , 0. ],
       [0. , 0.5]], dtype=float32)>

- tf.linalg. + tab을 누르면 좋아보이는 연산들 많음

a=tf.constant([[1.0,2.0],[3.0,4.0]])
print(a)
tf.linalg.det(a)
tf.Tensor(
[[1. 2.]
 [3. 4.]], shape=(2, 2), dtype=float32)
<tf.Tensor: shape=(), dtype=float32, numpy=-2.0>
tf.linalg.trace(a)
<tf.Tensor: shape=(), dtype=float32, numpy=5.0>

형태변환

- 기본: tf.reshape() 를 이용

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

       [[3],
        [4]]], dtype=int32)>

- 다차원

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

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

- tf.resh

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

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

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

선언고급

- 다른 자료형 (리스트나 넘파이)로 만들고 바꾸는것도 좋다.

np.diag([1,2,3,4])
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
tf.constant(np.diag([1,2,3,4]))
<tf.Tensor: shape=(4, 4), dtype=int64, numpy=
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])>

- tf.ones, tf.zeros

tf.zeros([3,3])
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]], dtype=float32)>
tf.reshape(tf.constant([0]*9),(3,3))
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]], dtype=int32)>

- range(10)

a=range(0,12)
tf.constant(a)
<tf.Tensor: shape=(12,), dtype=int32, numpy=array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11], dtype=int32)>
tf.constant(range(1,20,3)) 
<tf.Tensor: shape=(7,), dtype=int32, numpy=array([ 1,  4,  7, 10, 13, 16, 19], dtype=int32)>

- tf.linspace

tf.linspace(0,1,10)
<tf.Tensor: shape=(10,), dtype=float64, numpy=
array([0.        , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
       0.55555556, 0.66666667, 0.77777778, 0.88888889, 1.        ])>

tf.concat

- (2,1) concat (2,1) => (2,2)

  • 두번째 축이 바뀌었다. => axis=1
a=tf.constant([[1],[2]])
b=tf.constant([[3],[4]])
a,b
(<tf.Tensor: shape=(2, 1), dtype=int32, numpy=
 array([[1],
        [2]], dtype=int32)>,
 <tf.Tensor: shape=(2, 1), dtype=int32, numpy=
 array([[3],
        [4]], dtype=int32)>)
tf.concat([a,b],axis=1)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 3],
       [2, 4]], dtype=int32)>

- (2,1) concat (2,1) => (4,1)

  • 첫번째 축이 바뀌었다. => axis=0
a=tf.constant([[1],[2]])
b=tf.constant([[3],[4]])
a,b
(<tf.Tensor: shape=(2, 1), dtype=int32, numpy=
 array([[1],
        [2]], dtype=int32)>,
 <tf.Tensor: shape=(2, 1), dtype=int32, numpy=
 array([[3],
        [4]], dtype=int32)>)
tf.concat([a,b],axis=0)
<tf.Tensor: shape=(4, 1), dtype=int32, numpy=
array([[1],
       [2],
       [3],
       [4]], dtype=int32)>

- (1,2) concat (1,2) => (2,2)

  • 첫번째 // axis=0
a=tf.constant([[1,2]])
b=tf.constant([[3,4]])
tf.concat([a,b],axis=0)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
       [3, 4]], dtype=int32)>

- (1,2) concat (1,2) => (1,4)

  • 첫번째 // axis=0

- (2,3,4,5) concat (2,3,4,5) => (4,3,4,5)

  • 첫번째 // axis=0
a=tf.reshape(tf.constant(range(120)),(2,3,4,5))
b=-a
tf.concat([a,b],axis=0)
<tf.Tensor: shape=(4, 3, 4, 5), dtype=int32, numpy=
array([[[[   0,    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,   31,   32,   33,   34],
         [  35,   36,   37,   38,   39]],

        [[  40,   41,   42,   43,   44],
         [  45,   46,   47,   48,   49],
         [  50,   51,   52,   53,   54],
         [  55,   56,   57,   58,   59]]],


       [[[  60,   61,   62,   63,   64],
         [  65,   66,   67,   68,   69],
         [  70,   71,   72,   73,   74],
         [  75,   76,   77,   78,   79]],

        [[  80,   81,   82,   83,   84],
         [  85,   86,   87,   88,   89],
         [  90,   91,   92,   93,   94],
         [  95,   96,   97,   98,   99]],

        [[ 100,  101,  102,  103,  104],
         [ 105,  106,  107,  108,  109],
         [ 110,  111,  112,  113,  114],
         [ 115,  116,  117,  118,  119]]],


       [[[   0,   -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,  -31,  -32,  -33,  -34],
         [ -35,  -36,  -37,  -38,  -39]],

        [[ -40,  -41,  -42,  -43,  -44],
         [ -45,  -46,  -47,  -48,  -49],
         [ -50,  -51,  -52,  -53,  -54],
         [ -55,  -56,  -57,  -58,  -59]]],


       [[[ -60,  -61,  -62,  -63,  -64],
         [ -65,  -66,  -67,  -68,  -69],
         [ -70,  -71,  -72,  -73,  -74],
         [ -75,  -76,  -77,  -78,  -79]],

        [[ -80,  -81,  -82,  -83,  -84],
         [ -85,  -86,  -87,  -88,  -89],
         [ -90,  -91,  -92,  -93,  -94],
         [ -95,  -96,  -97,  -98,  -99]],

        [[-100, -101, -102, -103, -104],
         [-105, -106, -107, -108, -109],
         [-110, -111, -112, -113, -114],
         [-115, -116, -117, -118, -119]]]], dtype=int32)>

- (2,3,4,5) concat (2,3,4,5) => (2,6,4,5)

  • 두번째 // axis=1
a=tf.reshape(tf.constant(range(120)),(2,3,4,5))
b=-a
tf.concat([a,b],axis=1)
<tf.Tensor: shape=(2, 6, 4, 5), dtype=int32, numpy=
array([[[[   0,    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,   31,   32,   33,   34],
         [  35,   36,   37,   38,   39]],

        [[  40,   41,   42,   43,   44],
         [  45,   46,   47,   48,   49],
         [  50,   51,   52,   53,   54],
         [  55,   56,   57,   58,   59]],

        [[   0,   -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,  -31,  -32,  -33,  -34],
         [ -35,  -36,  -37,  -38,  -39]],

        [[ -40,  -41,  -42,  -43,  -44],
         [ -45,  -46,  -47,  -48,  -49],
         [ -50,  -51,  -52,  -53,  -54],
         [ -55,  -56,  -57,  -58,  -59]]],


       [[[  60,   61,   62,   63,   64],
         [  65,   66,   67,   68,   69],
         [  70,   71,   72,   73,   74],
         [  75,   76,   77,   78,   79]],

        [[  80,   81,   82,   83,   84],
         [  85,   86,   87,   88,   89],
         [  90,   91,   92,   93,   94],
         [  95,   96,   97,   98,   99]],

        [[ 100,  101,  102,  103,  104],
         [ 105,  106,  107,  108,  109],
         [ 110,  111,  112,  113,  114],
         [ 115,  116,  117,  118,  119]],

        [[ -60,  -61,  -62,  -63,  -64],
         [ -65,  -66,  -67,  -68,  -69],
         [ -70,  -71,  -72,  -73,  -74],
         [ -75,  -76,  -77,  -78,  -79]],

        [[ -80,  -81,  -82,  -83,  -84],
         [ -85,  -86,  -87,  -88,  -89],
         [ -90,  -91,  -92,  -93,  -94],
         [ -95,  -96,  -97,  -98,  -99]],

        [[-100, -101, -102, -103, -104],
         [-105, -106, -107, -108, -109],
         [-110, -111, -112, -113, -114],
         [-115, -116, -117, -118, -119]]]], dtype=int32)>

- (2,3,4,5) concat (2,3,4,5) => (2,3,8,5)

  • 세번째 // axis=2
a=tf.reshape(tf.constant(range(120)),(2,3,4,5))
b=-a
tf.concat([a,b],axis=2)
<tf.Tensor: shape=(2, 3, 8, 5), dtype=int32, numpy=
array([[[[   0,    1,    2,    3,    4],
         [   5,    6,    7,    8,    9],
         [  10,   11,   12,   13,   14],
         [  15,   16,   17,   18,   19],
         [   0,   -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,   31,   32,   33,   34],
         [  35,   36,   37,   38,   39],
         [ -20,  -21,  -22,  -23,  -24],
         [ -25,  -26,  -27,  -28,  -29],
         [ -30,  -31,  -32,  -33,  -34],
         [ -35,  -36,  -37,  -38,  -39]],

        [[  40,   41,   42,   43,   44],
         [  45,   46,   47,   48,   49],
         [  50,   51,   52,   53,   54],
         [  55,   56,   57,   58,   59],
         [ -40,  -41,  -42,  -43,  -44],
         [ -45,  -46,  -47,  -48,  -49],
         [ -50,  -51,  -52,  -53,  -54],
         [ -55,  -56,  -57,  -58,  -59]]],


       [[[  60,   61,   62,   63,   64],
         [  65,   66,   67,   68,   69],
         [  70,   71,   72,   73,   74],
         [  75,   76,   77,   78,   79],
         [ -60,  -61,  -62,  -63,  -64],
         [ -65,  -66,  -67,  -68,  -69],
         [ -70,  -71,  -72,  -73,  -74],
         [ -75,  -76,  -77,  -78,  -79]],

        [[  80,   81,   82,   83,   84],
         [  85,   86,   87,   88,   89],
         [  90,   91,   92,   93,   94],
         [  95,   96,   97,   98,   99],
         [ -80,  -81,  -82,  -83,  -84],
         [ -85,  -86,  -87,  -88,  -89],
         [ -90,  -91,  -92,  -93,  -94],
         [ -95,  -96,  -97,  -98,  -99]],

        [[ 100,  101,  102,  103,  104],
         [ 105,  106,  107,  108,  109],
         [ 110,  111,  112,  113,  114],
         [ 115,  116,  117,  118,  119],
         [-100, -101, -102, -103, -104],
         [-105, -106, -107, -108, -109],
         [-110, -111, -112, -113, -114],
         [-115, -116, -117, -118, -119]]]], dtype=int32)>

- (2,3,4,5) concat (2,3,4,5) => (2,3,4,10)

  • 네번째 // axis=3 # 0,1,2,3 // -4 -3 -2 -1
a=tf.reshape(tf.constant(range(120)),(2,3,4,5))
b=-a
tf.concat([a,b],axis=-1)
<tf.Tensor: shape=(2, 3, 4, 10), dtype=int32, numpy=
array([[[[   0,    1,    2,    3,    4,    0,   -1,   -2,   -3,   -4],
         [   5,    6,    7,    8,    9,   -5,   -6,   -7,   -8,   -9],
         [  10,   11,   12,   13,   14,  -10,  -11,  -12,  -13,  -14],
         [  15,   16,   17,   18,   19,  -15,  -16,  -17,  -18,  -19]],

        [[  20,   21,   22,   23,   24,  -20,  -21,  -22,  -23,  -24],
         [  25,   26,   27,   28,   29,  -25,  -26,  -27,  -28,  -29],
         [  30,   31,   32,   33,   34,  -30,  -31,  -32,  -33,  -34],
         [  35,   36,   37,   38,   39,  -35,  -36,  -37,  -38,  -39]],

        [[  40,   41,   42,   43,   44,  -40,  -41,  -42,  -43,  -44],
         [  45,   46,   47,   48,   49,  -45,  -46,  -47,  -48,  -49],
         [  50,   51,   52,   53,   54,  -50,  -51,  -52,  -53,  -54],
         [  55,   56,   57,   58,   59,  -55,  -56,  -57,  -58,  -59]]],


       [[[  60,   61,   62,   63,   64,  -60,  -61,  -62,  -63,  -64],
         [  65,   66,   67,   68,   69,  -65,  -66,  -67,  -68,  -69],
         [  70,   71,   72,   73,   74,  -70,  -71,  -72,  -73,  -74],
         [  75,   76,   77,   78,   79,  -75,  -76,  -77,  -78,  -79]],

        [[  80,   81,   82,   83,   84,  -80,  -81,  -82,  -83,  -84],
         [  85,   86,   87,   88,   89,  -85,  -86,  -87,  -88,  -89],
         [  90,   91,   92,   93,   94,  -90,  -91,  -92,  -93,  -94],
         [  95,   96,   97,   98,   99,  -95,  -96,  -97,  -98,  -99]],

        [[ 100,  101,  102,  103,  104, -100, -101, -102, -103, -104],
         [ 105,  106,  107,  108,  109, -105, -106, -107, -108, -109],
         [ 110,  111,  112,  113,  114, -110, -111, -112, -113, -114],
         [ 115,  116,  117,  118,  119, -115, -116, -117, -118, -119]]]],
      dtype=int32)>

- (4,) concat (4,) => (8,)

  • 첫번째축? // axis=0
a=tf.constant([1,2,3,4])
b=-a 
a,b
(<tf.Tensor: shape=(4,), dtype=int32, numpy=array([1, 2, 3, 4], dtype=int32)>,
 <tf.Tensor: shape=(4,), dtype=int32, numpy=array([-1, -2, -3, -4], dtype=int32)>)
tf.concat([a,b],axis=0)
<tf.Tensor: shape=(8,), dtype=int32, numpy=array([ 1,  2,  3,  4, -1, -2, -3, -4], dtype=int32)>

- (4,) concat (4,) => (4,2)

  • 두번째축? // axis=1 ==> 이런거없다..
a=tf.constant([1,2,3,4])
b=-a 
a,b
(<tf.Tensor: shape=(4,), dtype=int32, numpy=array([1, 2, 3, 4], dtype=int32)>,
 <tf.Tensor: shape=(4,), dtype=int32, numpy=array([-1, -2, -3, -4], dtype=int32)>)
tf.concat([a,b],axis=1)
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
Input In [80], in <cell line: 1>()
----> 1 tf.concat([a,b],axis=1)

File ~/anaconda3/envs/py310/lib/python3.10/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    151 except Exception as e:
    152   filtered_tb = _process_traceback_frames(e.__traceback__)
--> 153   raise e.with_traceback(filtered_tb) from None
    154 finally:
    155   del filtered_tb

File ~/anaconda3/envs/py310/lib/python3.10/site-packages/tensorflow/python/framework/ops.py:7107, in raise_from_not_ok_status(e, name)
   7105 def raise_from_not_ok_status(e, name):
   7106   e.message += (" name: " + name if name is not None else "")
-> 7107   raise core._status_to_exception(e) from None

InvalidArgumentError: ConcatOp : Expected concatenating dimensions in the range [-1, 1), but got 1 [Op:ConcatV2] name: concat

tf.stack

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

tnp

- tf는 넘파이에 비하여 텐서만들기가 너무힘듬

np.diag([1,2,3]).reshape(-1)
array([1, 0, 0, 0, 2, 0, 0, 0, 3])
  • 넘파이는 이런식으로 np.diag()도 쓸수 있고 reshape을 메소드로 쓸 수도 있는데...

tnp 사용방법 (불만해결방법)

import tensorflow.experimental.numpy as tnp
tnp.experimental_enable_numpy_behavior()
type(tnp.array([1,2,3]))
tensorflow.python.framework.ops.EagerTensor

- int와 float을 더할 수 있음

tnp.array([1,2,3])+tnp.array([1.0,2.0,3.0])
<tf.Tensor: shape=(3,), dtype=float64, numpy=array([2., 4., 6.])>
tf.constant([1,2,3])+tf.constant([1.0,2.0,3.0])
<tf.Tensor: shape=(3,), dtype=float64, numpy=array([2., 4., 6.])>
tnp.array(1)+tnp.array([1.0,2.0,3.0])
<tf.Tensor: shape=(3,), dtype=float64, numpy=array([2., 3., 4.])>
tnp.diag([1,2,3])
<tf.Tensor: shape=(3, 3), dtype=int64, numpy=
array([[1, 0, 0],
       [0, 2, 0],
       [0, 0, 3]])>
a=tnp.diag([1,2,3])
type(a)
tensorflow.python.framework.ops.EagerTensor
a=tf.constant([1,2,3])
a.reshape(3,1)
<tf.Tensor: shape=(3, 1), dtype=int32, numpy=
array([[1],
       [2],
       [3]], dtype=int32)>

선언고급

np.random.randn(5)
array([0.67533519, 0.18494521, 0.76946432, 0.94461951, 1.15058192])
tnp.random.randn(5) # 넘파이가 되면 나도 된다.
<tf.Tensor: shape=(5,), dtype=float64, numpy=array([-0.37112581, -0.31535817, -0.92963552, -0.68741888, -0.54859424])>

타입

type(tnp.random.randn(5))
tensorflow.python.framework.ops.EagerTensor

tf.contant로 만들어도 마치 넘파이인듯 쓰는 기능들

- 묵시적형변환이 가능

tf.constant([1,1])+tf.constant([2.2,3.3])
<tf.Tensor: shape=(2,), dtype=float64, numpy=array([3.20000005, 4.29999995])>

- 메소드를 쓸수 있음.

a= tnp.array([[1,2,3,4]])
a.T
<tf.Tensor: shape=(4, 1), dtype=int64, numpy=
array([[1],
       [2],
       [3],
       [4]])>

그렇지만 np.array는 아님

- 원소를 할당하는것은 불가능

a=tf.constant([1,2,3])
a
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 3], dtype=int32)>
a[0]=11
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [101], in <cell line: 1>()
----> 1 a[0]=11

TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment