티스토리 뷰
이미지 처리입니다.
합성곱에 대한 간단한 코드입니다.
CNN에 관해 설명이 잘 되어 있는 블로그가 있어 링크 남깁니다.
In [ ]:
Convolution Neural Network(CNN)¶
- cnn에 관한 설명은 아주 많습니다. 그중에 괜찮은 블로그가 있어 안내합니다.
01. Import¶
In [2]:
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
In [ ]:
02. Download and prepare the CIFAR10 dataset¶
In [3]:
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 170500096/170498071 [==============================] - 100s 1us/step 170508288/170498071 [==============================] - 100s 1us/step
In [ ]:
03. Verify the data¶
In [4]:
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i])
# The CIFAR labels happen to be arrays,
# which is why you need the extra index
plt.xlabel(class_names[train_labels[i][0]])
plt.show()
In [ ]:
03. Create the convolutional base¶
In [6]:
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
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'))
In [7]:
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 30, 30, 32) 896 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 15, 15, 32) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 13, 13, 64) 18496 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 6, 6, 64) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 4, 4, 64) 36928 ================================================================= Total params: 56,320 Trainable params: 56,320 Non-trainable params: 0 _________________________________________________________________
In [ ]:
Add Dense layers on top¶
- CIFAR has 10 output classes.
In [8]:
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
In [9]:
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 30, 30, 32) 896 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 15, 15, 32) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 13, 13, 64) 18496 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 6, 6, 64) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 4, 4, 64) 36928 _________________________________________________________________ flatten (Flatten) (None, 1024) 0 _________________________________________________________________ dense (Dense) (None, 64) 65600 _________________________________________________________________ dense_1 (Dense) (None, 10) 650 ================================================================= Total params: 122,570 Trainable params: 122,570 Non-trainable params: 0 _________________________________________________________________
In [ ]:
04. Compile and train the model¶
In [10]:
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
In [11]:
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
Epoch 1/10 1563/1563 [==============================] - 216s 132ms/step - loss: 1.5220 - accuracy: 0.4445 - val_loss: 1.3215 - val_accuracy: 0.5190 Epoch 2/10 1563/1563 [==============================] - 214s 137ms/step - loss: 1.1722 - accuracy: 0.5841 - val_loss: 1.0847 - val_accuracy: 0.6145 Epoch 3/10 1563/1563 [==============================] - 191s 122ms/step - loss: 1.0172 - accuracy: 0.6440 - val_loss: 0.9958 - val_accuracy: 0.6519 Epoch 4/10 1563/1563 [==============================] - 186s 119ms/step - loss: 0.9163 - accuracy: 0.6811 - val_loss: 0.9272 - val_accuracy: 0.6783 Epoch 5/10 1563/1563 [==============================] - 201s 129ms/step - loss: 0.8489 - accuracy: 0.7037 - val_loss: 0.8974 - val_accuracy: 0.6879 Epoch 6/10 1563/1563 [==============================] - 207s 132ms/step - loss: 0.7922 - accuracy: 0.7232 - val_loss: 0.9083 - val_accuracy: 0.6805 Epoch 7/10 1563/1563 [==============================] - 206s 132ms/step - loss: 0.7467 - accuracy: 0.7391 - val_loss: 0.9076 - val_accuracy: 0.6856 Epoch 8/10 1563/1563 [==============================] - 206s 132ms/step - loss: 0.7057 - accuracy: 0.7524 - val_loss: 0.8566 - val_accuracy: 0.7060 Epoch 9/10 1563/1563 [==============================] - 206s 132ms/step - loss: 0.6717 - accuracy: 0.7640 - val_loss: 0.8637 - val_accuracy: 0.7071 Epoch 10/10 1563/1563 [==============================] - 207s 132ms/step - loss: 0.6376 - accuracy: 0.7751 - val_loss: 0.8780 - val_accuracy: 0.6987
In [ ]:
05. Evaluate the model¶
In [12]:
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
313/313 - 13s - loss: 0.8780 - accuracy: 0.6987
In [14]:
plt.plot(history.history['loss'], label='loss')
plt.plot(history.history['val_loss'], label='val_loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.ylim([0, 2])
plt.legend(loc='upper right')
Out[14]:
<matplotlib.legend.Legend at 0xb139521700>
In [ ]:
'machineLearning > tensorflow' 카테고리의 다른 글
210720 tf_imageAugmentation (1) | 2021.07.21 |
---|---|
tf_imageTransferLearning (0) | 2021.07.15 |
tf_distributeCustomTraining (0) | 2021.07.11 |
tf_distributeKeras (0) | 2021.07.10 |
tf_customTraining (0) | 2021.07.09 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- programmers.co.kr
- 미분법
- 도함수
- LangChain
- streamlit
- multi modal
- 약수
- checkpoint
- LLM
- 미분
- GPT
- ChatGPT
- programmers
- TensorFlow
- RAG
- Python
- 챗봇
- AI_고교수학
- FewShot
- 텐서플로우
- 변화율
- 파이썬
- prompt
- Chatbot
- 로피탈정리
- 고등학교 수학
- image depict
- 프로그래머스
- 미분계수
- 랭체인
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함