본문 바로가기

인공지능/Deep Learning28

[Deep Learning] TensorFlow 레이블 인코딩된 값을 원핫 인코딩으로 바꾸기 📝딥러닝 텐서플로우 넘파이의 레이블 인코딩된 값을 원핫 인코딩으로 바꾸는 방법 바꾸는 방법은 텐서플로우에서 제공한다 import tensorflow as tf # 학습용과 테스트용 둘다 바꿔준다 (num_classes= 는 아웃풋 레이어 갯수) y_train = tf.keras.utils.to_categorical(y_train, num_classes= 10) y_test = tf.keras.utils.to_categorical(y_test, num_classes= 10) # 이렇게도 가능 from keras.utils import to_categorical y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10) 모델링할때 원핫.. 2022. 12. 29.
[Deep Learning] TensorFlow 모델 저장 / 불러오기 📝딥러닝 텐서플로우 모델 저장하고 불러오는 방법 네트워크와 웨이트를 통으로 저장하고 불러오기 # 폴더구조로 저장 model.save('fashion_mnist_model') # 저장된 인공지능 불러오기 model2 = tf.keras.models.load_model('fashion_mnist_model') # 저장된 경로와 파일명을 입력 # 파일 하나로 저장 model.save('fashion_mnist_model.h5') # 저장된 인공지능 불러오기 model3 = tf.keras.models.load_model('fashion_mnist_model.h5') json 파일로 네트워크만 저장하고 불러오기 ( 현재 to_yaml()은 지원되지 않는다 ) ※ 저장한 네트워크로부터 모델을 만들때 주의할점 : .. 2022. 12. 29.
[Deep Learning] Dropout 📝딥러닝 드랍아웃 드랍아웃이란 뉴런에 연결된 선을 일부분을 잘라서 학습이 잘 되도록 하는 방법이다 from keras.layers import Dropout def build_model() : model = Sequential() model.add( Dense( units= 128, activation= 'relu', input_shape=(784, ) ) ) model.add( Dropout(0.2) ) # rate 값 지정 랜덤으로 이 구간의 선을 20% 없애라는 뜻 model.add( Dense( units= 64, activation= 'relu') ) model.add( Dense( units=10, activation= 'softmax' ) ) model.compile( optimizer= '.. 2022. 12. 29.
[Deep Learning] DNN TensorFlow 이미지 분류하는 딥러닝 해보기 📝딥러닝 DNN 텐서플로우 이미지를 분류하는 딥러닝 해보기 TensorFlow keras datasets API에 들어있는 Fashion MNIST데이터를 가져온다 mnist = tf.keras.datasets.fashion_mnist 트레이닝셋과 테스트셋을 가져온다 ※ 텐서플로우에서 사진을 넘파이로 변환해둔 데이터 X_train.shape의 결과 값은 (60000, 28, 28) = 28행 28열 6만장(갯수)이다 (X_train, y_train), (X_test, y_test) = mnist.load_data() 해당 데이터에 들어있는 두번째 사진의 이미지를 확인해보기 위해 pyplot의 imshow() 사용 plt.imshow(X_train[1], cmap='gray') plt.show() 학습이 .. 2022. 12. 29.
[Deep Learning] epochs 횟수 조정 📝딥러닝 epochs 횟수 조정 epoch 횟수를 너무 많이 지정하면 학습한 데이터만 잘 맞추게 되는 오버피팅(Overfiting)이 된다 또 너무 적게 지정하면 학습이 덜 되어 언더피팅(Underfiting)이 된다 # 학습데이터 차트보기 plt.plot(epoch_history.history['loss']) plt.plot(epoch_history.history['val_loss']) plt.legend(['Train Loss', ' Validation Loss']) plt.show() # 밸리데이션데이터 차트보기 plt.plot(epoch_history.history['accuracy']) plt.plot(epoch_history.history['val_accuracy']) plt.legend(['.. 2022. 12. 29.
[Deep Learning] 분류 문제 Loss 셋팅 📝딥러닝 분류 문제 Loss 셋팅 2개로 분류하는 문제에서의 로스펑션은 bibary_crossentropy를 사용하고 3개 이상으로 분류하는 문제에는 두가지 방법이 있는데 y의 값을 확인하여 선택한다 첫번째 방법은 y값이 레이블 인코딩으로 되어있으면 sparse_categorical_crossentropy 두번째 방법은 y값이 원핫인코딩으로 되어있으면 categorical_crossentropy def build_model() : model = Sequential() model.add( Flatten() ) model.add( Dense( units= 128, activation= 'relu') ) model.add( Dense( units= 64, activation= 'relu') ) model.ad.. 2022. 12. 28.
[Deep Learning] activation Softmax 📝딥러닝 여러개의 값 중에서 가장 큰 값을 선택하는 엑티베이션 소프트맥스 Softmax 여러개의 값 중에서 가장 큰 값을 선택 [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05] 여기서 가장 큰 값을 1로 만들고 나머지는 0으로 만들어준다. [0, 0, 0, 0, 1, 0, 0, 0, 0] 아웃풋 레이어 activation= 'softmax' def build_model() : model = Sequential() model.add( Flatten() ) model.add( Dense( units= 128, activation= 'relu') ) model.add( Dense( units= 64, activation= 'relu') ) # 아웃풋 레이어에 activa.. 2022. 12. 28.
[Deep Learning] Flatten Library 📝딥러닝 플래튼 라이브러리 이미지의 가로 세로를 전부 일렬로 만들어 인풋레이어 지정 # 함수로 만들때 인풋레이어에 사용해준다 def build_model() : model = Sequential() model.add( Flatten() ) model.add( Dense( units= 128, activation= 'relu') ) model.add( Dense( units= 64, activation= 'relu') ) model.add( Dense( units=10, activation= 'softmax' ) ) model.compile( optimizer= 'adam', loss= 'sparse_categorical_crossentropy', metrics= [ 'accuracy' ]) return .. 2022. 12. 28.
[Deep Learning] TensorFlow EarlyStopping, Callback 📝딥러닝 텐서플로우 EarlyStopping, Callback callback 이란, 내가 만든 함수를 프레임워크가 실행시켜주는 것 EarlyStopping을 사용하면 지정된 에포크 횟수 동안 성능 향상이 없으면 자동으로 훈련이 멈춘다 # patience를 10으로 설정하면 10번의 에포크동안 성능향상이 없으면 멈추라는 뜻 early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience= 10) # 학습할때 callbacks을 입력 epoch_history = model.fit(X_train, y_train, epochs= 100000, validation_split= 0.2, callbacks= [ early_stop ]) accur.. 2022. 12. 28.
[Deep Learning] 학습중에 평가하기 validation 📝딥러닝 밸리데이션 val = validation 밸리데이션이란, 에포크가 한번 끝날때 마다 학습에 사용하지 않은 데이터로 시험을 보는 것을 말한다 테스트는 인공지능이 완전히 학습이 다 끝난 상태에서 평가하는 것이고 밸리데이션은 학습중에(에포크 끝날때마다) 평가하는 것을 말한다 validation_split : 학습할때 학습 데이터의 n% 는 테스트용으로 쓰겠다고 지정 # 인공지능 함수로 생성 def build_model() : model = Sequential() model.add( Dense( units= 64, activation= 'relu', input_shape= (9,) ) ) model.add( Dense( units= 64, activation= 'relu') ) model.add( De.. 2022. 12. 28.