一篇就懂 tensorflow入門 MNIST數據處理(介紹,提高,入門的常見問題解決彙總)(超詳細)

tensorflow入門 MNIST數據處理(介紹,提高,入門的常見問題解決彙總)(超詳細)

前言

自己學tensorflow剛開始還是挺不舒服的,各種不理解,各種錯誤,不過熬過去就好了。結果這麼長時間都沒有寫博客記錄,於是便整理了一下,就有了這篇文章,一方面爲了剛入門的小白,另一方面也幫自己總結一下。這篇文章我會寫的很細,希望能解決你用tensorflow入門處理MNIST數據的困難。(希望)話不多說,我們開始吧。

介紹

MNIST 是一個非常有名的手寫體數字識別數據集,在很多資料中,這個數據集都會被用作深度學習的入門樣例。(之前筆者學sklearn的時候,也用這個數據集做過處理,真的是很經典。)
這個數據集長什麼樣呢?
MNIST_data
其中
Training set images(訓練集圖片): train-images-idx3-ubyte.gz (9.9 MB, 解壓後 47 MB, 包含 60,000 個樣本)
Training set label(訓練集標籤)s: train-labels-idx1-ubyte.gz (29 KB, 解壓後 60 KB, 包含 60,000 個標籤)
Test set images(測試集圖片): t10k-images-idx3-ubyte.gz (1.6 MB, 解壓後 7.8 MB, 包含 10,000 個樣本)
Test set labels(測試集標籤): t10k-labels-idx1-ubyte.gz (5KB, 解壓後 10 KB, 包含 10,000 個標籤)

簡單實現

如果哪一步出錯了,就到最後的常見問題裏去找對應的解決方案就行。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  2 12:24:27 2020

@author: phoenix
"""

#import相關的庫,這一步失敗,在常見問題1處有解決方案
#import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.examples.tutorials.mnist import input_data
"""
tensorflow如果是1.0的版本,那麼直接import tensorflow as tf
如果是2.0之後的,那麼需要
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
"""

#2.載入數據集,MNIST_data前面是我的路徑,這一步失敗,在常見問題2處有解決方案
mnist = input_data.read_data_sets("/Users/phoenix/Downloads/MNIST_data",one_hot=True)

#3.每個批次的大小(可改)
batch_size = 100
#4.計算一共有多少個批次
n_batch = mnist.train.num_examples // batch_size

#5.定義兩個placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])

#6.創建一個簡單的神經網絡(可改)
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)

#7.二次代價函數(可改)
loss = tf.reduce_mean(tf.square(y-prediction))

#8.使用梯度下降法(可改)
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#9.初始化變量(可改)
init = tf.global_variables_initializer()

#10.結果存放在一個布爾型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一維張量中最大的值所在的位置
#11.求準確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

#12.開始訓練,顯示訓練次數和效果
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(30):
        for batch in range(n_batch):
            batch_xs,batch_ys =  mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
        
        test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        train_acc = sess.run(accuracy,feed_dict={x:mnist.train.images,y:mnist.train.labels})
        print("Iter " + str(epoch+1) + ",Testing Accuracy " + str(test_acc) +",Training Accuracy " + str(train_acc))

如果正常運行結果如下:
正常結果如下
那麼恭喜你完成了。完成之後

提高及優化

a.代碼#3處優化

#batch_size = 100
batch_size = 10

優化後效果:準確度提高,速度降低

b.代碼#6處優化(增加神經網絡和激活函數的選擇)

"""
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)
"""
keep_prob=tf.placeholder(tf.float32)
W1 = tf.Variable(tf.truncated_normal([784,2000],stddev=0.1))
b1 = tf.Variable(tf.zeros([2000])+0.1)
L1 = tf.nn.tanh(tf.matmul(x,W1)+b1)
L1_drop = tf.nn.dropout(L1,keep_prob) 

W4 = tf.Variable(tf.truncated_normal([2000,10],stddev=0.1))
b4 = tf.Variable(tf.zeros([10])+0.1)
prediction = tf.nn.softmax(tf.matmul(L1_drop,W4)+b4)

相對於之前的代碼加了一層。
個人的理解原來是784到10,現在是784到2000到10。
不過如果直接這樣替換的話應該會報錯,需要最後面的稍微改一下,改成下面這三行,加了keep_prob。

            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.7})
        
        test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
        train_acc = sess.run(accuracy,feed_dict={x:mnist.train.images,y:mnist.train.labels,keep_prob:1.0})

c.代碼#7處優化(損失函數的優化)

神經網絡模型的效果以及優化的目標是通過損失函數( loss function )來定義的

# loss = tf.reduce_mean(tf.square(y-prediction))
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))

d.代碼#8處優化(更改優化器)

# train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
train_step = tf.train.AdamOptimizer(1e-2).minimize(loss)

tensorflow的優化器有很多,如果想深入瞭解可以看下面這個博客。
優化器的選擇
https://blog.csdn.net/junchengberry/article/details/81102058
不知道爲什麼如果我的這裏(#8處)和神經網絡那(#6處)同時更改,準確率反而不提升了。

常見問題及解決方法

a.ModuleNotFoundError: No module named ‘tensorflow.examples.tutorials’

這個問題說明你安裝的tensorflow沒有tutorials文件夾,反應了你安裝的tensorflow不完整。所以有的朋友可以通過更改版本解決這個BUG。
這裏推薦的方法是先看
\site-packages\tensorflow_core\examples裏面有沒有tutorials文件夾。如果沒有,那麼下載下來解壓複製進去就行。
鏈接: tutorials文件夾下載地址
如果不清楚也可以看下面的一些博客當參考
具體步驟可以按照
鏈接: 解決方法一或者鏈接: 解決方法二
這個兩篇博客來做

b.module ‘tensorflow’ has no attribute ‘placeholder’

這個問題說明你的tensorflow是2.0,而運行1.0的代碼,自然會有報錯,解決起來也很簡單。如下,把import tensorflow as tf換成import tensorflow.compat.v1 as tf。再加一個tf.disable_v2_behavior()

#import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

---------------華麗的分割線-------------

寫完了,如果有不懂的地方,歡迎在下面留言。這篇博客最後的常見問題及解決部分也會隨着反饋來更新。如果覺得有用,麻煩各位點贊咯。謝謝各位😁。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章