| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
- gameplay effect
- animation
- listen server
- 유니티
- 언리얼 엔진
- Unreal Engine
- 게임 개발
- gameplay ability system
- widget
- 보안
- ability task
- 게임개발
- gameplay tag
- linear regression
- photon fusion2
- CTF
- C++
- gas
- unity
- Replication
- os
- 언리얼엔진
- MAC
- stride
- Aegis
- attribute
- rpc
- local prediction
- UI
- Multiplay
- Today
- Total
Replicated
Keras CNN - Argumentation 본문
Image augmentation
- Image classification은 많은 양의 학습 데이터를 필요로 함
- 데이터 부족시 augmentation을 통해 데이터를 늘릴 수 있음
- 기존 데이터를 가공, 변형해서 새로운 데이터를 만드는 방식
from tensorflow.keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
datagen = ImageDataGenerator(
rotation_range=40, # 0~180
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255, # 픽셀값을 0~1 로 변환
shear_range=0.2, # shearing transformations
zoom_range=0.2, # randomly zooming
horizontal_flip=True, # randomly flipping
fill_mode='nearest') # filling in newly created pixels
img = load_img('./image.jpg')
x = img_to_array(img)
x = x.reshape((1,) + x.shape)
i = 0
for batch in datagen.flow(x, batch_size=1,
save_to_dir='./new/', save_prefix='new',
save_format='jpeg'):
i += 1
if i > 30:
break # or for working infinitely
이미지 로드하고 agumentation
rotation_range=40 : 최대 40도까지 무작위로 회전
width_shift_range=0.2 : 이미지 가로 방향으로 20%까지 이동
height_shift_range=0.2 : 세로 방향으로 20%까지 이동
rescale=1./255 : 픽셀값(0~255)을 0~1 사이로 정규화 (1/255 곱함)
shear_range=0.2 : 이미지의 기울이기(shearing) 변환 적용 (최대 0.2 라디안)
zoom_range=0.2 : 20% 범위 내에서 임의로 확대/축소
horizontal_flip=True : 이미지를 좌우로 무작위 반전
fill_mode='nearest' : 회전·이동 시 생기는 빈 공간을 가장 가까운 픽셀로 채움

생성 결과
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
img_rows=28
img_cols=28
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train, X_test = X_train / 255.0, X_test / 255.0
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
datagen = ImageDataGenerator(
zoom_range=0.2,
shear_range=0.2,
rotation_range=10,
fill_mode='nearest',
validation_split = 0.2
)
datagen.fit(X_train)
train_gen = datagen.flow(X_train, y_train, batch_size=60)
seed = 100
np.random.seed(seed)
num_classes = 10
MNIST 데이터 증강 예시

제네레이터에 fit은 통계값 계산해두는 거
일부 옵션들 중 미리 계산이 필요한게 있는데, 사실 위 예시엔 없다

학습할 때마다 60개씩 꺼내서 쓰도록 미리 만들어둠
def cnn_model():
model = Sequential()
model.add(Conv2D(64, kernel_size=(5, 5),
padding='valid',
strides=(1, 1),
input_shape=(img_rows, img_cols, 1),
activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(127, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
CNN 정의
model = cnn_model()
disp = model.fit(train_gen,
validation_data=(X_test, y_test),
epochs=10,
batch_size=200,
verbose=1)
scores = model.evaluate(X_test, y_test, verbose=0)
print("loss: %.2f" % scores[0])
print("acc: %.2f" % scores[1])
plt.plot(disp.history['accuracy'])
plt.plot(disp.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
학습 및 평가
* 배치 사이즈 200이라 되어 있지만 traingen이 꺼내주는게 60이라 실 배치 사이즈는 60임

그래서 스탭 당 60000 / 60 = 1000이라 1000번
batch_size 인자는 무시됨

'학부 > 딥러닝' 카테고리의 다른 글
| 자연어 처리 : Word representation (0) | 2025.12.07 |
|---|---|
| 전이 학습 (Transfer Learning) (0) | 2025.12.07 |
| Keras CNN - MNIST (0) | 2025.10.25 |
| Keras CNN (0) | 2025.10.25 |
| Keras - MNIST (0) | 2025.10.25 |