가짜얼굴 (This person does not exist) Start

BioinformaticsAndMe







This person does not exist


: thispersondoesnotexist 웹사이트를 실행하면 처음보는 남녀노소 얼굴을 보게됨

: 하지만 보게되는 사진의 인물은 실존하지 않으며, 인공지능으로 합성된 가짜 얼굴임

: Nvidia의 소프트웨어 개발자가 오픈소스로 공개한 Generative adversarial network(GAN) 기술에 기반

*Generative adversarial network(GAN) - 대립 관계의 두 AI를 경쟁시켜 완성도를 높이는 적대적 생성모델

: 해당 사이트를 새로고침 할때마다, 새로운 얼굴 이미지를 생성함




#간혹, 버그로 보이는 얼굴도 볼 수 있음







#Reference

1) https://thispersondoesnotexist.com/

2) https://en.wikipedia.org/wiki/StyleGAN

3) https://news.joins.com/article/23393808

4) https://editoy.com/posts/2960





가짜얼굴 (This person does not exist) End

BioinformaticsAndMe

[TensorFlow] 심장질환 예측 Start

BioinformaticsAndMe









[TensorFlow] 심장질환 예측


: TensorFlow 2.0 에서 만들어진 DNN(심층신경망) 모델에 근거하여, 환자데이터로부터 심장병 유무를 예측

: 심장병은 사망률이 높은 질환으로 정확한 예측을 위해선, 훨씬 더 복잡한 데이터와 상호관계 분석이 필요

*아래 예제는 간단한 파일럿테스트

: 텐서플로우를 통한 심장질환 예측은 아래 순서로 진행

1) 데이터 준비

2) 환자데이터 살펴보기

3) 데이터 전처리

4) Neural Network 모델 만들기

5) 모델 Training

6) 심장질환 예측




1. 데이터 준비


: 분석데이터 다운로드 → https://www.kaggle.com/ronitf/heart-disease-uci (kaggle 가입 필요)

*heat.csv - 303명 환자기록과 14가지 속성(변수)

# 분석에 필요한 라이브러리 로딩 !pip install tensorflow-gpu==2.0.0-alpha0 import numpy as np import tensorflow as tf from tensorflow import keras import pandas as pd import seaborn as sns from pylab import rcParams import matplotlib.pyplot as plt from matplotlib import rc from google.colab import drive from sklearn.model_selection import train_test_split %matplotlib inline sns.set(style='whitegrid', palette='muted', font_scale=1.5) rcParams['figure.figsize'] = 14, 8 RANDOM_SEED = 42 np.random.seed(RANDOM_SEED)

# 구글드라이브 마운트 및 파일경로 지정

drive.mount("/content/drive")

heart_csv_path = "/content/drive/My Drive/Colab Notebooks/tensorflow-2/data/heart.csv"

# 데이터 로딩 후, 출력

data = pd.read_csv(heart_csv_path)

data.describe()

#age - 나이 #sex - (1 = 남성; 0 = 여성) #cp - 가슴 통증 유형(0, 1, 2, 3, 4) #trestbps - 안정 혈압(병원 입원시 mm Hg) #chol - 혈청 콜레스테롤(mg/dl) #fbs - (공복 혈당 > 120 mg/dl)(1 = true; 0 = false) #restecg - 안정 심전도 결과(0, 1, 2) #thalach - 최대 심박동수 #exang - 협심증 유발 운동(1 = yes; 0 = no) #oldpeak - 비교적 안정되기까지 운동으로 유발되는 ST depression #slope - 최대 운동 ST segment의 기울기 #ca - 형광 투시된 주요 혈관의 수(0-3) #thal - (3 = 보통; 6 = 해결된 결함; 7 = 해결가능한 결함) #target - 심장병 진단(1 = true; 0 = false)

# 데이터 구조 확인

data.shape

(303, 14)

# 데이터 변수 확인

data.columns

Index(['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal', 'target'], dtype='object')




2. 환자데이터 살펴보기


: 환자데이터를 직접 시각화하여, 데이터의 특징을 직관적으로 이해

# 303명의 환자에서 심장병 유무를 확인

f = sns.countplot(x='target', data=data) f.set_title("Heart disease presence distribution") f.set_xticklabels(['No Heart disease', 'Heart Disease']) plt.xlabel("")

# 303명의 환자에서 심장병 유무를 남녀로 나누어 확인

f = sns.countplot(x='target', data=data, hue='sex') plt.legend(['Female', 'Male']) f.set_title("Heart disease presence by gender") f.set_xticklabels(['No Heart disease', 'Heart Disease']) plt.xlabel("");

# 변수(Feature) 사이에서의 상관관계 정도를 Heatmap으로 구현

# +1에 가까울수록, positive correlation

# -1에 가까울수록, negative correlation

heat_map = sns.heatmap(data.corr(method='pearson'), annot=True, fmt='.2f', linewidths=2) heat_map.set_xticklabels(heat_map.get_xticklabels(), rotation=45);




3. 데이터 전처리


: 보유한 데이터는 범주형/숫자형의 혼합 형태로, 원활한 텐서플로우 모델링을 위해 데이터 전처리가 필요함

: 머신러닝 모델에서는 범주형/숫자형을 떠나 모든 Feature들이 숫자로 처리됨

# feater column은 'raw 데이터'와 '모델링하는 데이터'를 연결짓는 브릿지 역할

feature_columns = [] # 수치형 열(Numeric col)은 실수값을 변형시키지 않고 그대로 전달

for header in ['age', 'trestbps', 'chol', 'thalach', 'oldpeak', 'ca']: feature_columns.append(tf.feature_column.numeric_column(header)) # 버킷형 열(Bucketized column)은 수치값을 구간을 나누어 범주형으로 변환 age = tf.feature_column.numeric_column("age") age_buckets = tf.feature_column.bucketized_column(age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]) feature_columns.append(age_buckets) # 범주형 열(Categorical column)은 특정 문자열을 수치형으로 매핑하여 전달 data["thal"] = data["thal"].apply(str) thal = tf.feature_column.categorical_column_with_vocabulary_list( 'thal', ['3', '6', '7']) thal_one_hot = tf.feature_column.indicator_column(thal) feature_columns.append(thal_one_hot) data["sex"] = data["sex"].apply(str) sex = tf.feature_column.categorical_column_with_vocabulary_list( 'sex', ['0', '1']) sex_one_hot = tf.feature_column.indicator_column(sex) feature_columns.append(sex_one_hot) data["cp"] = data["cp"].apply(str) cp = tf.feature_column.categorical_column_with_vocabulary_list( 'cp', ['0', '1', '2', '3']) cp_one_hot = tf.feature_column.indicator_column(cp) feature_columns.append(cp_one_hot) data["slope"] = data["slope"].apply(str) slope = tf.feature_column.categorical_column_with_vocabulary_list( 'slope', ['0', '1', '2']) slope_one_hot = tf.feature_column.indicator_column(slope) feature_columns.append(slope_one_hot) # 임베딩 열(Embedding column)은 범주형 열에 가능한 값이 많을 때 사용 thal_embedding = tf.feature_column.embedding_column(thal, dimension=8) feature_columns.append(thal_embedding) # 교차특성 열(Crossed column)은 여러 특성을 연결하여 하나의 특성으로 만듦

age_thal_crossed = tf.feature_column.crossed_column([age_buckets, thal], hash_bucket_size=1000) age_thal_crossed = tf.feature_column.indicator_column(age_thal_crossed) feature_columns.append(age_thal_crossed) cp_slope_crossed = tf.feature_column.crossed_column([cp, slope], hash_bucket_size=1000) cp_slope_crossed = tf.feature_column.indicator_column(cp_slope_crossed) feature_columns.append(cp_slope_crossed)

# Pandas 데이터프레임 → Tensorlfow 데이터셋

def create_dataset(dataframe, batch_size=32): dataframe = dataframe.copy() labels = dataframe.pop('target') return tf.data.Dataset.from_tensor_slices((dict(dataframe), labels)) \ .shuffle(buffer_size=len(dataframe)) \ .batch(batch_size)

# 전체데이터를 Training set과 Test set으로 나누기

train, test = train_test_split(data, test_size=0.2, random_state=RANDOM_SEED)

train_ds = create_dataset(train) test_ds = create_dataset(test)




4. Neural Network 모델 만들기


# 오버피팅을 줄이기 위해, Dense layer 사이에 Dropout layer 배치

model = tf.keras.models.Sequential([ tf.keras.layers.DenseFeatures(feature_columns=feature_columns), tf.keras.layers.Dense(units=128, activation='relu'), tf.keras.layers.Dropout(rate=0.2), tf.keras.layers.Dense(units=128, activation='relu'), tf.keras.layers.Dense(units=1, activation='sigmoid') ])




5. 모델 Training


# 모델 컴파일 후, 학습되면서 생기는 손실과 정확도 지표 출력

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) history = model.fit(train_ds, validation_data=test_ds, epochs=100, use_multiprocessing=True)

# model.evaludate 함수로 Test set 정확도 평가 model.evaluate(test_ds)

2/2 [==============================] - 0s 23ms/step - loss: 0.3431 - accuracy: 0.8852 [0.3430721387267113, 0.8852459]

# 모델의 정확도 시각화 plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.ylim((0, 1)) plt.legend(['train', 'test'], loc='upper left');

# 모델의 손실 시각화 plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show()




6. 심장질환 예측


# 만들어진 DNN 모델로 심장질환을 예측

# 앞서 얻은 accuracy에 상관없이, precision/recall/f1-score가 높지 않음을 확인

*precision = 정밀도

*recall = 재현율

*f1-score = 정밀도와 재현율의 조화 평균

from sklearn.metrics import classification_report, confusion_matrix

predictions = model.predict(test_ds)

bin_predictions = tf.round(predictions).numpy().flatten()

print(classification_report(y_test.values, bin_predictions))

precision recall f1-score support 0 0.59 0.66 0.62 29 1 0.66 0.59 0.62 32 micro avg 0.62 0.62 0.62 61 macro avg 0.62 0.62 0.62 61 weighted avg 0.63 0.62 0.62 61

# Confusion matrix(혼동 행렬)로 결과 시각화

class_names = [0,1] fig,ax = plt.subplots() tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks,class_names) plt.yticks(tick_marks,class_names) sns.heatmap(pd.DataFrame(cnf_matrix),annot=True,cmap="Blues",fmt="d",cbar=False) ax.xaxis.set_label_position('top') plt.tight_layout() plt.ylabel('Actual label') plt.xlabel('Predicted label');





#Reference

1) https://towardsdatascience.com/heart-disease-prediction-in-tensorflow-2-tensorflow-for-hackers-part-ii-378eef0400ee

2) https://colab.research.google.com/drive/13EThgYKSRwGBJJn_8iAvg-QWUWjCufB1

3) https://www.kaggle.com/ronitf/heart-disease-uci

4) https://www.tensorflow.org/tutorials/structured_data/feature_columns

5) https://locslab.github.io/Tensorflow-feature-columns(1)/





[TensorFlow] 심장질환 예측 End

BioinformaticsAndMe

[TensorFlow] RNN 기반의 텍스트 분류 Start

BioinformaticsAndMe









[TensorFlow] RNN을 이용한 텍스트 분류


: TensorFlow 2.0 에서 수행되는 RNN(순환신경망) 기반의 텍스트 분류 신경망 학습 과정

*RNN(Recurrent Neural Network() - 뉴런 출력이 다시 입력으로 재귀하는 연결 구조의 인공신경망 알고리즘

: IMDB Large Movie Review Dataset 영화 리뷰 데이터 사용

ㄱ) '긍정 리뷰는 1, 부정 리뷰는 0'으로 표시된 레이블 및 리뷰에 대한 텍스트로 구성된 데이터

ㄴ) 25000개 Training 데이터 및 25000개 Testing 데이터를 보유




1. 파이썬 라이브러리 로딩


: 텍스트 분류에 사용되는 파이썬 라이브러리 로딩

# '__future__' : python 2에서 python 3 문법 사용 가능 from __future__ import absolute_import, division, print_function, unicode_literals # 텐서플로우 및 데이터셋 라이브러리 임포트 import tensorflow_datasets as tfds import tensorflow as tf

# 시각화를 위한 matplotlib 라이브러리 임포트 import matplotlib.pyplot as plt def plot_graphs(history, string): plt.plot(history.history[string]) plt.plot(history.history['val_'+string], '') plt.xlabel("Epochs") plt.ylabel(string) plt.legend([string, 'val_'+string]) plt.show()




2. 인풋 프로세스 설정


: Training을 위한 Input 데이터 및 파이프라인 설정

# 데이터셋 다운로드

dataset, info = tfds.load('imdb_reviews/subwords8k', with_info=True, as_supervised=True) train_dataset, test_dataset = dataset['train'], dataset['test']

Downloading and preparing dataset imdb_reviews (80.23 MiB) to /root/tensorflow_datasets/imdb_reviews/subwords8k/0.1.0... Dl Completed... 1/|/100% 1/1 [00:04<00:00, 4.94s/ url] Dl Size... 80/|/100% 80/80 [00:04<00:00, 16.31 MiB/s] Dataset imdb_reviews downloaded and prepared to /root/tensorflow_datasets/imdb_reviews/subwords8k/0.1.0. Subsequent calls will reuse this data.

# 데이터셋 info에는 인코딩 정보가 담기며, 컴퓨터가 인식하는 단어수 출력

encoder = info.features['text'].encoder

print ('Vocabulary size: {}'.format(encoder.vocab_size))

Vocabulary size: 8185

# 'Hello TensorFlow' 인코딩하기

sample_string = 'Hello TensorFlow.' encoded_string = encoder.encode(sample_string) print ('Encoded string is {}'.format(encoded_string)) original_string = encoder.decode(encoded_string) print ('The original string: "{}"'.format(original_string))

Encoded string is [4025, 222, 6307, 2327, 4043, 2120, 7975] The original string: "Hello TensorFlow."

# 예외 처리를 위한 가정 설정문(assert) 사용

assert original_string == sample_string # 인코드된 정보 확인 for index in encoded_string: print ('{} ----> {}'.format(index, encoder.decode([index])))

4025 ----> Hell 222 ----> o 6307 ----> Ten 2327 ----> sor 4043 ----> Fl 2120 ----> ow 7975 ----> .

# Training을 위한 데이터 준비

BUFFER_SIZE = 10000        #Buffer size: 1 epoch 되는 데이터 수 BATCH_SIZE = 64             #Batch size: 1 step에서 사용되는 데이터 수


train_dataset = train_dataset.shuffle(BUFFER_SIZE) train_dataset = train_dataset.padded_batch(BATCH_SIZE, train_dataset.output_shapes) test_dataset = test_dataset.padded_batch(BATCH_SIZE, test_dataset.output_shapes)




3. 모델 생성


: 입/출력을 시퀀스 단위로 처리하고 순환적으로 주고 받는 RNN 모델 생성

# 텍스트를 숫자로 변환하는 Word embedding에서, Layer는 단어마다 하나의 Vector로 저장

model = tf.keras.Sequential([ tf.keras.layers.Embedding(encoder.vocab_size, 64), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid') ])

# 케라스 모델을 컴파일하여, Training 과정 configure

model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(1e-4), metrics=['accuracy'])




4. 모델 Training


# model.fit 함수로 모델이 학습되면서 손실과 정확도 지표 출력

history = model.fit(train_dataset, epochs=10, validation_data=test_dataset,

validation_steps=30)

Epoch 1/10 391/391 [==============================] - 937s 2s/step - loss: 0.6472 - accuracy: 0.6030 - val_loss: 0.0000e+00 - val_accuracy: 0.0000e+00 Epoch 2/10 391/391 [==============================] - 994s 3s/step - loss: 0.3484 - accuracy: 0.8593 - val_loss: 0.3369 - val_accuracy: 0.8505 Epoch 3/10 391/391 [==============================] - 988s 3s/step - loss: 0.2492 - accuracy: 0.9074 - val_loss: 0.3119 - val_accuracy: 0.8698 Epoch 4/10 391/391 [==============================] - 986s 3s/step - loss: 0.2091 - accuracy: 0.9244 - val_loss: 0.3093 - val_accuracy: 0.8693 Epoch 5/10 391/391 [==============================] - 987s 3s/step - loss: 0.1793 - accuracy: 0.9371 - val_loss: 0.3262 - val_accuracy: 0.8693 Epoch 6/10 391/391 [==============================] - 988s 3s/step - loss: 0.1595 - accuracy: 0.9454 - val_loss: 0.3674 - val_accuracy: 0.8708 Epoch 7/10 391/391 [==============================] - 996s 3s/step - loss: 0.1450 - accuracy: 0.9516 - val_loss: 0.3684 - val_accuracy: 0.8672 Epoch 8/10 391/391 [==============================] - 987s 3s/step - loss: 0.1432 - accuracy: 0.9529 - val_loss: 0.4392 - val_accuracy: 0.7958 Epoch 9/10 391/391 [==============================] - 982s 3s/step - loss: 0.1345 - accuracy: 0.9560 - val_loss: 0.3832 - val_accuracy: 0.8542 Epoch 10/10 391/391 [==============================] - 990s 3s/step - loss: 0.1104 - accuracy: 0.9657 - val_loss: 0.4369 - val_accuracy: 0.8547

# model.evaludate 함수로 Test set 정확도 평가 test_loss, test_acc = model.evaluate(test_dataset) print('Test Loss: {}'.format(test_loss)) print('Test Accuracy: {}'.format(test_acc))

391/391 [==============================] - 192s 491ms/step - loss: 0.4446 - accuracy: 0.8577 Test Loss: 0.44456175211674115 Test Accuracy: 0.8576800227165222

# 패딩(padding) - 모델 입력으로 사용하기 위해, 모든 샘플 길이를 동일하게 맞추는 작업

# 보통 0을 넣어서 길이가 다른 샘플들의 길이를 맞춰줌

def pad_to_size(vec, size): zeros = [0] * (size - len(vec)) vec.extend(zeros) return (vec)

# 예측도 함수 정의 (prediction이 0.5이상은 리뷰 positive, 0.5이하는 리뷰 negative)

def sample_predict(sentence, pad): encoded_sample_pred_text = encoder.encode(sample_pred_text) if pad: encoded_sample_pred_text = pad_to_size(encoded_sample_pred_text, 64) encoded_sample_pred_text = tf.cast(encoded_sample_pred_text, tf.float32) predictions = model.predict(tf.expand_dims(encoded_sample_pred_text, 0)) return (predictions)

# 패딩 작업없이 Sample text 분류 sample_pred_text = ('The movie was cool. The animation and the graphics ' 'were out of this world. I would recommend this movie.') predictions = sample_predict(sample_pred_text, pad=False) print (predictions)

[[0.5275577]]        #Positive

# 패딩 작업으로 Sample text 분류 sample_pred_text = ('The movie was cool. The animation and the graphics ' 'were out of this world. I would recommend this movie.') predictions = sample_predict(sample_pred_text, pad=True) print (predictions)

[[0.57966185]]        #Positive

# 모델의 정확도값 시각화 plot_graphs(history, 'accuracy')

# 모델의 손실값 시각화 plot_graphs(history, 'loss')





#Reference

1) https://www.tensorflow.org/tutorials/text/text_classification_rnn

2) https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/text/text_classification_rnn.ipynb#scrollTo=hw86wWS4YgR2

3) https://wikidocs.net/24586

4) https://towardsdatascience.com/implementation-of-rnn-lstm-and-gru-a4250bf6c090

5) https://wikidocs.net/32105





[TensorFlow] RNN 기반의 텍스트 분류 End

BioinformaticsAndMe

[TensorFlow] 이미지 분류 신경망 Start

BioinformaticsAndMe










[TensorFlow] 케라스를 이용한 이미지 분류


: TensorFlow 2.0 에서 수행되는 기본적인 이미지 분류 신경망 학습 과정

: 티셔츠/바지/운동화 등의 10개 카테고리 이미지(Fashion MNIST 데이터셋)를 분류하기 위한 뉴럴 네트워크 모델

: 고수준 API인 케라스(tf.keras) 사용 




1. 파이썬 라이브러리 로딩


: 이미지 분류에 사용되는 파이썬 라이브러리 로딩

# '__future__' : python 2에서 python 3 문법 사용 가능 from __future__ import absolute_import, division, print_function, unicode_literals, unicode_literals # 텐서플로우 및 케라스 라이브러리 임포트 import tensorflow as tf from tensorflow import keras # 넘파이 및 matplotlib 라이브러리 임포트 import numpy as np import matplotlib.pyplot as plt

# 텐서플로우 버전 확인 print(tf.__version__)

2.0.0




2. Fashion MNIST 데이터셋


: 이미지 분류의 재료가 되는 Fashion MNIST 데이터셋

ㄱ) 10개 카테고리와 7만개의 흑백 이미지로 구성

ㄴ) 각 이미지는 낮는 해상도로 개별 옷 품목을 나타냄

: 이미지 분류 뉴럴 네트워크 모델링에 6만개의 이미지를 사용

: 만들어진 네트워크의 이미지 분류 정확도를 평가하기 위해, 나머지 1만개 이미지 사용

# Fashion MNIST 데이터셋은 텐서플로우에서 쉽게 로딩 가능

# load_data() 함수로 넘파이 배열을 반환 fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

#train_images, train_labels 배열은 모델 학습에 사용될 Training set #test_images, test_labels 배열은 모델 테스트에 사용될 Test set

Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz 32768/29515 [=================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz 26427392/26421880 [==============================] - 1s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz 8192/5148 [===============================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz 4423680/4422102 [==============================] - 0s 0us/step

: 모든 이미지는 28x28 픽셀의 넘파이 배열 (픽셀 값은 0~255)

: Label은 0~9의 정수 배열 (옷 이미지의 클래스를 나타냄, 각 이미지는 1개 Label에 매핑됨)

# 데이터셋에 클래스 이름이 없으므로, 나중에 이미지를 출력하기 위해 별도의 변수를 생성

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']




3. 데이터 점검


: 모델 훈련 전, Training/Test 데이터셋 구조 확인하기

# Traning set 확인 (60000개 이미지, 28x28 픽셀)

train_images

(60000, 28, 28)

# Training set의 각 Label은 0~9 정수

train_labels

array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)

# Test set 확인 (10000개 이미지, 28x28 픽셀)

test_images.shape

(60000, 28, 28)

# Test set의 각 Label은 0~9 정수

test_labels

array([9, 2, 1, ..., 8, 1, 5], dtype=uint8)




4. 데이터 전처리


: 모델 훈련 전, 정확한 모델링을 위한 데이터셋 전처리

# 픽셀 값의 범위가 0~255 라는 것을 확인

plt.figure() plt.imshow(train_images[0]) plt.colorbar() plt.grid(False) plt.show()

# Training/Test set 모두 255로 나누어, 범위값을 0~1 사이로 표준화

train_images = train_images / 255.0

test_images = test_images / 255.0

# 데이터 포맷 확인을 위해, Training set에서 처음 25개 이미지 및 클래스를 출력

plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i], cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[i]])

plt.show()




5. 모델 층(Layer) 설정


: 신경망 기본 구성 요소인 층(Layer)을 생성하고 연결

# keras.layers.Flatten로 첫번째 층 생성 후, 두 개의 keras.layers.Dense 층에 연결

model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ])

#keras.layers.Flatten - 이미지에 있는 픽셀의 행을 펼쳐서 일렬로 배열(28*28=784 픽셀의 1차원 배열 변환) #keras.layers.Dense - 마지막 층은 10개 노드의 Softmax 층으로 10개 클라스 중 하나에 속할 확률을 출력(전체 합=1)




6. 모델 컴파일(Compile)


ㄱ) Optimizer - 데이터와 손실 함수 기반으로 모델 업데이트 방법을 결정

ㄴ) Loss function - 훈련 동안의 모델 오차를 측정 (모델이 올바른 학습을 하도록 이 함수를 최소화)

ㄷ) Metrics - 훈련 단계와 테스트 단계를 모니터링 (아래는 올바르게 분류된 이미지 비율인 정확도를 사용)

# 모델 훈련에 필요한 설정을 컴파일 과정에서 추가

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])




7. 모델 훈련


1) Training set을 모델에 주입 (train_images 및 train_labels 배열)

2) 모델이 이미지와 레이블을 매핑하는 방법을 학습

3) Test set에 대한 모델의 예측 생성 (test_images 및 test_labels 배열)

# model.fit 함수로 모델이 학습되면서 손실과 정확도 지표 출력 model.fit(train_images, train_labels, epochs=5)

Train on 60000 samples Epoch 1/5 60000/60000 [==============================] - 5s 85us/sample - loss: 0.6054 - accuracy: 0.8128 Epoch 2/5 60000/60000 [==============================] - 5s 85us/sample - loss: 0.5179 - accuracy: 0.8242 Epoch 3/5 60000/60000 [==============================] - 5s 85us/sample - loss: 0.5379 - accuracy: 0.8268 Epoch 4/5 60000/60000 [==============================] - 5s 84us/sample - loss: 0.5429 - accuracy: 0.8281 Epoch 5/5 60000/60000 [==============================] - 5s 86us/sample - loss: 0.5362 - accuracy: 0.8312 <tensorflow.python.keras.callbacks.History at 0x7f59c40b9668>




8. 정확도(Accuracy) 평가


: Test set으로 모델의 성능을 비교

: 과적합(Overfitting)으로 인해, Test set이 Training set보다 정확도가 낮음

# model.evaludate 함수로 Test set 정확도 평가 test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\n테스트 정확도:', test_acc)

10000/1 - 0s - loss: 0.5376 - accuracy: 0.7879 테스트 정확도: 0.7879




9. 예측(Prediction) 실행


학습된 모델을 사용하여, 이미지에 대한 예측이 가능

: Test set에 있는 각 이미지의 Label 예측

# 첫번째 예측으로 10개의 옷 품목에 상응하는 모델의 신뢰도가 배열로 보여짐 predictions = model.predict(test_images)

predictions[0]

array([0. , 0. , 0. , 0. , 0. , 0.1025838 , 0. , 0.10969254, 0. , 0.78772366], dtype=float32)

# 가장 높은 신뢰도를 가진 레이블 확인 np.argmax(predictions[0])

9    #모델은 해당 이미지를 앵클 부츠(class_name[9])로 예측

# 예측이 정확한지 테스트 레이블 확인 test_labels[0]

9    #정답

# 이미지 클래스를 예측하여 그래프/신뢰도를 출력하는 함수 정의 def plot_image(i, predictions_array, true_label, img): predictions_array, true_label, img = predictions_array[i], true_label[i], img[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 100*np.max(predictions_array), class_names[true_label]), color=color) def plot_value_array(i, predictions_array, true_label): predictions_array, true_label = predictions_array[i], true_label[i] plt.grid(False) plt.xticks([]) plt.yticks([]) thisplot = plt.bar(range(10), predictions_array, color="#777777") plt.ylim([0, 1]) predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red') thisplot[true_label].set_color('blue')

# 올바른 예측은 파란색, 잘못 예측은 빨강색

# 숫자는 예측 레이블의 신뢰도 퍼센트 num_rows = 5 num_cols = 3 num_images = num_rows*num_cols plt.figure(figsize=(2*2*num_cols, 2*num_rows)) for i in range(num_images): plt.subplot(num_rows, 2*num_cols, 2*i+1) plot_image(i, predictions, test_labels, test_images) plt.subplot(num_rows, 2*num_cols, 2*i+2) plot_value_array(i, predictions, test_labels) plt.show()

# 한 개의 이미지 예측을 테스트하기 위해, Test set에서 이미지 선택 img = test_images[0] # tf.keras 모델은 한 개의 이미지만 사용할 때에도 배치 추가 img = (np.expand_dims(img,0)) # 입력된 이미지에 대한 예측 실행 predictions_single = model.predict(img) plot_value_array(0, predictions_single, test_labels) _ = plt.xticks(range(10), class_names, rotation=45)

# model.predict 함수는 2차원 넘파이 배열을 반환하므로 첫 번째 이미지 예측을 선택 np.argmax(predictions_single[0])

9    #모델은 해당 이미지를 앵클 부츠(class_name[9])로 예측






#Reference

1) https://www.tensorflow.org/tutorials/keras/classification

2) https://colab.research.google.com/github/tensorflow/docs/blob/master/site/ko/tutorials/keras/classification.ipynb#scrollTo=2tRmdq_8CaXb

3) https://towardsdatascience.com/multi-label-classification-and-class-activation-map-on-fashion-mnist-1454f09f5925





[TensorFlow] 이미지 분류 신경망 End

BioinformaticsAndMe

[TensorFlow1.0] 인공신경망 (Artificial neural network) 기초 Start

BioinformaticsAndMe










1. 인공신경망 (Artificial Neural Network;ANN)


: 인공신경망(ANN)은 인간의 뇌를 묘사한 기계학습 예측 모델

→ 인공적인 신경망인 뉴런으로 구성되어, 입력값을 받아 계산 수행

: 인공신경망은 최근 딥러닝의 도약으로 그 성능이 재조명되고 활발하게 사용되는 중

: 인공신경망 종류

ㄱ) Perceptron(퍼셉트론) - 각 노드의 가중치 합이 0보다 크면 활성화되는 기본적인 인공신경망 알고리즘

ㄴ) Convolutional Neural Network(CNN) - 시신경 구조를 모방한 인공신경망 알고리즘

ㄷ) Recurrent Neural Network(RNN) - 뉴런 출력이 다시 입력으로 재귀하는 연결 구조의 인공신경망 알고리즘


#INPUT LAYER(입력층) - 외부 데이터를 입력하는 입구 노드

#HIDDEN LAYER(은닉층) - 노드 사이를 연결하고, 결과를 노드로 전달

#OUTPUT LAYER(출력층) - 최종 결과를 내보내는 출구 노드





2. [TensorFlow] 텐서플로우 인공신경망 기초


# '__future__' : python 2에서 python 3 문법 사용 가능

from __future__ import absolute_import, division, print_function

# 케라스, 넘파이 라이브러리 임포트 from tensorflow.keras import layers , models , optimizers , losses , initializers import numpy as np



ㄱ) Input 1개, Output 1개 인공신경망

# 그래프 생성

# initializers.Constant(2)는 weight값을 default 2로 지정 input_node = layers.Input(shape = (1,) ) output_node = layers.Dense( units = 1 , kernel_initializer = initializers.Constant(2))(input_node) # 모델 생성 model = models.Model( inputs = input_node , outputs = output_node )

# 샘플 1개를 생성된 모델로 출력

x = np.asarray([[10]]) model.predict(x)

array([[20.]], dtype=float32)

# 샘플 3개를 생성된 모델로 출력

x = np.asarray([[1],[2],[10]]) model.predict(x)

array([[ 2.], [ 4.], [20.]], dtype=float32)



ㄴ) Input 2개, Output 2개 인공신경망


# 그래프 생성

input_node = layers.Input(shape = (2,) ) output_node = layers.Dense( units = 2 , kernel_initializer = initializers.Constant(2))(input_node)

# 모델 생성 model = models.Model( inputs = input_node , outputs = output_node )

# 샘플 1개를 생성된 모델로 출력

x = np.asarray([[10 , 2]]) model.predict(x)

array([[24., 24.]], dtype=float32)

# 샘플 4개를 생성된 모델로 출력

x = np.asarray([[10 , 2],[2 , 4],[10 , 5],[22,11]]) model.predict(x)

array([[24., 24.], [12., 12.], [30., 30.], [66., 66.]], dtype=float32)



ㄷ) Input 2개, Hidden 2개, Output 1개 인공신경망

# 그래프 생성

input_node = layers.Input(shape = (2,) ) hidden_node = layers.Dense( units = 2 , kernel_initializer = initializers.Constant(2))(input_node) output_node = layers.Dense( units = 1 , kernel_initializer = initializers.Constant(3))(hidden_node)


# 모델 생성 model = models.Model( inputs = input_node , outputs = output_node )

# 샘플 1개를 생성된 모델로 출력

x = np.asarray([[10 , 2]]) model.predict(x)

array([[144.]], dtype=float32)

# 샘플 4개를 생성된 모델로 출력

x = np.asarray([[10 , 2],[2 , 4],[10 , 5],[22,11]]) model.predict(x)

array([[144.], [ 72.], [180.], [396.]], dtype=float32)





3. [TensorFlow] 활성함수 (relu vs softmax)


relu 활성함수

- 노드 결과값이 음수면 0을 내보냄

- 마지막이 아닌 레이어에 사용


 softmax 활성함수

- 입력값을 0~1사이 값으로 표준화하여 출력

- 출력값들의 총합은 항상 1

- 마지막 레이어 Output이 2개 이상일 경우, 마지막 레이어에 사용


# relu 활성함수 모델링

input_node2 = layers.Input(shape = (2,) ) output_node2 = layers.Dense( units = 1 , activation = 'relu' , kernel_initializer = initializers.Constant(1))(input_node2) model2 = models.Model( inputs = input_node2 , outputs = output_node2 )


# 예제 데이터 data = [[ 1 ,-3], [ 3 , -9], [ 10, 0], [ -8 ,10], [ 0 , -1]] data = np.array(data)


# relu 활성함수 예제 결과 res2 = model2.predict(data) print(res2)

[[ 0.] [ 0.] [10.] [ 2.] [ 0.]]





#Reference

1) https://namu.wiki/w/%EC%9D%B8%EA%B3%B5%EC%8B%A0%EA%B2%BD%EB%A7%9D

2) https://ko.wikipedia.org/wiki/%EC%9D%B8%EA%B3%B5_%EC%8B%A0%EA%B2%BD%EB%A7%9D

3) 2019년도 유전체 분석 분야 재직*연구자 전문교육

4) https://www.sciencedirect.com/science/article/pii/B9780128015599000065

5) https://m.blog.naver.com/wideeyed/221021710286





[TensorFlow1.0] 인공신경망 (Artificial neural network) 기초 End

BioinformaticsAndMe

[TensorFlow1.0] Cancer classification using gene expression Start

BioinformaticsAndMe










[TensorFlow] Cancer classification using gene expression


: TensorFlow 1.0 에서 수행되는 유전자 발현 기반의 Cancer classification 과정

*유전자 발현에 근거하여, Cancer와 Normal을 구분하는 모델링 수행

: 아래 캐글(Kaggle) 사이트에는 '백혈병 AML/ALL'을 예측하는 다양한 텐서플로우 모델들이 존재

*https://www.kaggle.com/varimp/gene-expression-classification





[TensorFlow] 유전자 발현에 근거한 암 분류 모델 예제


: Bladder~Stomach → 해당 조직의 발현값

: Cancer_1 → 1(암환자), 0(정상인)

: 아래 예제 파일은 첫번째 행(Annotation)을 필터한 상태

Example_expression.csv


Bladder

Breast

Brain

Colon

Kidney

Liver

Lung

Pancreas

Ovary

Stomach

Cancer_1

6.0588

2.8661

3.0927

6.0077

2.8955

5.5982

2.8897

6.1144

5.3427

8.1293

0

4.4945

2.2051

0.9343

5.2312

1.787

7.3889

2.5828

3.4843

5.5047

6.8844

0

6.2015

3.66

2.9109

6.6927

1.5316

6.6405

3.6972

4.4913

5.4835

8.8552

0

6.2664

1.5854

4.9801

5.3313

2.8055

7.7239

4.2165

3.8075

5.8058

8.6699

1

5.904

2.1047

4.3618

5.9225

1.3454

6.388

3.1604

5.6396

5.1506

8.3964

1

# '__future__' : python 2에서 python 3 문법 사용 가능

from __future__ import absolute_import, division, print_function

# 텐서플로우, 넘파이 라이브러리 임포트 import tensorflow as tf

import numpy as np

# 유전자 발현 데이터 로딩 및 배열 확인 xy = np.loadtxt('Example_expression.csv', delimiter=',', dtype=np.float32) x_data = xy[:, 0:-1] y_data = xy[:, [-1]] print(x_data, y_data) print(x_data.shape, y_data.shape)

[[6.0588 2.8661 3.0927 ... 6.1144 5.3427 8.1293] [4.4945 2.2051 0.9343 ... 3.4843 5.5047 6.8844] [6.2015 3.66 2.9109 ... 4.4913 5.4835 8.8552] ... [6.6107 0.7146 2.6828 ... 4.8744 4.8949 6.7165] [6.9365 2.5683 5.0457 ... 4.89 5.7063 7.8359] [5.9141 2.676 2.1013 ... 4.3999 6.5358 8.5825]] [[0.] [0.] [0.] ... [1.] [1.] [1.]] (5000, 10) (5000, 1)

# 프로그램 실행 순간에 변수값을 입력하기 위해 placedholder 함수 사용

X = tf.placeholder(tf.float32, shape=[None, 10]) Y = tf.placeholder(tf.float32, shape=[None, 1])

# 텐서플로우에서 학습될 W(Weight) 및 b(bias) 값을 변수(Variable) 노드로 정의 # W와 b 값의 초기값 정보가 없기에 랜덤하게 값을 설정 W = tf.Variable(tf.random_normal([10,1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias')

# sigmoid 함수를 이용한 가설 정의 hypothesis = tf.sigmoid(tf.matmul(X, W) + b)

# cost function 정의 (reduce_mean 함수로 평균 계산)

cost = tf.reduce_mean(Y*tf.log(hypothesis + 0.001) + (1-Y)*tf.log(1-hypothesis+0.001))

# 최적화를 위한 경사하강법 정의 train = tf.train.GradientDescentOptimizer(learning_rate=0.0001).minimize(cost)

# hypothesis 값이 0.5 이상이면 'true'로 예측 predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)


# 정확도 연산 accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))

# 세션을 생성하고 그래프 실행 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for step in range(10001): cost_val, _ = sess.run([cost, train], feed_dict={X:x_data, Y:y_data}) if step%1000==0: print(step, cost_val)

# 정확도 결과 출력 h, c, a = sess.run([hypothesis, predicted, accuracy], feed_dict={X:x_data, Y:y_data}) print("\nHypothesis: ", h, "\nCorrect (Y): ", c, "\nAccuracy: ", a)

0 -3.9441097 1000 -3.9540856 2000 -3.9601758 3000 -3.96437 4000 -3.9674852 5000 -3.9699223 6000 -3.9718964 7000 -3.973543 8000 -3.9749436 9000 -3.9761567 10000 -3.9772208 Hypothesis: [[1.5199184e-06] [3.5762787e-07] [4.1723251e-07] ... [2.3841858e-07] [2.9802322e-07] [0.0000000e+00]] Correct (Y): [[0.] [0.] [0.] ... [0.] [0.] [0.]] Accuracy: 0.4216





#Reference

1) https://github.com/aymericdamien/TensorFlow-Examples/tree/master/tensorflow_v2

2) https://medium.com/@manjabogicevic/multiple-linear-regression-using-python-b99754591ac0

3) http://contents.kocw.net/document/ch5_6.pdf

4) https://www.kaggle.com/varimp/gene-expression-classification

5) 2019년도 유전체 분석 분야 재직*연구자 전문교육





[TensorFlow1.0] Cancer classification using gene expression End

BioinformaticsAndMe

[TensorFlow1.0] Multiple Linear Regression Start

BioinformaticsAndMe










[TensorFlow] Multiple Linear Regression(MLR)?


: TensorFlow 1.0 에서 수행되는 다중선형회귀분석(Multiple Linear Regression;MLR) 과정

*Multiple Linear Regression - 설명변수(독립변수)가 2개 이상이고, 종속변수가 1개인 회귀모형을 모델링하는 기법

: 다중선형회귀분석은 여러 독립변수를 도입함으로써, 오차값을 줄이고 결과 정확도를 높임


: 아래 표를 기반해 'Profit'을 종속변수(Dependent variable)로, 나머지를 독립변수(Independent variable)에 두는 다중회귀모형을 만들 수 있음





[TensorFlow] MLR 예제


: 텐서플로우 MLR 분석을 위한, 기업 공채 지원자 점수 예제표

지원자

1차 서류

2차 인적성 

3차 면접 

최종 점수

65

90

85

240

80

88

92

260

70

75

95

240

75

85

65

225

90

85

85

260

# '__future__' : python 2에서 python 3 문법 사용 가능

from __future__ import absolute_import, division, print_function

# 텐서플로우 라이브러리 임포트 import tensorflow as tf

# 예제 데이터

x_data = [[65., 90., 85.], [80., 88., 92.], [70., 75., 95.], [75., 85., 65.], [90., 85., 85.]] y_data = [[240.], [260.], [240.], [225.], [260.]]

# 프로그램 실행 순간에 변수값을 입력하기 위해 placedholder 함수 사용 X = tf.placeholder(tf.float32, shape=[None, 3]) Y = tf.placeholder(tf.float32, shape=[None, 1])

# 텐서플로우에서 학습될 W(Weight) 및 b(bias) 값을 변수(Variable) 노드로 정의

# W와 b 값의 초기값 정보가 없기에 랜덤하게 값을 설정 W = tf.Variable(tf.random_normal([3,1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias')

# 다중회귀모형 가설 정의 (matmul 함수로 행렬곱 수행)

hypothesis = tf.matmul(X, W) + b


# cost function 정의 (reduce_mean 함수로 평균 계산) cost = tf.reduce_mean(tf.square(hypothesis - Y))


# 최적화를 위한 경사하강법 정의

optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)


# minimize 함수를 사용해 cost 함수의 최소값을 얻음 train = optimizer.minimize(cost)

# 세션을 생성하고 그래프의 모든 전역변수를 초기화 sess = tf.Session() sess.run(tf.global_variables_initializer())

# 그래프를 실행하고 feed_dict를 통해 실행 초기값을 입력함 for step in range(1001): cost_val, hy_val, _ = sess.run( [cost, hypothesis, train], feed_dict={X: x_data, Y: y_data} ) if step%200==0: print(step, "Cost: ", cost_val, "\nPrediction:\n", hy_val)

0 Cost: 8397.166 Prediction: [[169.02368] [165.52513] [160.76976] [130.99226] [146.38747]] 200 Cost: 93.65354 Prediction: [[254.29305] [260.94043] [245.62996] [218.28816] [246.3491 ]] 400 Cost: 53.146355 Prediction: [[251.37286] [260.50125] [243.09482] [221.05096] [249.46597]] 600 Cost: 31.487442 Prediction: [[249.10394] [260.2357 ] [241.52197] [222.79031] [251.7963 ]] 800 Cost: 19.353357 Prediction: [[247.3255 ] [260.0807 ] [240.56805] [223.86734] [253.5586 ]] 1000 Cost: 12.246923 Prediction: [[245.92062] [259.99527] [240.00885] [224.5187 ] [254.90598]]





#Reference

1) https://github.com/aymericdamien/TensorFlow-Examples/tree/master/tensorflow_v2

2) https://medium.com/@manjabogicevic/multiple-linear-regression-using-python-b99754591ac0

3) http://contents.kocw.net/document/ch5_6.pdf





[TensorFlow1.0] Multiple Linear Regression End

BioinformaticsAndMe

차원의 저주 (Curse of dimensionality) Start

BioinformaticsAndMe






차원의 저주 (Curse of dimensionality)


: 수학적 공간 차원(=변수 개수)이 늘어나면서, 문제 계산법이 지수적으로 커지는 상황

: 차원이 높아질수록 데이터 사이의 거리가 멀어지고, 빈공간이 증가하는 공간의 성김 현상(Sparsity)을 보임

*KNN(K-Nearest Neighbors) 분류 알고리즘에서 흔하게 발생하는 문제


(좌측 그림) - 1차원에 10개의 데이터가 존재 (10^1=10)

(중앙 그림) - 2차원에 100개의 데이터가 존재 (10^2=100)

(우측 그림) - 3차원에 1,000개의 데이터가 존재 (10^3=1,000)


→ '8'의 위치를 설명하는 상황에서, 차원이 커질수록  설명 공간이 지수적으로 늘어남

→ Feature가 많아질수록, 동일한 데이터를 설명하는 빈 공간이 증가함

→ 차원의 저주로 인해, 알고리즘 모델링 과정에서 저장 공간과 처리 시간이 불필요하게 증가됨 (성능 저하)





차원의 저주 피하기


: 차원을 줄이는 알고리즘 사용

ㄱ) PCA(Principal Component Analysis)

ㄴ) LDA(Linear Discriminant Analysis)

ㄷ) LLE(Locally Linear Embedding)

ㄹ) MDS(Multidimensional Scaling)

ㅁ) Isomap

ㅅ) t-SNE(t-Distributed Stochastic Neighbor Embedding)







#Reference

1) https://medium.com/diogo-menezes-borges/give-me-the-antidote-for-the-curse-of-dimensionality-b14bce4bf4d2

2) https://zetawiki.com/wiki/차원의_저주

3) https://www.kdnuggets.com/2017/04/must-know-curse-dimensionality.html

4) https://datapedia.tistory.com/15





차원의 저주 (Curse of dimensionality) End

BioinformaticsAndMe

Feature selection vs Feature extraction Start

BioinformaticsAndMe






1. Feature selection (특징 선택)


: Feature selection(=Variable selection)은 관련없거나 중복되는 Feature들을 필터링하고 간결한 subset을 생성하는 과정

*Feature(특징) - 데이터 모델의 모든 입력 변수

: 대규모 변수를 가진 데이터에서 Feature selection은 차원 감소에 효과적

→머신 러닝 알고리즘의 Performance 향상

: Variance Thresholds(비지도학습) 또는 Genetic Algorithms(지도학습)에 사용됨





2. Feature extraction (특징 추출)


: Feature extraction은 기존 Feature들의 조합으로 유용한 Feature들을 새롭게 생성하는 과정

: 고차원의 원본 Feature 공간을 저차원의 새로운 Feature 공간으로 투영함

: PCA(비지도학습), LDA(지도학습)에 사용됨





3. Feature selection vs Feature extraction


: 데이터의 차원을 줄이기 위해, Feature selection(특징 선택) 및 Feature extraction(특징 추출) 과정을 진행할 수 있음

*Feature selection - 기존 Feature들의 부분 집합(하위 집단)을 유지

*Feature extraction - 기존 Feature에 기반하여 새로운 Feature들을 생성

: 수많은 변수가 있는 데이터셋에서, 적절한 Feature selection과 Feature extraction으로 오버피팅 방지 가능







#Reference

1) https://medium.com/@mehulved1503/feature-selection-and-feature-extraction-in-machine-learning-an-overview-57891c595e96

2) http://parnec.nuaa.edu.cn/jliu/FeatureExtraction.htm

3) https://benthamopen.com/FULLTEXT/TOBIOIJ-11-117

4) https://elitedatascience.com/dimensionality-reduction-algorithms#feature-selection

5) https://www.researchgate.net/publication/315807942_Affect_Measurement_A_Roadmap_Through_Approaches_Technologies_and_Data_Analysis

6) http://terryum.io/korean/2016/05/05/FeatureSelection_KOR/





Feature selection vs Feature extraction End

BioinformaticsAndMe

K-NN(최근접이웃) 알고리즘 Start

BioinformaticsAndMe







What is a K-NN Algorithm?


: K-NN(Nearest Neighbor)는 단순하지만 높은 정확성의 특징으로 널리 사용되는 분류 알고리즘

: K-NN은 사용할 수 있는 모든 경우를 저장하고 Distance measure 등의 유사성에 기반하여, 새로운 정보를 분류하는 단순한 알고리즘

: 객체는 K개의 최근접 이웃 사이에서 가장 공통적인 항목에 할당되는 객체로 과반수 투표에 의해 분류

*예제: 당신은 내가 다음 총선 때 여당과 야당 중 어느 쪽을 지지할지 예측할 수 있는가?

   당신이 나를 전혀 몰라도, 내 주변 이웃들이 지지하는 정당을 안다면, 어느 정도 내 선택을 예측할 수 있다.





How the K-NN algorithm works?


: K-NN에서 K는 가장 가까운 이웃의 수 (이웃의 수는 이 알고리즘의 핵심적인 결정 요인)

: 클래스가 두 개인 경우에서 K는 일반적으로 홀수 (K=1 인 경우의 알고리즘은 가장 가까운 인접 알고리즘이라 함)

: 아래 그림은 노랑색 물음표의 Label을 예측하는 상황에서, K=1인 경우, 물음표에 가장 가까운 이웃의 Label을 물음표에 할당



KNN 알고리즘 아래 3단계로 수행된다

1) 가장 가까운 이웃을 찾기 위해, Distance measure를 사용해 이웃 간의 거리를 계산

*Distance measure: Euclidean distance/Manhattan distance/Minkowski distance

2) 거리가 가까운 이웃들 K개 만큼 찾음

3) 찾아진 이웃들을 다수결 투표 원칙으로 기반하여, 신규 데이터 Label 예측 



#일반적으로 사용되는 Euclidean distance measure





How to choose the optimal value of K?


: 이웃수 K는 K-NN 모델링에서 입력해야 하는 Hyper-parameter

: 일반적으로 K 값이 커질수록 전체 노이즈가 줄어들면서, 모델의 정확도가 커짐 (항상 그런 것은 아님)

: 대부분의 데이터셋에서 K 값은 3~10 정도를 사용
*Cross-validation을 통해, 적합한 K 값을 찾기도 함
: 보통, 클래스 개수가 짝수인 경우에는 홀수 K 값을 선택함







#Reference

1) https://www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learn

2) https://www.kdnuggets.com/2019/07/classifying-heart-disease-using-k-nearest-neighbors.html

3) https://ko.wikipedia.org/wiki/K-%EC%B5%9C%EA%B7%BC%EC%A0%91_%EC%9D%B4%EC%9B%83_%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98

4) https://kkokkilkon.tistory.com/14





K-NN(최근접이웃) 알고리즘 End

BioinformaticsAndMe

+ Recent posts