簡體   English   中英

深度學習和神經網絡

[英]Deep learning and neural network

# set the matplotlib backend so figures can be saved in the background
import matplotlib
matplotlib.use("Agg")

# import the necessary packages
from keras.layers.core import Dropout, Activation
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.optimizers import SGD
import matplotlib.pyplot as plt

from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras.layers import Dense, Conv2D, Flatten
from keras.layers.convolutional import MaxPooling2D

(trainX, testX, trainY, testY) = train_test_split(data,labels, test_size=0.25, random_state=42)

lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)

#create model
model = Sequential()
#add model layers
model.add(Conv2D(32, kernel_size=3, activation="relu", input_shape=(32,32,3)))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(32, kernel_size=3, activation="relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, kernel_size=3, activation="relu"))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation("relu"))
model.add(Dropout(0.5))
model.add(Dense(3, activation="softmax"))

# initialize our initial learning rate and # of epochs to train for
INIT_LR = 0.001
EPOCHS = 500

opt = SGD(lr=INIT_LR, clipvalue=0.5)
model.compile(loss="categorical_crossentropy", optimizer=opt,metrics=["accuracy"])

es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=200)
mc = ModelCheckpoint('best_model_500Epoch.h5', monitor='val_accuracy', mode='max', verbose=1, save_best_only=True)

H = model.fit(trainX, trainY, validation_data=(testX, testY),epochs=EPOCHS, batch_size=32,callbacks=[es, mc])

使用以下腳本進行預測。

from keras.models import load_model
import pickle
import cv2
import os
import matplotlib.pyplot as plt
from keras import backend as k


new_model = load_model('model_name.h5')
lb = pickle.loads(open("Label_Binarizer", "rb").read())

dirName = "Other_than_class"
listOfFile = os.listdir(dirName)



# Iterate over all the entries
for entry in listOfFile:
    # Create full path
    fullPath = os.path.join(dirName, entry)
    # If entry is a directory then get the list of files in this 
    directory
    image = cv2.imread(fullPath)
    output = image.copy()
    image = cv2.resize(image, (32, 32))

    # scale the pixel values to [0, 1]
    image = image.astype("float") / 255.0

    # check to see if we should flatten the image and add a batch
    # dimension
    image = image.flatten()
    image = image.reshape((1, image.shape[0]))


    # preds = new_model.predict(image)
    preds = new_model.predict(image.reshape(1, 32, 32, 3))
    print(preds[0])

    k.clear_session()

    # find the class label index with the largest corresponding 
    probability
    i = preds.argmax(axis=1)[0]
    label = lb.classes_[i]


    plt.grid(False)
    plt.imshow(output)
    plt.xlabel("Actual: " + str(entry))
    plt.title("Prediction: " + str(preds[0][i] * 100)+"  "+str(label))
    plt.show()

我已經使用上述架構為 3 類貓、狗和花開發了模型。 當我預測這些類的任何看不見的圖像時,它給出了很好的結果。 但是當我為 house.jpg 或 notebook.jpg 或這些 3 類以外的圖像預測它時,它也會在這些 3 類中進行預測,這太惡心了。 我做錯了什么?

預測house.jpg或laptop.jpg的准確率也在85%以上。 該怎么做才能使其不從類別中預測圖像。

但是,當我為 house.jpg 或 notebook.jpg 或這些 3 類以外的圖像預測它時,它也會在這些 3 類中進行預測。

這是正常行為,因為最后一層的神經網絡

model.add(Dense(3, activation="softmax"))

它從您的問題中返回每個類的概率

所以,如果你使用的是laptop.jpg圖像,它可能會返回三個小概率,最大的一個它會為你提供輸出。

由於您沒有在training集中使用laptop圖像,因此neural network對此一無所知。

一種方法可能是設置閾值概率,假設為50% ,如果這3概率中沒有一個超過此閾值,則打印Unknown

換句話說,如果您使用softmax分布進行分類,那么您可以確定正確分類樣本的基線最大probability是多少,然后推斷新樣本是否不屬於任何已知類別,如果其最大概率低於某種threshold

這個想法來自一篇解釋這種情況的研究論文: A Baseline for Detective Misclassified and Out-of-Distribution Examples in Neural Networks

您的問題是您的網絡只有三個選項(“貓”、“狗”或“花”)。

最好的方法是添加第四個選項(“未知”)。

因此,您需要向訓練數據中添加一些帶有“未知”標簽的隨機圖片。 這些圖片當然不能包含貓、狗或花。

這樣,您的網絡不僅可以學習預測給定的對象,還可以學習判斷圖片中是否沒有已知對象。

更籠統地說:您應該盡可能接近其實際應用來訓練您的網絡

在您的情況下:為什么您有 house.jpg 但不將其用於培訓?

你一切都做得很好。 如果你不讓你的網絡為你的 notebook.jpg 選擇另一個類的可能性,你的模型將嘗試做的工作是了解那台筆記本電腦的圖片是否與貓、狗或花有更多的共同點。 假設它有一朵花,您的網絡可以預測您提供給它的任何筆記本電腦圖片的類別花!

再見 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM