njs03332 / ml_study

3 stars 0 forks source link

2023/02/09 ~ 2023/02/14 #58

Open danbi5228 opened 1 year ago

danbi5228 commented 1 year ago

2023.02.14 pm10:30

1: 12.2.1 2: 12.2.2 - 12.2.3 3: 12.2.4 - 12.2.5

image
njs03332 commented 1 year ago

12.2 넘파이처럼 텐서플로 사용하기

12.2.1 텐서와 연산

# 텐서 만들기 
tf.constant([[1., 2., 3.], [4., 5., 6.]])
tf.constant(42)

# 크기 & 데이터 타입 확인 
t.shape
t.dtype

# 인덱스 참조
t[:, 1:]
### 결과: [[2., 3.], [5., 6.]]

# 기존의 배열을 ...으로 적고 추가하고 싶은 위치에 tf.newaxis 적기 -> size 변경
t[..., 1, tf.newaxis]
### 결과: [[2.], [5.]]

# 모든 종류의 텐서 연산 가능
t + 10
### 결과: [[11., 12., 13.], [14., 15., 16.]]
tf.square(t)
### 결과: [[1., 4., 9.], [16., 25., 36.]]
t @ tf.transpose(t)
### 결과: [[14., 32.], [32., 77.]]
danbi5228 commented 1 year ago

12.2.4 변수

tf.Tensor와 tf.Variable은 비슷하게 동작함

v = tf.Variable([[1., 2., 3.], [4., 5., 6.]])

tf.Tensor와 달리 값 수정이 가능

assign(): 변수값 변경

원소의 assign() / scatter_update() / scatter_nd_update(): 개별 원소(또는 슬라이드) 수정

v.assign(2 * v) # -> [[2., 4., 6.], [8., 10., 12.]] v[0: 1].assign(42) # -> [[2., 42., 6.], [8., 10., 12.]] v[:, 2].assign([0., 1.]) # -> [[2., 42., 0.], [8., 10., 1.]] v.scatter_nd_update(indices=[[0, 0], [1, 2]], updates=[100., 200.,]) # -> [[100., 42., 0.], [8., 10., 200.]]


### 12.2.5 다른 데이터 구조
- 자세한 내용은 주피터 노트북의 '텐서와 연산'과 부록 F 참고
- 희소 텐서 sparks tensor
  - tf.SparseTensor
  - 대부분 0으로 채워진 텐서를 효율적으로 나타냄. tf.sparse 패키지에서 연산 제공
- 텐서 배열 tensor array
  - tf.TensorArray
  - 텐서의 리스트. 기본적으로는 고정된 길이를 가지지만 동적으로 바꿀 수 있음
- 래그드 탠서 ragged tensor
  - tf.RaggedTensor
  - 리스트의 리스트를 나타냄
  - 텐서에 포함된 값은 동일한 데이터 타입을 가져야 하지만 리스트의 길이는 다를 수 있음. tf.ragged 패키지에서 연산 제공
- 문자열 텐서 string tensor
  - tf.string 타입의 텐서. 유니코드가 아니라 바이트 문자열을 나타냄
  - tf.strings 패키지에서 유니코드 문자열과 바이트 문자열 텐서 사이의 변환을 위한 연산 제공
- 집합 set
  - 일반적인 텐서(또는 희소 텐서)로 나타냄. tf.sets 패키지에서 집합 연산 제공
- 큐 queue
  - 단계별로 텐서를 저장
  - tf.queue 패키지에서 간단한 fifo queue 외 priority queue, random shuffle queue, padding fifo queue 등 여러 큐 제공
givitallugot commented 1 year ago

12.2.2 텐서와 넘파이

a = np.array([2,4,5]) # numpy array
t = tf.constant([[1,2,3], [4,5,6]]) # tensor

tf.constant(a) # numpy array to tensor
tf.square(a) # ok [4, 16, 25]

t.numpy() # tensor to numpy array
np.squre(a) # ok [[1,4,9], [16,25,36]]

12.2.3 타입 변환

t2 = tf.constant(40., dtype=tf.float64) tf.constant(2.0) + tf.cast(t2, tf.float32) # 연산됨, 42.0