Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

AI study/๋”ฅ๋Ÿฌ๋‹ ํ”„๋ ˆ์ž„์›Œํฌ

[keras] CNN ๋ชจ๋ธ ๊ตฌ์„ฑ ์‚ดํŽด๋ณด๊ธฐ

๊ฐ์ž ๐Ÿฅ” 2021. 3. 3. 21:09
๋ฐ˜์‘ํ˜•

๋‚ด๊ฐ€ ํ—ท๊ฐˆ๋ ค์„œ ์ •๋ฆฌ!

๋ชจ๋ธ ํ•˜๋‚˜๋ฅผ ์˜ˆ์‹œ๋กœ ๋“ค์–ด์„œ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์„ค๋ช…ํ•ด๋ณด๊ฒ ๋‹ค.

1. ๋ชจ๋ธ ์ƒ์„ฑ

model = models.Sequential()
  • keras์˜ Sequential ๋ชจ๋ธ ์‚ฌ์šฉ
    • ๊ณ„์ธต์„ ์„ ํ˜•์œผ๋กœ ์Œ“์€ ๋ชจ๋ธ์„ ์˜๋ฏธ

2. ์ธต (Layer) ์ถ”๊ฐ€

๋ชจ๋ธ ๊ตฌ์„ฑ

INPUT → ์ฝ˜๋ณผ๋ฃจ์…˜ ๋ ˆ์ด์–ด (Conv2D) → ReLU ํ•จ์ˆ˜ → ๋งฅ์Šค ํ’€๋ง ๋ ˆ์ด์–ด(MaxPooling2D)

 ์ฝ˜๋ณผ๋ฃจ์…˜ ๋ ˆ์ด์–ด (Conv2D) → ReLU ํ•จ์ˆ˜ → ๋งฅ์Šค ํ’€๋ง ๋ ˆ์ด์–ด(MaxPooling2D)

 ์ฝ˜๋ณผ๋ฃจ์…˜ ๋ ˆ์ด์–ด (Conv2D) → ์™„์ „์—ฐ๊ฒฐ๊ณ„์ธต (Dense) → softmaxํ•จ์ˆ˜  OUTPUT

 

model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28,28,1)))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
model.add(layers.MaxPooling2D((2,2)))
model.add(layers.Conv2D(64, (3,3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.summary()

 

  • model.add ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ํ•œ ์ธต์”ฉ ์Œ“์•„๊ฐ„๋‹ค.
  • Conv2D : ์ฝ˜๋ณผ๋ฃจ์…˜ ๋ ˆ์ด์–ด
    • ํŒŒ๋ผ๋ฏธํ„ฐ
      • Conv2D(filter=32, kernel_size = (3,3), activation = 'relu', input_shape = (28,28,1))
  • MaxPooling2D : ๋งฅ์Šค ํ’€๋ง ๋ ˆ์ด์–ด
    • ํŒŒ๋ผ๋ฏธํ„ฐ
      • MaxPooling2D((2,2))
      • strides ๊ฐ€ (2,2) ๋ผ๋Š” ๋œป
  • Flatten()
    • Dense์ธต์— ์ž…๋ ฅ๋˜๋ ค๋ฉด 1์ฐจ์›์˜ ๋ฐฐ์—ด์ด์–ด์•ผ ํ•˜๊ธฐ๋•Œ๋ฌธ์— Flatten()ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ 1์ฐจ์›๋ฐฐ์—ด๋กœ ๋งŒ๋“ค์–ด์ฃผ๋Š”๊ฒƒ
  • Dense : ์™„์ „ ์—ฐ๊ฒฐ NN ๋ ˆ์ด์–ด
    • ๋ชจ๋ธ์„ ์™„์„ฑํ•˜๋ ค๋ฉด ๋งˆ์ง€๋ง‰ ํ•ฉ์„ฑ๊ณฑ์ธต์˜ ํฌ๊ธฐ (3,3,64) ๋ฅผ ํ•˜๋‚˜ ์ด์ƒ์˜ Dense์ธต์— ์ฃผ์ž…ํ•ด์„œ ๋ถ„๋ฅ˜ ์ˆ˜ํ–‰ ํ•„์š”
    • Dense(64, activation = 'relu')
      • ์ถœ๋ ฅ๋…ธ๋“œ ๊ฐœ์ˆ˜ 64๊ฐœ, ํ™œ์„ฑํ™”ํ•จ์ˆ˜ relu ์‚ฌ์šฉ
    • Dense(10, activation = 'softmax')
      • ๋งˆ์ง€๋ง‰ ์ถœ๋ ฅ ๋…ธ๋“œ๋ฅผ 10๊ฐœ๋กœ ์ง€์ •ํ•˜๊ณ , softmax ํ•จ์ˆ˜๋ฅผ ์ตœ์ข… ํ™œ์„ฑํ™” ํ•จ์ˆ˜๋กœ ์‚ฌ์šฉ

3. model.fit ํ•จ์ˆ˜ ์ ์šฉ

model.fit(X_train, Y_train,
	 batch_size = batch_size,
         nb_epoch = nb_epoch,
         verbose = 2,
         validation_data = (X_test, Y_test))
  • model.fit ํŒŒ๋ผ๋ฏธํ„ฐ
    • x : ์ž…๋ ฅ๋ฐ์ดํ„ฐ
    • y : ๋ผ๋ฒจ (ํƒ€๊ฒŸ๊ฐ’)
    • batch_size : ๋ฐฐ์น˜ ํฌ๊ธฐ
    • nb_epoch : ํ•™์Šต epoch ํšŸ์ˆ˜
    • verbose : ๋กœ๊น… ์„ค์ •
      • 0: ์—†์Œ, 1: ํ”„๋กœ๊ทธ๋ž˜์Šค๋ฐ”, 2: epoch๋‹น
    • valication_data: (X,Y) ์˜ ๊ฒ€์ฆ๋ฐ์ดํ„ฐ
    • shuffle : ๊ฐ epoch๋งˆ๋‹ค ์ƒ˜ํ”Œ์„ ์„ž์„์ง€ ์—ฌ๋ถ€

4. model.evaluate ํ•จ์ˆ˜

model.evaluate(X_test,Y_test, verbose = 0)
  • model.evaluate ํŒŒ๋ผ๋ฏธํ„ฐ
    • x,y : ๊ฒ€์ฆ๋ฐ์ดํ„ฐ ์ž…๋ ฅ
    • batch_size : ๋ฐฐ์น˜ํฌ๊ธฐ
    • verbose : ์ถœ๋ ฅ๋ชจ๋“œ (0 or 1)
  • model.evaluate ๋ฆฌํ„ด๊ฐ’ (๊ฒฐ๊ณผ)
    • ๋ชจ๋ธ metrics๊ฐ€ ์—†๋‹ค๋ฉด : loss๊ฐ’์œผ๋กœ ์ถœ๋ ฅ
    • ๋ชจ๋ธ metrics๊ฐ€ ์žˆ๋‹ค๋ฉด : ๋ชฉ๋ก์œผ๋กœ ์ถœ๋ ฅ
๋ฐ˜์‘ํ˜•