溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

發(fā)布時間:2021-10-18 15:13:33 來源:億速云 閱讀:183 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程”吧!

目錄
  • 基礎(chǔ)理論

  • 一、訓(xùn)練CNN卷積神經(jīng)網(wǎng)絡(luò)

    • 1、載入數(shù)據(jù)

    • 2、改變數(shù)據(jù)維度

    • 3、歸一化

    • 4、獨熱編碼

    • 5、搭建CNN卷積神經(jīng)網(wǎng)絡(luò)

      • 5-1、第一層:第一個卷積層

      • 5-2、第二層:第二個卷積層

      • 5-3、扁平化

      • 5-4、第三層:第一個全連接層

      • 5-5、第四層:第二個全連接層(輸出層)

    • 6、編譯

      • 7、訓(xùn)練

        • 8、保存模型

          • 代碼

          • 二、識別自己的手寫數(shù)字(圖像)

            • 1、載入數(shù)據(jù)

              • 2、載入訓(xùn)練好的模型

                • 3、載入自己寫的數(shù)字圖片并設(shè)置大小

                  • 4、轉(zhuǎn)灰度圖

                    • 5、轉(zhuǎn)黑底白字、數(shù)據(jù)歸一化

                      • 6、轉(zhuǎn)四維數(shù)據(jù)

                        • 7、預(yù)測

                          • 8、顯示圖像

                            • 效果展示

                              • 代碼

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              基礎(chǔ)理論

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              第一層:卷積層。

                              第二層:卷積層。

                              第三層:全連接層。

                              第四層:輸出層。

                              圖中原始的手寫數(shù)字的圖片是一張 28×28 的圖片,并且是黑白的,所以圖片的通道數(shù)是1,輸入數(shù)據(jù)是 28×28×1 的數(shù)據(jù),如果是彩色圖片,圖片的通道數(shù)就為 3。
                              該網(wǎng)絡(luò)結(jié)構(gòu)是一個 4 層的卷積神經(jīng)網(wǎng)絡(luò)(計算神經(jīng)網(wǎng)絡(luò)層數(shù)的時候,有權(quán)值的才算是一層,池化層就不能單獨算一層)(池化的計算是在卷積層中進行的)。
                              對多張?zhí)卣鲌D求卷積,相當(dāng)于是同時對多張?zhí)卣鲌D進行特征提取。

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              特征圖數(shù)量越多說明卷積網(wǎng)絡(luò)提取的特征數(shù)量越多,如果特征圖數(shù)量設(shè)置得太少容易出現(xiàn)欠擬合,如果特征圖數(shù)量設(shè)置得太多容易出現(xiàn)過擬合,所以需要設(shè)置為合適的數(shù)值。

                              一、訓(xùn)練CNN卷積神經(jīng)網(wǎng)絡(luò)

                              1、載入數(shù)據(jù)

                              # 1、載入數(shù)據(jù)
                              mnist = tf.keras.datasets.mnist
                              (train_data, train_target), (test_data, test_target) = mnist.load_data()

                              2、改變數(shù)據(jù)維度

                              注:在TensorFlow中,在做卷積的時候需要把數(shù)據(jù)變成4維的格式。
                              這4個維度分別是:數(shù)據(jù)數(shù)量,圖片高度,圖片寬度,圖片通道數(shù)。

                              # 3、歸一化(有助于提升訓(xùn)練速度)
                              train_data = train_data/255.0
                              test_data = test_data/255.0

                              3、歸一化

                              # 3、歸一化(有助于提升訓(xùn)練速度)
                              train_data = train_data/255.0
                              test_data = test_data/255.0

                              4、獨熱編碼

                              # 4、獨熱編碼
                              train_target = tf.keras.utils.to_categorical(train_target, num_classes=10)
                              test_target = tf.keras.utils.to_categorical(test_target, num_classes=10)    #10種結(jié)果

                              5、搭建CNN卷積神經(jīng)網(wǎng)絡(luò)

                              model = Sequential()
                              5-1、第一層:第一個卷積層

                              第一個卷積層:卷積層+池化層。

                              # 5-1、第一層:卷積層+池化層
                              # 第一個卷積層
                              model.add(Convolution2D(input_shape = (28,28,1), filters = 32, kernel_size = 5, strides = 1, padding = 'same', activation = 'relu'))
                              #         卷積層         輸入數(shù)據(jù)                  濾波器數(shù)量      卷積核大小        步長          填充數(shù)據(jù)(same padding)  激活函數(shù)
                              # 第一個池化層 # pool_size
                              model.add(MaxPooling2D(pool_size = 2, strides = 2, padding = 'same',))
                              #         池化層(最大池化) 池化窗口大小   步長          填充方式
                              5-2、第二層:第二個卷積層
                              # 5-2、第二層:卷積層+池化層
                              # 第二個卷積層
                              model.add(Convolution2D(64, 5, strides=1, padding='same', activation='relu'))
                              # 64:濾波器個數(shù)      5:卷積窗口大小
                              # 第二個池化層
                              model.add(MaxPooling2D(2, 2, 'same'))
                              5-3、扁平化

                              把(64,7,7,64)數(shù)據(jù)變成:(64,7*7*64)。

                              flatten扁平化:

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              # 5-3、扁平化 (相當(dāng)于把(64,7,7,64)數(shù)據(jù)->(64,7*7*64))
                              model.add(Flatten())
                              5-4、第三層:第一個全連接層
                              # 5-4、第三層:第一個全連接層
                              model.add(Dense(1024,activation = 'relu'))
                              model.add(Dropout(0.5))
                              5-5、第四層:第二個全連接層(輸出層)
                              # 5-5、第四層:第二個全連接層(輸出層)
                              model.add(Dense(10, activation='softmax'))
                              # 10:輸出神經(jīng)元個數(shù)

                              6、編譯

                              設(shè)置優(yōu)化器、損失函數(shù)、標(biāo)簽。

                              # 6、編譯
                              model.compile(optimizer=Adam(lr=1e-4), loss='categorical_crossentropy', metrics=['accuracy'])
                              #            優(yōu)化器(adam)               損失函數(shù)(交叉熵?fù)p失函數(shù))            標(biāo)簽

                              7、訓(xùn)練

                              # 7、訓(xùn)練
                              model.fit(train_data, train_target, batch_size=64, epochs=10, validation_data=(test_data, test_target))

                              8、保存模型

                              # 8、保存模型
                              model.save('mnist.h6')

                              效果:

                              Epoch 1/10
                              938/938 [==============================] - 142s 151ms/step - loss: 0.3319 - accuracy: 0.9055 - val_loss: 0.0895 - val_accuracy: 0.9728
                              Epoch 2/10
                              938/938 [==============================] - 158s 169ms/step - loss: 0.0911 - accuracy: 0.9721 - val_loss: 0.0515 - val_accuracy: 0.9830
                              Epoch 3/10
                              938/938 [==============================] - 146s 156ms/step - loss: 0.0629 - accuracy: 0.9807 - val_loss: 0.0389 - val_accuracy: 0.9874
                              Epoch 4/10
                              938/938 [==============================] - 120s 128ms/step - loss: 0.0498 - accuracy: 0.9848 - val_loss: 0.0337 - val_accuracy: 0.9889
                              Epoch 5/10
                              938/938 [==============================] - 119s 127ms/step - loss: 0.0424 - accuracy: 0.9869 - val_loss: 0.0273 - val_accuracy: 0.9898
                              Epoch 6/10
                              938/938 [==============================] - 129s 138ms/step - loss: 0.0338 - accuracy: 0.9897 - val_loss: 0.0270 - val_accuracy: 0.9907
                              Epoch 7/10
                              938/938 [==============================] - 124s 133ms/step - loss: 0.0302 - accuracy: 0.9904 - val_loss: 0.0234 - val_accuracy: 0.9917
                              Epoch 8/10
                              938/938 [==============================] - 132s 140ms/step - loss: 0.0264 - accuracy: 0.9916 - val_loss: 0.0240 - val_accuracy: 0.9913
                              Epoch 9/10
                              938/938 [==============================] - 139s 148ms/step - loss: 0.0233 - accuracy: 0.9926 - val_loss: 0.0235 - val_accuracy: 0.9919
                              Epoch 10/10
                              938/938 [==============================] - 139s 148ms/step - loss: 0.0208 - accuracy: 0.9937 - val_loss: 0.0215 - val_accuracy: 0.9924

                              可以發(fā)現(xiàn)訓(xùn)練10次以后,效果達到了99%+,還是比較不錯的。

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              代碼

                              # 手寫數(shù)字識別 -- CNN神經(jīng)網(wǎng)絡(luò)訓(xùn)練
                              import os
                              os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
                               import tensorflow as tf
                              from tensorflow.keras.models import Sequential
                              from tensorflow.keras.layers import Dense,Dropout,Convolution2D,MaxPooling2D,Flatten
                              from tensorflow.keras.optimizers import Adam
                               # 1、載入數(shù)據(jù)
                              mnist = tf.keras.datasets.mnist
                              (train_data, train_target), (test_data, test_target) = mnist.load_data()
                              # 2、改變數(shù)據(jù)維度
                              train_data = train_data.reshape(-1, 28, 28, 1)
                              test_data = test_data.reshape(-1, 28, 28, 1)
                              # 注:在TensorFlow中,在做卷積的時候需要把數(shù)據(jù)變成4維的格式
                              # 這4個維度分別是:數(shù)據(jù)數(shù)量,圖片高度,圖片寬度,圖片通道數(shù) 
                              # 3、歸一化(有助于提升訓(xùn)練速度)
                              train_data = train_data/255.0
                              test_data = test_data/255.0 
                              # 4、獨熱編碼
                              train_target = tf.keras.utils.to_categorical(train_target, num_classes=10)
                              test_target = tf.keras.utils.to_categorical(test_target, num_classes=10)    #10種結(jié)果 
                              # 5、搭建CNN卷積神經(jīng)網(wǎng)絡(luò)
                              model = Sequential()
                              # 5-1、第一層:卷積層+池化層
                              # 第一個卷積層
                              model.add(Convolution2D(input_shape = (28,28,1), filters = 32, kernel_size = 5, strides = 1, padding = 'same', activation = 'relu'))
                              #         卷積層         輸入數(shù)據(jù)                  濾波器數(shù)量      卷積核大小        步長          填充數(shù)據(jù)(same padding)  激活函數(shù)
                              # 第一個池化層 # pool_size
                              model.add(MaxPooling2D(pool_size = 2, strides = 2, padding = 'same',))
                              #         池化層(最大池化) 池化窗口大小   步長          填充方式 
                              # 5-2、第二層:卷積層+池化層
                              # 第二個卷積層
                              model.add(Convolution2D(64, 5, strides=1, padding='same', activation='relu'))
                              # 64:濾波器個數(shù)      5:卷積窗口大小
                              # 第二個池化層
                              model.add(MaxPooling2D(2, 2, 'same')) 
                              # 5-3、扁平化 (相當(dāng)于把(64,7,7,64)數(shù)據(jù)->(64,7*7*64))
                              model.add(Flatten()) 
                              # 5-4、第三層:第一個全連接層
                              model.add(Dense(1024, activation = 'relu'))
                              model.add(Dropout(0.5)) 
                              # 5-5、第四層:第二個全連接層(輸出層)
                              model.add(Dense(10, activation='softmax'))
                              # 10:輸出神經(jīng)元個數(shù) 
                              # 6、編譯
                              model.compile(optimizer=Adam(lr=1e-4), loss='categorical_crossentropy', metrics=['accuracy'])
                              #            優(yōu)化器(adam)               損失函數(shù)(交叉熵?fù)p失函數(shù))            標(biāo)簽 
                              # 7、訓(xùn)練
                              model.fit(train_data, train_target, batch_size=64, epochs=10, validation_data=(test_data, test_target)) 
                              # 8、保存模型
                              model.save('mnist.h6')

                              二、識別自己的手寫數(shù)字(圖像)

                              1、載入數(shù)據(jù)

                              # 1、載入數(shù)據(jù)
                              mnist = tf.keras.datasets.mnist
                              (x_train, y_train), (x_test, y_test) = mnist.load_data()

                              數(shù)據(jù)集的圖片(之一):

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              2、載入訓(xùn)練好的模型

                              # 2、載入訓(xùn)練好的模型
                              model = load_model('mnist.h6')

                              3、載入自己寫的數(shù)字圖片并設(shè)置大小

                              # 3、載入自己寫的數(shù)字圖片并設(shè)置大小
                              img = Image.open('6.jpg')
                              # 設(shè)置大小(和數(shù)據(jù)集的圖片一致)
                              img = img.resize((28, 28))

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              4、轉(zhuǎn)灰度圖

                              # 4、轉(zhuǎn)灰度圖
                              gray = np.array(img.convert('L'))       #.convert('L'):轉(zhuǎn)灰度圖

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              可以發(fā)現(xiàn)和數(shù)據(jù)集中的白底黑字差別很大,所以我們把它反轉(zhuǎn)一下:

                              5、轉(zhuǎn)黑底白字、數(shù)據(jù)歸一化

                              MNIST數(shù)據(jù)集中的數(shù)據(jù)都是黑底白字,且取值在0~1之間。

                              # 5、轉(zhuǎn)黑底白字、數(shù)據(jù)歸一化
                              gray_inv = (255-gray)/255.0

                              6、轉(zhuǎn)四維數(shù)據(jù)

                              CNN神經(jīng)網(wǎng)絡(luò)預(yù)測需要四維數(shù)據(jù)。

                              # 6、轉(zhuǎn)四維數(shù)據(jù)(CNN預(yù)測需要)
                              image = gray_inv.reshape((1,28,28,1))

                              7、預(yù)測

                              # 7、預(yù)測
                              prediction = model.predict(image)           # 預(yù)測
                              prediction = np.argmax(prediction,axis=1)   # 找出最大值
                              print('預(yù)測結(jié)果:', prediction)

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              8、顯示圖像

                              # 8、顯示
                              # 設(shè)置plt圖表
                              f, ax = plt.subplots(3, 3, figsize=(7, 7))
                              # 顯示數(shù)據(jù)集圖像
                              ax[0][0].set_title('train_model')
                              ax[0][0].axis('off')
                              ax[0][0].imshow(x_train[18], 'gray')
                              # 顯示原圖
                              ax[0][1].set_title('img')
                              ax[0][1].axis('off')
                              ax[0][1].imshow(img, 'gray')
                              # 顯示灰度圖(白底黑字)
                              ax[0][2].set_title('gray')
                              ax[0][2].axis('off')
                              ax[0][2].imshow(gray, 'gray')
                              # 顯示灰度圖(黑底白字)
                              ax[1][0].set_title('gray')
                              ax[1][0].axis('off')
                              ax[1][0].imshow(gray_inv, 'gray')
                               
                              plt.show()

                              效果展示

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程

                              代碼

                              # 識別自己的手寫數(shù)字(圖像預(yù)測)
                              import os
                              os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
                              import tensorflow as tf
                              from tensorflow.keras.models import load_model
                              import matplotlib.pyplot as plt
                              from PIL import Image
                              import numpy as np 
                              # 1、載入數(shù)據(jù)
                              mnist = tf.keras.datasets.mnist
                              (x_train, y_train), (x_test, y_test) = mnist.load_data() 
                              # 2、載入訓(xùn)練好的模型
                              model = load_model('mnist.h6') 
                              # 3、載入自己寫的數(shù)字圖片并設(shè)置大小
                              img = Image.open('5.jpg')
                              # 設(shè)置大?。ê蛿?shù)據(jù)集的圖片一致)
                              img = img.resize((28, 28)) 
                              # 4、轉(zhuǎn)灰度圖
                              gray = np.array(img.convert('L'))       #.convert('L'):轉(zhuǎn)灰度圖
                              # 5、轉(zhuǎn)黑底白字、數(shù)據(jù)歸一化
                              gray_inv = (255-gray)/255.0 
                              # 6、轉(zhuǎn)四維數(shù)據(jù)(CNN預(yù)測需要)
                              image = gray_inv.reshape((1,28,28,1)) 
                              # 7、預(yù)測
                              prediction = model.predict(image)           # 預(yù)測
                              prediction = np.argmax(prediction,axis=1)   # 找出最大值
                              print('預(yù)測結(jié)果:', prediction) 
                              # 8、顯示
                              # 設(shè)置plt圖表
                              f, ax = plt.subplots(2, 2, figsize=(5, 5))
                              # 顯示數(shù)據(jù)集圖像
                              ax[0][0].set_title('train_model')
                              ax[0][0].axis('off')
                              ax[0][0].imshow(x_train[18], 'gray')
                              # 顯示原圖
                              ax[0][1].set_title('img')
                              ax[0][1].axis('off')
                              ax[0][1].imshow(img, 'gray')
                              # 顯示灰度圖(白底黑字)
                              ax[1][0].set_title('gray')
                              ax[1][0].axis('off')
                              ax[1][0].imshow(gray, 'gray')
                              # 顯示灰度圖(黑底白字)
                              ax[1][1].set_title(f'predict:{prediction}')
                              ax[1][1].axis('off')
                              ax[1][1].imshow(gray_inv, 'gray') 
                              plt.show()

                              感謝各位的閱讀,以上就是“Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的方法教程這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

                              向AI問一下細(xì)節(jié)

                              免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

                              AI