iT邦幫忙

2021 iThome 鐵人賽

DAY 26
0
AI & Data

Python 機器學習實驗室 ʘ ͜ʖ ʘ系列 第 26

[Python] CNN

昨天用了一般的NN來做影像分類,但其實同樣的情況用CNN會有效率很多,今天就來建立CNN再應用一次。

下載dataset和packages

import tensorflow as tf
from tensorflow import keras
fashion_mnist = keras.datasets.fashion_mnist
(X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()
X_train = (X_train / 255.0).reshape(60000, 28, 28, 1)
X_test = (X_test / 255.0).reshape(10000, 28, 28, 1)
class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
                   "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"]

開始建模,記得第一層layer要放input shape,layer中重要的參數有:

  1. filters:每層中filter的數量
  2. kernal_size:filter的寬度與長度,必須要是奇數
  3. strides: 步伐大小
  4. padding:是不是要處理邊界,一般來說設定都是 “same”,也就是要處理
model = keras.models.Sequential()
model.add(keras.layers.Conv2D(filters=7, kernel_size=5, strides=1, padding="same", activation="relu",input_shape=[28, 28, 1]))
model.add(keras.layers.MaxPool2D(pool_size=2))

model.add(keras.layers.Conv2D(filters=7, kernel_size=3, strides=1, padding="same", activation="relu"))
model.add(keras.layers.MaxPool2D(pool_size=2))

model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(50, activation="relu"))
model.add(keras.layers.Dense(50, activation="relu"))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Dense(10, activation="softmax"))


model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"])
print(model.summary())
history = model.fit(X_train, y_train, epochs=10, validation_split=0.1)
model.evaluate(X_test, y_test)

https://ithelp.ithome.com.tw/upload/images/20211010/20142004zqh5n1KKgq.png

[reference]
https://blog.csdn.net/zz2230633069/article/details/88544747
https://www.geeksforgeeks.org/keras-conv2d-class/
https://www.cnblogs.com/yjybupt/p/11646846.html
https://woj.app/6491.html


上一篇
[Python] 來自己建立一個Neural Network吧
下一篇
deep learning 能做什麼呢
系列文
Python 機器學習實驗室 ʘ ͜ʖ ʘ30

尚未有邦友留言

立即登入留言