딥러닝 논문 구현 관련 기초 코딩 지식 정리 1

프레임워크는 텐서플로우를 기반으로 하였습니다. 제가 강의를 듣고 필요한 내용을 정리해본 것입니다. 👩‍💻

데이터 로드

기존의 인덱스는 첫번째 열로 자동으로 삽입. 이 때 drop=True 옵션을 주면 기존 인덱스를 버리고 재배열 , frac 반환해야하는 전체 인스턴스의 비율

df=df.sample(frac=1).reset_index(drop=True)

데이터 특성 표준화하기

⛳️ 특성의 평균이 0, 표준편차가 1이 되도록 반환 = ‘표준화’

fit_transform : 각 features 의 평균과 표준편차를 계산한 후, 그에 맞게 표준화

transform : 사전에 fit_transform 을 통해서 구해진 모수에 맞게 표준화, 성능 평가는 test 데이터 표준화 작업 시에 train 데이터(잘 이해한 데이터)로 학습된 모델이 test 데이터(새로운 데이터)에 얼마만큼의 성능을 보이는지 확인하는 것이기 때문에 사용

from sklearn import preprocessing
scaler=preprocessing.StandardScaler()
standardized=scaler.fit_transform(x)

잘 표준화되었는지 확인도 가능하다 :)

print(standardized.std())

데이터 분할

features 데이터와 라벨값을 모두 넣어준 경우 총 네 가지 분할된 값 반환 (x_train, x_test, y_train, y_test)

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)

설계한 모델 구성 체크하기

from tensorflow.keras.utils import plot_model
plot_model(model)

스크린샷 2021-02-04 오후 12 31 28

output 이 2개일 시에는 각각의 loss 를 딕셔너리 형태로 지정

model.compile(optimizer=optimizer,loss={‘y1_output’:’mse’,’y2_output’:’mse’})

matplotlib 로 모델 성능 시각화하기 + 약간의 numpy

plt.plot(‘x’,’y’,data=data_dict)

plt.xlim([xmin,xmax])

plt.ylim([ymin,ymax])

plt.axis([xmin,xmax,ymin,ymax])

plt.scatter(x,y) => sns scatterplot 으로도 가능 !

plt.xticks([0,1,2]), plt.yticks(np.arange(1,6)) 눈금 표시

만약 디테일하게 조정하고 싶으면 rc파라미터 딕셔너리 값 변경해주기 (rc=’run command’) ex. plt.rcParams[‘font.size’]=12

np.swapaxes(arr,axis1,aixs2) ; 배열의 두 축을 상호교환해준다.

Custom Loss 사용하기

custom loss 정의에 유용한 텐서플로우 문법

tf.where(is_small_error,small_error_loss,big_error_loss)
#걸어준 is_small_error 조건에 True 면 small_error_loss 반환, false 면 big_error_loss 반환
#hubber loss 구현할 때 유용

model.compile(loss=my_hubber_loss,optimizer=optimizer)

이런 식으로 custom loss 사용 가능

텐서플로우 functional api 를 사용하는 이유

매우 유연하기 때문에 시아미스 네트워크 등을 구성할 수 있다.

input_a = Input(shape=(28,28,), name="left_input")
vect_output_a = base_network(input_a)

이런 식으로 미리 정해준 모델에 새로 정해준 모델 레이어를 넣어줄 수 있기 때문 !

lambda 레이어 사용 (custom layer1)

람다레이어 사용 시 weights 를 정의해주지는 않는다. 고로, 단순한 custom 활성화 함수 등을 적용해야할 때 람다 레이어를 사용한다.

model = tf.keras.models.Sequential([

​ tf.keras.layers.Flatten(input_shape=(28, 28)),

​ tf.keras.layers.Dense(128),

tf.keras.layers.Lambda(my_relu),

​ tf.keras.layers.Dense(10, activation=’softmax’)

])

이런 식으로 미리 정의한 함수를 layer 로 사용 가능 !

Custom class 레이어 사용 (custom layer2)

init : 케라스 layer 을 상속받고 기본 속성을 정의하는 곳

build : 훈련 가능한 weights 을 정의하는 곳. shape 도 여기서 잡아줄 수가 있다.

call : custom 알고리즘을 정의하는 곳

siamese network

m : margin 같은 클래스에 속하는 데이터는 최대한 멀어도 margin 거리만큼만 차이가 나야 한다. 즉, 같은 클래스에 속하지 않은 데이터는 아무리 가까워도 margin 값 보다는 멀어야한다. 스크린샷 2021-02-04 오후 1 25 04

Losses explained: Contrastive Loss