當(dāng)前位置:
首頁(yè) >
Tensorflow2.x.x全卷积神经网络(CNN)
發(fā)布時(shí)間:2025/3/15
59
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Tensorflow2.x.x全卷积神经网络(CNN)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Tensorflow2.x.x全卷積神經(jīng)網(wǎng)絡(luò)(CNN)
本章節(jié)主要使用Tensorflow2.x.x來(lái)搭建CNN神經(jīng)網(wǎng)絡(luò)。
全卷積神經(jīng)網(wǎng)絡(luò)原理
引用小伙伴的原理,作者個(gè)人理解為卷積層提取特征而已,每一層提取的特征不一樣。所以如果需要對(duì)模型進(jìn)行改進(jìn)的話就可以從對(duì)高級(jí)特征和低級(jí)特征的提取進(jìn)行優(yōu)化。
實(shí)現(xiàn)1
使用CNN實(shí)現(xiàn)對(duì)MNIST數(shù)據(jù)集的分類,最后一層不使用Dense嘗試。
import tensorflow as tf # mnist數(shù)據(jù)集 from tensorflow.keras.datasets import mnist # Adam優(yōu)化器 from tensorflow.keras.optimizers import Adam # 交叉熵?fù)p失函數(shù),一般用于多分類 from tensorflow.keras.losses import CategoricalCrossentropy # 模型和網(wǎng)絡(luò)層 from tensorflow.keras import Model, layers# 批次大小 BATCH_SIZE = 128 # 迭代次數(shù) EPOCHS = 10 # 加載mnist的訓(xùn)練、測(cè)試數(shù)據(jù)集 train, test = mnist.load_data() # 數(shù)據(jù)集的預(yù)處理 @tf.function def preprocess(x, y):# 將x一維數(shù)據(jù)轉(zhuǎn)為3維灰度圖x = tf.reshape(x, [28, 28, 1])# 將x的范圍由[0, 255]為[0, 1]x = tf.image.convert_image_dtype(x, tf.float32)# 將y數(shù)字標(biāo)簽進(jìn)行獨(dú)熱編碼y = tf.one_hot(y, 10)# 返回處理后的x和yreturn x, y# 使用Dataset來(lái)減少內(nèi)存的使用 train = tf.data.Dataset.from_tensor_slices(train) # 對(duì)數(shù)據(jù)進(jìn)行預(yù)處理并且給定BATCH_SIZE train = train.map(preprocess).batch(BATCH_SIZE)# test數(shù)據(jù)集同理 test = tf.data.Dataset.from_tensor_slices(test) test = test.map(preprocess).batch(BATCH_SIZE)x = layers.Input(shape=(28, 28, 1)) # 輸入為x, 大小為 28*28*1 y = layers.Conv2D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu')(x) # 64核的卷積層 # 在conv2d和maxpool之間可以使用BatchNormalization來(lái)提升訓(xùn)練速度, 可自行百度BatchNormalization的用途 # y = layers.BatchNormalization(axis=3)(y, training=True) training為True則是訓(xùn)練模式,否則是推理模式 y = layers.MaxPooling2D(pool_size=(2, 2))(y) # 池化層 y = layers.Conv2D(filters=128, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 128核的卷積層 y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Conv2D(filters=256, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 256核的卷積層 y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Conv2D(filters=512, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 512核的卷積層 y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Conv2D(filters=10, kernel_size=3, strides=1, padding='same', activation='softmax')(y) # 10分類, 使用sotfmax激活 y = layers.Flatten()(y) # 由于是多維, 于是進(jìn)行扁平化# 創(chuàng)建模型 cnn = Model(x, y) # 打印模型 print(cnn.summary()) # 編譯模型,選擇優(yōu)化器、評(píng)估標(biāo)準(zhǔn)、損失函數(shù) cnn.compile(optimizer=Adam(learning_rate=1e-4), metrics=['acc'], loss=CategoricalCrossentropy()) # 這里使用初始學(xué)習(xí)率為1e-4的adam優(yōu)化器 # 進(jìn)行模型訓(xùn)練 history = cnn.fit(train, epochs=EPOCHS) # 測(cè)試集的評(píng)估 score = cnn.evaluate(test) # 打印評(píng)估成績(jī) print('loss: {0}, acc: {1}'.format(score[0], score[1])) # loss: 0.04622650425310123, acc: 0.9848999977111816# 繪制訓(xùn)練過(guò)程中每個(gè)epoch的loss和acc的折線圖 import matplotlib.pyplot as plt # history對(duì)象中有history字典, 字典中存儲(chǔ)著“損失”和“評(píng)估標(biāo)準(zhǔn)” epochs = range(EPOCHS) fig = plt.figure(figsize=(15, 5), dpi=100)ax1 = fig.add_subplot(1, 2, 1) ax1.plot(epochs, history.history['loss']) ax1.set_title('loss graph') ax1.set_xlabel('epochs') ax1.set_ylabel('loss val')ax2 = fig.add_subplot(1, 2, 2) ax2.plot(epochs, history.history['acc']) ax2.set_title('acc graph') ax2.set_xlabel('epochs') ax2.set_ylabel('acc val')fig.show()模型結(jié)構(gòu):
結(jié)果:
實(shí)現(xiàn)2
使用CNN實(shí)現(xiàn)對(duì)MNIST數(shù)據(jù)集的分類,最后一層使用Dense嘗試。
import tensorflow as tf # mnist數(shù)據(jù)集 from tensorflow.keras.datasets import mnist # Adam優(yōu)化器 from tensorflow.keras.optimizers import Adam # 交叉熵?fù)p失函數(shù),一般用于多分類 from tensorflow.keras.losses import CategoricalCrossentropy # 模型和網(wǎng)絡(luò)層 from tensorflow.keras import Model, layers# 批次大小 BATCH_SIZE = 128 # 迭代次數(shù) EPOCHS = 10 # 加載mnist的訓(xùn)練、測(cè)試數(shù)據(jù)集 train, test = mnist.load_data() # 數(shù)據(jù)集的預(yù)處理 @tf.function def preprocess(x, y):# 將x一維數(shù)據(jù)轉(zhuǎn)為3維灰度圖x = tf.reshape(x, [28, 28, 1])# 將x的范圍由[0, 255]為[0, 1]x = tf.image.convert_image_dtype(x, tf.float32)# 將y數(shù)字標(biāo)簽進(jìn)行獨(dú)熱編碼y = tf.one_hot(y, 10)# 返回處理后的x和yreturn x, y# 使用Dataset來(lái)減少內(nèi)存的使用 train = tf.data.Dataset.from_tensor_slices(train) # 對(duì)數(shù)據(jù)進(jìn)行預(yù)處理并且給定BATCH_SIZE train = train.map(preprocess).batch(BATCH_SIZE)# test數(shù)據(jù)集同理 test = tf.data.Dataset.from_tensor_slices(test) test = test.map(preprocess).batch(BATCH_SIZE)x = layers.Input(shape=(28, 28, 1)) # 輸入為x, 大小為 28*28*1 y = layers.Conv2D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu')(x) # 64核的卷積層 # 在conv2d和maxpool之間可以使用BatchNormalization來(lái)提升訓(xùn)練速度, 可自行百度BatchNormalization的用途 # y = layers.BatchNormalization(axis=3)(y, training=True) training為True則是訓(xùn)練模式,否則是推理模式 y = layers.MaxPooling2D(pool_size=(2, 2))(y) # 池化層 y = layers.Conv2D(filters=128, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 128核的卷積層 y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Conv2D(filters=256, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 256核的卷積層 y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Conv2D(filters=512, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 512核的卷積層 y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Flatten()(y) # 由于是多維, 于是進(jìn)行扁平化 y = layers.Dense(10, activation='softmax')(y) # 10分類, 使用sotfmax激活# 創(chuàng)建模型 cnn = Model(x, y) # 打印模型 print(cnn.summary()) # 編譯模型,選擇優(yōu)化器、評(píng)估標(biāo)準(zhǔn)、損失函數(shù) cnn.compile(optimizer=Adam(learning_rate=1e-4), metrics=['acc'], loss=CategoricalCrossentropy()) # 這里使用初始學(xué)習(xí)率為1e-4的adam優(yōu)化器 # 進(jìn)行模型訓(xùn)練 history = cnn.fit(train, epochs=EPOCHS) # 測(cè)試集的評(píng)估 score = cnn.evaluate(test) # 打印評(píng)估成績(jī) print('loss: {0}, acc: {1}'.format(score[0], score[1])) # loss: 0.035550699669444456, acc: 0.9883999824523926# 繪制訓(xùn)練過(guò)程中每個(gè)epoch的loss和acc的折線圖 import matplotlib.pyplot as plt # history對(duì)象中有history字典, 字典中存儲(chǔ)著“損失”和“評(píng)估標(biāo)準(zhǔn)” epochs = range(EPOCHS) fig = plt.figure(figsize=(15, 5), dpi=100)ax1 = fig.add_subplot(1, 2, 1) ax1.plot(epochs, history.history['loss']) ax1.set_title('loss graph') ax1.set_xlabel('epochs') ax1.set_ylabel('loss val')ax2 = fig.add_subplot(1, 2, 2) ax2.plot(epochs, history.history['acc']) ax2.set_title('acc graph') ax2.set_xlabel('epochs') ax2.set_ylabel('acc val')fig.show()模型結(jié)構(gòu):
結(jié)果如下:
使用Dense對(duì)比
可以看出使用Dense的準(zhǔn)確率將高一些,并且從折線圖可以看出使用Dense訓(xùn)練下降會(huì)比較快。
與ANN對(duì)比
cnn的準(zhǔn)確率比ANN高了一些。卷積可以很好的提取特征并且相對(duì)ANN而言不容易過(guò)擬合。
使用BatchNormalization層優(yōu)化卷積網(wǎng)絡(luò)的實(shí)現(xiàn)
使用BatchNormalization可以有效提高訓(xùn)練速度和準(zhǔn)確度。
import tensorflow as tf # mnist數(shù)據(jù)集 from tensorflow.keras.datasets import mnist # Adam優(yōu)化器 from tensorflow.keras.optimizers import Adam # 交叉熵?fù)p失函數(shù),一般用于多分類 from tensorflow.keras.losses import CategoricalCrossentropy # 模型和網(wǎng)絡(luò)層 from tensorflow.keras import Model, layers# 批次大小 BATCH_SIZE = 128 # 迭代次數(shù) EPOCHS = 10 # 加載mnist的訓(xùn)練、測(cè)試數(shù)據(jù)集 train, test = mnist.load_data() # 數(shù)據(jù)集的預(yù)處理 @tf.function def preprocess(x, y):# 將x一維數(shù)據(jù)轉(zhuǎn)為3維灰度圖x = tf.reshape(x, [28, 28, 1])# 將x的范圍由[0, 255]為[0, 1]x = tf.image.convert_image_dtype(x, tf.float32)# 將y數(shù)字標(biāo)簽進(jìn)行獨(dú)熱編碼y = tf.one_hot(y, 10)# 返回處理后的x和yreturn x, y# 使用Dataset來(lái)減少內(nèi)存的使用 train = tf.data.Dataset.from_tensor_slices(train) # 對(duì)數(shù)據(jù)進(jìn)行預(yù)處理并且給定BATCH_SIZE train = train.map(preprocess).batch(BATCH_SIZE)# test數(shù)據(jù)集同理 test = tf.data.Dataset.from_tensor_slices(test) test = test.map(preprocess).batch(BATCH_SIZE)x = layers.Input(shape=(28, 28, 1)) # 輸入為x, 大小為 28*28*1 y = layers.Conv2D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu')(x) # 64核的卷積層 # 在conv2d和maxpool之間可以使用BatchNormalization來(lái)提升訓(xùn)練速度, 可自行百度BatchNormalization的用途 y = layers.BatchNormalization(axis=3)(y, training=True) y = layers.MaxPooling2D(pool_size=(2, 2))(y) # 池化層 y = layers.Conv2D(filters=128, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 128核的卷積層 y = layers.BatchNormalization(axis=3)(y, training=True) y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Conv2D(filters=256, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 256核的卷積層 y = layers.BatchNormalization(axis=3)(y, training=True) y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Conv2D(filters=512, kernel_size=3, strides=1, padding='same', activation='relu')(y) # 512核的卷積層 y = layers.BatchNormalization(axis=3)(y, training=True) y = layers.MaxPooling2D(pool_size=(2, 2))(y) y = layers.Flatten()(y) # 由于是多維, 于是進(jìn)行扁平化 y = layers.Dense(10, activation='softmax')(y) # 10分類, 使用sotfmax激活# 創(chuàng)建模型 cnn = Model(x, y) # 打印模型 print(cnn.summary()) # 編譯模型,選擇優(yōu)化器、評(píng)估標(biāo)準(zhǔn)、損失函數(shù) cnn.compile(optimizer=Adam(learning_rate=1e-4), metrics=['acc'], loss=CategoricalCrossentropy()) # 這里使用初始學(xué)習(xí)率為1e-4的adam優(yōu)化器 # 進(jìn)行模型訓(xùn)練 history = cnn.fit(train, epochs=EPOCHS) # 測(cè)試集的評(píng)估 score = cnn.evaluate(test) # 打印評(píng)估成績(jī) print('loss: {0}, acc: {1}'.format(score[0], score[1])) # loss: 0.035550699669444456, acc: 0.9883999824523926# 繪制訓(xùn)練過(guò)程中每個(gè)epoch的loss和acc的折線圖 import matplotlib.pyplot as plt # history對(duì)象中有history字典, 字典中存儲(chǔ)著“損失”和“評(píng)估標(biāo)準(zhǔn)” epochs = range(EPOCHS) fig = plt.figure(figsize=(15, 5), dpi=100)ax1 = fig.add_subplot(1, 2, 1) ax1.plot(epochs, history.history['loss']) ax1.set_title('loss graph') ax1.set_xlabel('epochs') ax1.set_ylabel('loss val')ax2 = fig.add_subplot(1, 2, 2) ax2.plot(epochs, history.history['acc']) ax2.set_title('acc graph') ax2.set_xlabel('epochs') ax2.set_ylabel('acc val')fig.show()模型結(jié)構(gòu):
結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的Tensorflow2.x.x全卷积神经网络(CNN)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2020年抖音美妆直播报告
- 下一篇: 卷积神经网络(CNN)及其实践