"Keras"의 두 판 사이의 차이
둘러보기로 가기
검색하러 가기
잔글 (→설치) |
|||
(사용자 2명의 중간 판 17개는 보이지 않습니다) | |||
1번째 줄: | 1번째 줄: | ||
== 개요 == | == 개요 == | ||
− | |||
− | + | === 설치 === | |
+ | 간단히 pip install keras를 통해 설치하거나.. 최근엔 텐서플로우를 설치하면 그 안에 설치되어 있다. 어차피 백엔드로 텐서플로우를 사용하는 경우가 많을테니.. 텐서플로우만 설치하면 된다. | ||
+ | |||
+ | ==== 설치 확인 ==== | ||
+ | <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번째 줄: | ||
!방법 | !방법 | ||
|- | |- | ||
− | | | + | |이미지 |
− | | | + | | |
− | | | + | |<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> | ||
|} | |} | ||
42번째 줄: | 92번째 줄: | ||
x = csv[['열1', '열2']].as_matrix() # 넘파이배열로 바꾸어 x에 담는다. | x = csv[['열1', '열2']].as_matrix() # 넘파이배열로 바꾸어 x에 담는다. | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |} | ||
+ | |||
+ | === 신경망 모델 제작 === | ||
+ | {| class="wikitable" | ||
+ | !의도 | ||
+ | !설명 | ||
+ | !방법 | ||
+ | |- | ||
+ | |모듈 불러오기 | ||
+ | |layers : 각 계층을 만드는 모듈. | ||
+ | models : 각 레이어들을 연결하여 신경망모델을 만든 후 컴파일하고 학습시키는 역할. | ||
+ | |<syntaxhighlight lang="python"> | ||
+ | from keras import layers, models | ||
+ | </syntaxhighlight> | ||
+ | |- | ||
+ | |신경망 디자인 | ||
+ | |ANN에 필요한 파라미터를 정해준다. | ||
+ | {| class="wikitable" | ||
+ | !인수 | ||
+ | !설명 | ||
+ | |- | ||
+ | |Nin | ||
+ | |입력계층 노드 수 | ||
+ | |- | ||
+ | |Nh | ||
+ | |은닉계층 노드 수 | ||
+ | |- | ||
+ | |number_of_class | ||
+ | |출력값이 가질 클래스 수 | ||
+ | |- | ||
+ | |Nout | ||
+ | |출력노드 수 | ||
+ | |} | ||
+ | | | ||
+ | |- | ||
+ | |모델링 | ||
+ | |다양한 방법으로 모델링. | ||
+ | | | ||
|} | |} | ||
64번째 줄: | 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]] |
2022년 1월 7일 (금) 06:39 기준 최신판
1 개요[편집 | 원본 편집]
1.1 설치[편집 | 원본 편집]
간단히 pip install keras를 통해 설치하거나.. 최근엔 텐서플로우를 설치하면 그 안에 설치되어 있다. 어차피 백엔드로 텐서플로우를 사용하는 경우가 많을테니.. 텐서플로우만 설치하면 된다.
1.1.1 설치 확인[편집 | 원본 편집]
import keras
print(keras.__version__)
2 데이터 처리[편집 | 원본 편집]
데이터 입럭은 3가지 형태로 이루어진다.
- 넘파이 배열. 일반적인 데이터과학에서 자주 사용되는 형태.
- - 데이터 과학에서 pandas의 dataframe을 많이 사용하는데, 이를 넘파이의 ndarray로 변환하여야 사용할 수 있다.
train_x = df.values
형태로 ndarray 값을 얻을 수 있다.
- - 데이터 과학에서 pandas의 dataframe을 많이 사용하는데, 이를 넘파이의 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/ 위 링크에 정규화, 텍스트 배열 등의 전략이 소개되어 있다.
2.1 텐서플로우 데이터셋 오브젝트 예시[편집 | 원본 편집]
의도 | 설명 | 방법 |
---|---|---|
이미지 | 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
| |
텍스트 | 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
| |
CSV | # 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))
|
3 사용[편집 | 원본 편집]
3.1 데이터 사전작업[편집 | 원본 편집]
의도 | 설명 | 방법 |
---|---|---|
정규화 | 일반적으로 데이터는 0~1 사이로 정규화한다. | |
csv 가져오기 | csv를 넘파이 배열화 해야 한다. | import pandas
csv = pd.read_csv("경로.csv") # 판다스를 이용하여 불러온다.
x = csv[['열1', '열2']].as_matrix() # 넘파이배열로 바꾸어 x에 담는다.
|
3.1.1 신경망 모델 제작[편집 | 원본 편집]
의도 | 설명 | 방법 | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
모듈 불러오기 | layers : 각 계층을 만드는 모듈.
models : 각 레이어들을 연결하여 신경망모델을 만든 후 컴파일하고 학습시키는 역할. |
from keras import layers, models
| ||||||||||
신경망 디자인 | ANN에 필요한 파라미터를 정해준다.
|
|||||||||||
모델링 | 다양한 방법으로 모델링. |
3.2 기타 활용[편집 | 원본 편집]
3.2.1 샘플데이터[편집 | 원본 편집]
의도 | 설명 | 방법 |
---|---|---|
손글씨 샘플 | mnist의 샘플데이터를 가져온다. | from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
|
4 오버피팅 막기[편집 | 원본 편집]
4.1 드롭아웃[편집 | 원본 편집]
from keras import model, layers
model = models.Sequential()
models.add(....)
models.add(layers.Dropout(0.5)) # 얼마의 비율로 드롭아웃을 실행할 것인가.
층 사이사이에 넣을 수 있다.
4.2 가중치 규제[편집 | 원본 편집]
4.2.1 L2 규제 만들기[편집 | 원본 편집]
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'))
4.2.2 L1 규제 만들기[편집 | 원본 편집]
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'))
4.2.3 L1, L2 동시 사용[편집 | 원본 편집]
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'))
4.3 원핫인코딩[편집 | 원본 편집]
from keras.utils import to_categorical
lables = to_categorical(lables) # 레이블의 1,2,3,4,5의 카테고리를 독립적인 (1,0,0,..) 따위로 변형한다.