[英]Can't get accuracy in own digit image dataset for mnist
我是機器學習的新手,我嘗試了 mnist 數據集,准確率約為 97%,但隨后我嘗試處理我的圖像數據集,結果准確率為 0%。 請幫幫我。
這是 97% 准確率模型代碼:
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv2D, Flatten
from keras.callbacks import ModelCheckpoint
x_train = tf.keras.utils.normalize(x_train, axis =1)
x_test = tf.keras.utils.normalize(x_test, axis = 1)
model = Sequential()
model.add(Flatten())
model.add(Dense(128, activation = 'relu'))
model.add(Dense(128, activation = 'relu'))
model.add(Dense(10, activation = 'softmax'))
model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
checkpointer = ModelCheckpoint(filepath = 'mnist.model.weights.best.hdf5',verbose = 1,save_best_only = True, monitor = 'loss')
model.fit(x_train, y_train, epochs = 3, callbacks = [checkpointer],
batch_size = 32,verbose = 2,shuffle = True)
現在我嘗試了我的 10 張圖像,但沒有一個被正確預測。 下面是代碼:
from skimage import io
from skimage import color
import numpy as np
import tensorflow as tf
import keras
img_0 = color.rgb2gray(io.imread("0.jpg"))
img_2 = color.rgb2gray(io.imread("2.jpg"))
img_3 = color.rgb2gray(io.imread("3.jpg"))
img_4 = color.rgb2gray(io.imread("4.jpg"))
img_5 = color.rgb2gray(io.imread("5.jpg"))
img_6 = color.rgb2gray(io.imread("6.jpg"))
img_7 = color.rgb2gray(io.imread("7.jpg"))
img_8 = color.rgb2gray(io.imread("8.jpg"))
img_9 = color.rgb2gray(io.imread("9.jpg"))
array = [img_0, img_2, img_3, img_4, img_5, img_6, img_7, img_8, img_9]
#normalized the data between 0-1
array = tf.keras.utils.normalize(array, axis = 1)
#used the loop to increase the dimensions of the input layer as 1,28,28 which will be converted into 1*784
for i in array:
i = np.expand_dims(i,axis = 0)
print(i.shape)
new_model = tf.keras.models.load_model('mnist_save.model')
new_model.load_weights('mnist.model.weights.best.hdf5')
predictions = new_model.predict(array)
你能幫我解決我的問題嗎?
如果我是你,我會檢查以下三件事。
1. 並排可視化訓練和測試數據
這是查看低性能是否合理的最簡單方法。 基本上,如果測試數據與訓練數據看起來非常不同,則您的預訓練模型無法在這個新的測試領域中實現高性能。 即使情況並非如此,可視化應該有助於決定可以應用哪些簡單的域適應來實現更好的性能。
2. 仔細檢查你的 L2normalization
我看了一下keras.utils.normalize
的源碼
@tf_export('keras.utils.normalize')
def normalize(x, axis=-1, order=2):
"""Normalizes a Numpy array.
Arguments:
x: Numpy array to normalize.
axis: axis along which to normalize.
order: Normalization order (e.g. 2 for L2 norm).
Returns:
A normalized copy of the array.
"""
l2 = np.atleast_1d(np.linalg.norm(x, order, axis))
l2[l2 == 0] = 1
return x / np.expand_dims(l2, axis)
由於您使用的是 tensorflow 后端,沿第一個軸normalize
意味着什么? 標准化每一行? 這很奇怪。 進行歸一化的正確方法是 (1) 向量化您的輸入圖像,即每個圖像都變成一個向量; (2) 對結果向量進行normalize
(在軸 = 1 處)。
實際上,這有點不合適,尤其是當您想在不同領域應用預訓練模型時。 這是因為 L2 歸一化對非零值更敏感。 在 MNIST 樣本中,幾乎是二值化的,即 0 或 1。 但是,在灰度圖像中,您可能會遇到 [0,255] 中的值,這是一個完全不同的分布。
您可以嘗試簡單的 (0,1) 歸一化,即
x_normalized = (x-min(x))/(max(x)-min(x))
但這需要您重新訓練新模型。
3. 應用領域適應技術
這意味着您希望在將測試圖像提供給模型之前(甚至在標准化之前)執行以下操作。
當然,應用什么技術取決於您在可視化結果中觀察到的域差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.