tensor들을 이용한 연산 (유사 numpy)
텐서의 기본 계산은 element-wise하게 계산된다.
import tensorflow as tf
import numpy as np
# 텐서플로우에서의 합
# 벡터의 합과 같이 계산된다.
t1 = tf.constant([1, 2, 3])
t2 = tf.constant([10, 20, 30])
print(t1 + t2) # 각각 element끼리 더한다.
print(t1 - t2)
print(t1 * t2) # 예외 조금 다름
print(t1 / t2)
print(t1 % t2)
print(t1 // t2)
브로드캐스팅을 이용하면 for문을 대체할 수 있음
# %%
# 브로드캐스팅
t1 = tf.random.normal(shape=(3, 4), mean=0, stddev=5)
t2 = tf.random.normal(shape=(3, 4), mean=0, stddev=5)
# cast는 데이터 타입 변경해준다.
# 현재 normal을 사용하여 float32 -> int16으로 변경
t1 = tf.cast(t1, dtype=tf.int16)
t2 = tf.cast(t2, dtype=tf.int16)
print(t1.numpy())
print(t2.numpy())
print(t1 + t2) # 고차원의 텐서도 element끼리 더해진다.
# 형태가 다를 경우1
t1 = tf.random.normal(shape=(3, 4), mean=0, stddev=5)
t2 = tf.random.normal(shape=(1, 4), mean=0, stddev=5)
t1 = tf.cast(t1, dtype=tf.int16)
t2 = tf.cast(t2, dtype=tf.int16)
# (3 x 4)와 (1 x 4)의 계산
# 형태가 맞지 않아도 계산이 가능하도록 확장된다.
t3 = t1 + t2 # (1 x 4)이 (4 x 4)의 형태로 늘어나서 계산된다.
print(t1.numpy(), '\n')
print(t2.numpy(), '\n')
print(t3.numpy(), '\n')
# 형태가 다를 경우2
t1 = tf.random.normal(shape=(3, 1), mean=0, stddev=5)
t2 = tf.random.normal(shape=(1, 4), mean=0, stddev=5)
t1 = tf.cast(t1, dtype=tf.int16)
t2 = tf.cast(t2, dtype=tf.int16)
# (3 x 1)와 (1 x 4)의 계산
# 형태가 맞지 않아도 계산이 가능하도록 확장된다.
t3 = t1 + t2 # 각각 (3 x 4)의 형태로 늘어나서 계산된다.
print(t1.numpy(), '\n')
print(t2.numpy(), '\n')
print(t3.numpy(), '\n')
reduce family
# %%
# 데이터셋에서 데이터 추출
# 행(row) 으로 뽑으면 data-wise를 꺼낸다.
# 열(column) 으로 뽑으면 attribute을 꺼낸다.
# reduce_sum()
t1 = tf.random.normal(shape=(3, 4), mean=0, stddev=5)
t1 = tf.cast(t1, dtype=tf.int16)
t2 = tf.reduce_sum(t1)
print(t1.numpy())
print(t2.numpy())
# reduce_sum( argument추가 )
# axis
t2 = tf.reduce_sum(t1.axis=0)
print(t1.numpy(), '\n')
print(t2.numpy(), '\n')
# 높은 차원에서의 axis
t1 = tf.random.normal(shape=(128, 128, 3), mean=0, stddev=5)
t1 = tf.cast(t1, dtype=tf.int16)
t2 = tf.reduce_sum(t1.axis=2) # 각 픽셀들끼리의 합을 의미한다. channel-wise
print(t1.numpy(), '\n')
print(t2.numpy(), '\n')
# reduce_sum()
# reduce_prod()
# reduce_min
# reduce_max
# reduce_mean
# reduce_std
# reduce_variance
# reduce_all
# reduce_any
axis = 0 의 의미는 (3 x 4)에서의 3이 axis=0, 4가 axis=1이다.
axis = 0 을 기준으로 해당 축을 없애버리면서 계산한다 라고 생각한다.
(3 x 4) 을 하나의 스칼라들로 (1 x 4) 또는 (4, ) 의 형태로 만드는 것이다.
axis 을 지정해주는 것은 해당 축의 데이터 정보를 없애면서 어떤 연산을 해라를 의미한다.
reduce_sum외에도 reduce_maen의 경우 channel-wise에서의 평균으로 계산할 수 있다.