기본 콘텐츠로 건너뛰기

Python CNN(Convolutional Neural Network) 예제


예제
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, MaxPoolling2D
import numpy as pd
img_width = 225
img_height = 225
batch_size = 10
epochs = 50
num_classes = 2

# 파일에 저장된 이미지를 학습용 데이터로 로드한다
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    'images',seed=123,image_size=(img_height,img_width),batch_size=batch_size
)
# Found 20 files belonging to 2 classes.

class_names = train_ds.class_names # ['bottle', 'cup']

model = Sequential([
    tf.keras.layers.experimental.preprocessing.Rescaling(1.0/255),
    Conv2D(32,3,activation='relu'), # 총 필터의 갯수 32, 필터의 사이즈 3x3, 활성화 함수 relu 음수는 0 양수는 그대로
    MaxPooling2D(),
    Conv2D(32,3,activation='relu'),
    MaxPooling2D(),
    Conv2D(32,3,activation='relu'),
    MaxPooling2D(),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(num_classes, activation='softmax')
])
model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
             metrics=['accuracy'])
hist = model.fit(train_ds,epochs=epochs)
loss = hist.history['loss']
accuracy = hist.history['accuracy']
# 시각화
import matplotlib.pyplot as plt
plt.figure(figsize=(5,2))
plt.plot(loss, 'r--', label='loss')
plt.plot(accuracy, 'g', label='accuracy')
plt.xlabel('Epoch')
plt.ylabel('Error')
plt.legend()
plt.show()
# 테스트 이미지 준비
test_image_path = 'images_test/cup_test/r1ti21VgQf-5slrBHv4fAA.jpg'
img = tf.keras.preprocessing.image.load_img(test_image_path, target_size=(img_height,img_width))
# 신경망에 전달할 수 있는 데이터로 변환
img_array = tf.keras.preprocessing.image.img_to_array(img)
img_array.shape # (225, 225, 3)
img_array2 = tf.expand_dims(img_array, 0) # data, axis
pred = model.predict(img_array2) # [0.000014, 0.999986]
percent = np.max(pred)*100 # 99.99856948852539
idx = np.argmax(pred) # 1, 제일 큰 인덱스를 리턴
class_names[idx], f'{percent}%' # '('cup', '99.99856948852539%')

이 블로그의 인기 게시물

Python 인공신경망 추천 시스템(회귀)

예제 # 인공신경망을 이용한 추천 시스템 # - 순차형(Sequential) 신경망 생성법 # - 함수형(Functional) 신경망 생성법 # - 지금까지 나온 추천 방식 중에서 가장 좋은 성능 # - Regression 방식으로 분석가능 # - 영화의 평점 정보(userid, movieid, rating) # - 이용자는 영화에 대한 취향이 모두 다르다 # - 영화는 다양한 장르가 혼합되어 있다 # - 이용자는 자신의 취향에 맞는 영화에 높은 rating을 제시함 # - 어떤 이용자에게 어떤 장르의 영화를 추천할 것인가? # __call__() 함수를 가진 클래스는 파이썬 함수 callable(클래스)를 사용하면 True를 반환한다 from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Dense, Embedding, Input input = Input(shape=(1,)) # 함수형 신경망 생성법 hidden1 = Dense(2, activation='relu')(input) # Dense(2, activation='relu')__call__() hidden2 = Dense(2, activation='relu')(hidden1) # callable.object callable(Dense) # __call__ 함수가 있으면 True, 없으면 False # Using Functional API from keras.models import Sequential from keras.layers import * model = Sequential() model.add(Input(shape=(3,))) # Input tensor model.add(Dense(4)) # hidden layer 1 model.add(Dense(units=4)) # hidden layer 2 model.add(Dense(units=1)) # ou...

Blogger

코드 하이라이트 사이트 http://hilite.me/ 코드 <!-- 나만의 공간 --> <style id='daru_css' type='text/css'> .code {      overflow: auto;      height: 200px;      background-color: rgb(239,239,239);      border-radius: 10px;      padding: 5px 10px; } .code::-webkit-scrollbar-thumb {      background-color: grey;      border: 1px solid transparent;      border-radius: 10px;      background-clip: padding-box;   } .code::-webkit-scrollbar {      width: 15px; } </style> <!-- 나만의 공간 -->

Javascript on 함수

엔터키 감지하기 <input type="password" onkeypress="func(event)" /> function func(event) {      if(event.keyCode == 13) { // keyCode 13은 엔터이다           alert("엔터를 입력했습니다.");     }     if (event.tartget.value == 13) {          alert("엔터를 입력했습니다.");     } }