▷ 오늘 학습 계획: 텐서플로 강의
list, tuple, array → tensor
tf.constant()
Numpy array 추출
list_ten.numpy()
차원의 수
# Number of array dimensions list_ten.ndim
data type 지정
# 미리 지정하기 tensor = tf.constant([1,2,3], dtype=float64) # 이미 만들어진 tensor의 type 변경: tf.cast tf.cast(tensor, dtype=tf.int32)
- 참고
double precision: 64bits
single precision: 32bits
half precision: 16bits특정 값의 Tensor 생성
- tf.ones
- tf.zeros
- tf.range
# 첫항이 1이고 공비가 2인 등비수열 def geometric_sequence(n): r = tf.range(n, dtype="int32") s = tf.ones(n, dtype=tf.int32) * 2 return s**r
Random Value(난수)
- Noise를 재현하거나 test할 때 많이 사용
- 상수 형태로 반환된다(tf.tensor)
- tf.random에 구현되어 있다.
tf.random.normal, tf.random.uniform 등shape = (3,3) tf.random.normal(shape) tf.random.uniform(shape)
Random seed 관리
- random value로 보통 가중치 초기화
- 재현성 유지를 위해 항상 random seed 고정해두기
tf.random.set_seed({seed_number})
- 미지수, 가중치를 정의할 때 사용
- 직접 사용할 일이 많지는 않다.
- 변수 정의는 변수 생성 + 초기화
tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]]) tf.Variable(tensor) # constant와 같이 기본 속성값(shape, dtype 등)이 들어있다. tensor.shape tensor.dtype tensor.numpy tensor.numpy() # numpy 객체 반환
- 기존 텐서의 메모리를 재사용하여 텐서를 재할당 할 수 있다.
- 기존 메모리의 크기와 다르면 할당 할 수 없다.
a = tf.Variable([2.0, 3.0]) a.assign([1,2]) # a와 같은 형태로 할당
기본 연산
- tf.add
- tf.subtract
- tf.multiply
- tf.divide
- tf.pow
- tf.negative
여러가지 연산
- tf.abs: 절댓값
- tf.sign: 부호
- tf.round
- tf.ceil
- tf.floor
- tf.squre: 제곱
- tf.sqrt: 제곱근
- tf.maximum
- tf.minimum
- tf.cumsum
- tf.cumprod: 누적곱
차원 축소 연산
- tf.reduce_mean
- tf.reduce_max
- tf.reduce_min
- tf.reduce_prod: 설정한 축의 요소를 모두 곱한 값
- tf.reduce_sum
tf.reduce_sum(a, axis=0, keepdims=True) #차원을 축소하지 않을 때 True
행렬과 관련된 연산
- tf.matmul: 내적
- tf.linalg.inv: 역행렬
크기 및 차원 바꾸기
- tf.reshape: 벡터 행렬의 크기 변환
- tf.transpose: 전치 연산
- tf.expand_dims: 지정된 축으로 차원 추가
- tf.squeeze: 벡터로 차원 축소(원소의 개수가 1개인 차원을 줄여준다.)
텐서를 나누거나 두 개 이상의 텐서 합치기
- tf.slice: 특정 부분 추출
- tf.split: 분할
- tf.concat: 합치기
- tf.tile: 복제-붙이기
- tf.stack: 합성(concat과 다르게 차원을 하나 더 만들어서 고차원 텐서 생성)
- tf.unstack: 분리
tf.GradientTape
context 안에서 실행된 모든 연산을 tape에 기록,
후진 방식 자동 미분(reverse mode differentiation)을 사용해 tape에 기록된 연산의 gradient 계산
- tf.Variable만 기록
- A variable + tensor는 tensor로 반환
- trainable 조건으로 미분 기록을 제어
기록되고 있는 variable 확인
tape.watched_variables()
Scalar를 Scalar로 미분
x = tf.Variable(3.0) # x는 constant가 아니라 variable! with tf.GradientTape() as tape: y = x**2
# dy = 2x*dx dy_dx = tape.gradient(y,x) # y를 x로 미분 dy_dx.numpy() # 6.0
Scalar를 Vector로 미분
for epoch in range(100): with tf.GradientTape() as tape: y_hat = X * w + b loss = tf.reduce_mean(tf.square(y - y_hat)) dw, db = tape.gradient(loss, [w, b]) w.assign_sub(lr * dw) b.assign_sub(lr * dw)
Conv2D
- filters: layer에서 사용할 Filter(weights)의 갯수
- kernel_size: Filter(weights)의 사이즈
- strides: 몇 개의 pixel을 skip 하면서 훑어지나갈 것인지 (출력 피쳐맵의 사이즈에 영향을 줌)
- padding: zero padding을 만들 것인지. VALID는 Padding이 없고, SAME은 Padding이 있음 (출력 피쳐맵의 사이즈에 영향을 줌)
- activation: Activation Function을 지정
MaxPool2D
- pool_size: Pooling window 크기
- strides: 몇 개의 pixel을 skip 하면서 훑어지나갈 것인지
- padding: zero padding을 만들 것인지
Dense
- units : 노드 갯수
- activation : 활성화 함수
- use_bias : bias 를 사용 할 것인지
- kernel_initializer : 최초 가중치를 어떻게 세팅 할 것인지
- bias_initializer : 최초 bias를 어떻게 세팅 할 것인지
- save 함수
model.save('checkpoints/model_weight.h5') model = tf.keras.models.load_model('checkpoints/model_weight.h5')
- save_weights 함수
model.save_weights('checkpoints/model_weight.h5') model = build_resnet((32, 32, 3)) model.load_weights('checkpoints/model_weight.h5')
- callbacks 함수 사용
save_path = 'checkpoints/{epoch}-{val_loss:.2f}.h5' tf.keras.callbacks.ModelCheckpoint(save_path, monitor='val_accuracy', save_best_only) # 이후에 compile, fit(callbacks 포함) 과정 거쳐야 함
- pb(protoBuffer) 형식으로 저장
save_path에 'h5'만 없애기
import os from glob import glob os.listdir('./') #로컬 환경에 저장되어 있는 파일 목록 glob('./*.png') #현재 폴더에 png 파일 전체
def read_image(path): raw = tf.io.read_file(path) img = tf.io.decode_image(raw) return img
미리 이미지 데이터를 모두 불러오는게 아니라 그 때 그 때 처리
dataset = tf.data.Dataset.from_tensor_slices(img) AUTOTUNE = tf.data.experimental.AUTOTUNE dataset = dataset.map(read_image, num_parallel_calls=AUTOTUNE) dataset = dataset.batch(32) #원하는 배치 사이즈만큼 dataset = dataset.prefetch(AUTOTUNE) #병렬적으로 다음 배치를 읽어서 속도↑ dataset = dataset.shuffle(buffer_size=100) dataset = dataset.repeat() #epoch 숫자를 넣는 경우도 있다. next(iter(dataset))
데이터를 불러오는 동시에 여러가지 전처리 구현
from tensorflow.keras.preprocessing.image import ImageDataGenerator datagen = ImageDataGenerator( rotation_range = 20, width_shift_range = 0.2, height_shift_range = 0.2, horizontal_flip = True )
- flow: 데이터를 모두 메모리에 불러두고 사용
result = next(iter(datagen.flow(train_x, train_y)))
- flow_from_directory
- flow_from_dataframe
▷ 내일 학습 계획: 파이토치 강의
[이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.]