바뀜

3,954 바이트 추가됨 ,  2022년 1월 7일 (금) 06:39
잔글
1번째 줄: 1번째 줄:  +
== 개요 ==
 +
 +
=== 설치 ===
 +
간단히 pip install keras를 통해  설치하거나.. 최근엔 텐서플로우를 설치하면 그 안에 설치되어 있다. 어차피 백엔드로 텐서플로우를 사용하는 경우가 많을테니.. 텐서플로우만 설치하면 된다.
 +
 +
==== 설치 확인 ====
 +
<syntaxhighlight lang="python">
 +
import keras
 +
print(keras.__version__)
 +
</syntaxhighlight>
 +
 
== 데이터 처리 ==
 
== 데이터 처리 ==
 
데이터 입럭은 3가지 형태로 이루어진다.
 
데이터 입럭은 3가지 형태로 이루어진다.
    
# 넘파이 배열. 일반적인 데이터과학에서 자주 사용되는 형태.
 
# 넘파이 배열. 일반적인 데이터과학에서 자주 사용되는 형태.
 +
#:- 데이터 과학에서 pandas의 dataframe을 많이 사용하는데, 이를 넘파이의 ndarray로 변환하여야 사용할 수 있다. <code>train_x = df.values</code>형태로 ndarray 값을 얻을 수 있다.
 
# 텐서플로우의 데이터셋 오브젝트. 성능행상에 도움.
 
# 텐서플로우의 데이터셋 오브젝트. 성능행상에 도움.
 
#:- 이미지 파일을 데이터셋화 : tf.keras.preprocessing.image_dataset_from_directory
 
#:- 이미지 파일을 데이터셋화 : tf.keras.preprocessing.image_dataset_from_directory
11번째 줄: 23번째 줄:  
https://keras.io/getting_started/intro_to_keras_for_engineers/
 
https://keras.io/getting_started/intro_to_keras_for_engineers/
 
위 링크에 정규화, 텍스트 배열 등의 전략이 소개되어 있다.
 
위 링크에 정규화, 텍스트 배열 등의 전략이 소개되어 있다.
 +
 +
=== 텐서플로우 데이터셋 오브젝트 예시 ===
 +
{| class="wikitable"
 +
!의도
 +
!설명
 +
!방법
 +
|-
 +
|이미지
 +
|
 +
|<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>
 +
|-
 +
|CSV
 +
|
 +
|<syntaxhighlight lang="python">
 +
# 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>
 +
|}
    
= 사용 =
 
= 사용 =
41번째 줄: 101번째 줄:  
|-
 
|-
 
|모듈 불러오기
 
|모듈 불러오기
|.layers : 각 계층을 만드는 모듈.
+
|layers : 각 계층을 만드는 모듈.
 
models : 각 레이어들을 연결하여 신경망모델을 만든 후 컴파일하고 학습시키는 역할.
 
models : 각 레이어들을 연결하여 신경망모델을 만든 후 컴파일하고 학습시키는 역할.
 
|<syntaxhighlight lang="python">
 
|<syntaxhighlight lang="python">
from keras import layers. models
+
from keras import layers, models
 
</syntaxhighlight>
 
</syntaxhighlight>
 
|-
 
|-
92번째 줄: 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]]
 
[[분류:Keras]]