1번째 줄: |
1번째 줄: |
| == 개요 == | | == 개요 == |
− | 케라스. 원래 시에노 엔진을 편리하게 사용하려 개발했으나, 이후 사용할 수 있는 엔진이 점차 늘어났다. 사용자가 인공지능을 쉽게 구현하는 데 도움을 주는 인터페이스 제공.
| |
| | | |
− | TensorFlow 등으로 코드를 작성하는 일은 쉽지 않다. 거쳐야 하는 과정도 많고. 텐서플로우 위에서 이를 직관적이고 간편하게 이용할 수 있게 해주는 도구이다.
| + | === 설치 === |
| + | 간단히 pip install keras를 통해 설치하거나.. 최근엔 텐서플로우를 설치하면 그 안에 설치되어 있다. 어차피 백엔드로 텐서플로우를 사용하는 경우가 많을테니.. 텐서플로우만 설치하면 된다. |
| | | |
− | 머신러닝 라이브러리인 Theano와 TensorFlow를 백엔드로 사용하는 라이브러리.
| + | ==== 설치 확인 ==== |
| + | <syntaxhighlight lang="python"> |
| + | import keras |
| + | print(keras.__version__) |
| + | </syntaxhighlight> |
| | | |
− | === 설치 === | + | == 데이터 처리 == |
| + | 데이터 입럭은 3가지 형태로 이루어진다. |
| + | |
| + | # 넘파이 배열. 일반적인 데이터과학에서 자주 사용되는 형태. |
| + | #:- 데이터 과학에서 pandas의 dataframe을 많이 사용하는데, 이를 넘파이의 ndarray로 변환하여야 사용할 수 있다. <code>train_x = df.values</code>형태로 ndarray 값을 얻을 수 있다. |
| + | # 텐서플로우의 데이터셋 오브젝트. 성능행상에 도움. |
| + | #:- 이미지 파일을 데이터셋화 : tf.keras.preprocessing.image_dataset_from_directory |
| + | #:- 텍스트 파일을 데이터셋화 : tf.keras.preprocessing.text_dataset_from_directory |
| + | #:- CSV 파일을 데이터셋화 : tf.data.experimental.make_csv_dataset |
| + | # 파이썬 제너레이터. |
| + | |
| + | https://keras.io/getting_started/intro_to_keras_for_engineers/ |
| + | 위 링크에 정규화, 텍스트 배열 등의 전략이 소개되어 있다. |
| + | |
| + | === 텐서플로우 데이터셋 오브젝트 예시 === |
| {| class="wikitable" | | {| class="wikitable" |
| !의도 | | !의도 |
12번째 줄: |
30번째 줄: |
| !방법 | | !방법 |
| |- | | |- |
− | |케라스 설치 | + | |이미지 |
− | |그냥 파이썬을 이용하는 경우. | + | | |
− | |pip install keras | + | |<syntaxhighlight lang="python"> |
| + | dataset = keras.preprocessing.image_dataset_from_directory( |
| + | 'path/to/main_directory', batch_size=64, image_size=(200, 200)) |
| + | |
| + | # For demonstration, iterate over the batches yielded by the dataset. |
| + | for data, labels in dataset: |
| + | print(data.shape) # (64, 200, 200, 3) |
| + | print(data.dtype) # float32 |
| + | print(labels.shape) # (64,) |
| + | print(labels.dtype) # int32 |
| + | </syntaxhighlight> |
| + | |- |
| + | |텍스트 |
| + | | |
| + | |<syntaxhighlight lang="python"> |
| + | dataset = keras.preprocessing.text_dataset_from_directory( |
| + | 'path/to/main_directory', batch_size=64) |
| + | |
| + | # For demonstration, iterate over the batches yielded by the dataset. |
| + | for data, labels in dataset: |
| + | print(data.shape) # (64,) |
| + | print(data.dtype) # string |
| + | print(labels.shape) # (64,) |
| + | print(labels.dtype) # int32 |
| + | </syntaxhighlight> |
| |- | | |- |
− | |conda사용 | + | |CSV |
− | |아나콘다를 설치하고 이를 이용해 설치하면 텐서플로 등의 엔진들도 자동으로 설치해준다. | + | | |
− | |conda install keras-gpu | + | |<syntaxhighlight lang="python"> |
− | conda install keras # gpu가 없는 경우.
| + | # Set Feature_B as label column |
| + | dataset = tf.data.experimental.make_csv_dataset( |
| + | filename, batch_size=2, label_name="Feature_B") |
| + | iterator = ds.as_numpy_iterator() |
| + | print(next(iterator)) |
| + | # prints (features, labels) tuple: |
| + | # (OrderedDict([('Feature_A', array([1, 2], dtype=int32))]), |
| + | # array([b'a', b'b'], dtype=object)) |
| + | </syntaxhighlight> |
| |} | | |} |
| | | |
51번째 줄: |
101번째 줄: |
| |- | | |- |
| |모듈 불러오기 | | |모듈 불러오기 |
− | |.layers : 각 계층을 만드는 모듈. | + | |layers : 각 계층을 만드는 모듈. |
| models : 각 레이어들을 연결하여 신경망모델을 만든 후 컴파일하고 학습시키는 역할. | | models : 각 레이어들을 연결하여 신경망모델을 만든 후 컴파일하고 학습시키는 역할. |
| |<syntaxhighlight lang="python"> | | |<syntaxhighlight lang="python"> |
− | from keras import layers. models | + | from keras import layers, models |
| </syntaxhighlight> | | </syntaxhighlight> |
| |- | | |- |
102번째 줄: |
152번째 줄: |
| | | | | |
| |} | | |} |
− | [[분류:딥러닝 라이브러리]] | + | |
| + | = 오버피팅 막기 = |
| + | |
| + | == 드롭아웃 == |
| + | <syntaxhighlight lang="python3"> |
| + | from keras import model, layers |
| + | |
| + | model = models.Sequential() |
| + | models.add(....) |
| + | models.add(layers.Dropout(0.5)) # 얼마의 비율로 드롭아웃을 실행할 것인가. |
| + | </syntaxhighlight>층 사이사이에 넣을 수 있다. |
| + | |
| + | == 가중치 규제 == |
| + | |
| + | === L2 규제 만들기 === |
| + | <syntaxhighlight lang="python3"> |
| + | from keras import model, layers, regularizers |
| + | |
| + | l2_model = models.Sequential() |
| + | l2_model.add(layers.Dense(16, kernel_regularizer=regularizers.l2(0.001), # 0.001은 가중치에 곱할 값. |
| + | activation='relu', input_shape=(10000,))) |
| + | l2_model.add(layers.Dense(16, kernel_regularizer=regularizers.l2(0.001), |
| + | activation='relu')) |
| + | l2_model.add(layers.Dense(1, activation='sigmoid')) |
| + | </syntaxhighlight> |
| + | |
| + | === L1 규제 만들기 === |
| + | <syntaxhighlight lang="python3"> |
| + | from keras import model, layers, regularizers |
| + | |
| + | l1_model = models.Sequential() |
| + | l1_model.add(layers.Dense(16, kernel_regularizer=regularizers.l1(0.0001), |
| + | activation='relu', input_shape=(10000,))) |
| + | l1_model.add(layers.Dense(16, kernel_regularizer=regularizers.l1(0.0001), |
| + | activation='relu')) |
| + | l1_model.add(layers.Dense(1, activation='sigmoid')) |
| + | </syntaxhighlight> |
| + | |
| + | === L1, L2 동시 사용 === |
| + | <syntaxhighlight lang="python3"> |
| + | l1l2_model = models.Sequential() |
| + | l1l2_model.add(layers.Dense(16, kernel_regularizer=regularizers.l1_l2(l1=0.0001, l2=0.0001), |
| + | activation='relu', input_shape=(10000,))) |
| + | l1l2_model.add(layers.Dense(16, kernel_regularizer=regularizers.l1_l2(l1=0.0001, l2=0.0001), |
| + | activation='relu')) |
| + | l1l2_model.add(layers.Dense(1, activation='sigmoid')) |
| + | </syntaxhighlight> |
| + | |
| + | == 원핫인코딩 == |
| + | <syntaxhighlight lang="python3"> |
| + | from keras.utils import to_categorical |
| + | |
| + | lables = to_categorical(lables) # 레이블의 1,2,3,4,5의 카테고리를 독립적인 (1,0,0,..) 따위로 변형한다. |
| + | </syntaxhighlight> |
| + | [[분류:Keras]] |