Python 深度学习与神经网络

Python 深度学习与神经网络,python,tensorflow,machine-learning,deep-learning,neural-network,Python,Tensorflow,Machine Learning,Deep Learning,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 LabelBinari

使用以下脚本进行预测

# 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])
我已经使用上述架构为3类猫、狗和花开发了模型。当我预测这些类的任何看不见的图像时,它给出了很好的结果。但是,当我预测house.jpg或laptop.jpg或其他三类图片时,我还预测了这三类图片,这太恶心了。 我做错了什么

house.jpg或laptop.jpg的预测准确率也在85%以上。 怎样做才能使它不能预测出类外的图像

但当我预测house.jpg或laptop.jpg或图像时 除了这三个等级之外,在这三个等级中 三班制

这是正常的行为,因为神经网络在最后一层

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()
它返回问题中每个类的概率

因此,如果您使用的是
laptop.jpg
图像,它可能会返回三个小概率,最大的概率为您提供输出

由于您在
培训
集中没有使用
笔记本电脑
图像,因此
神经网络
对此毫无概念

一种方法是设置阈值概率,比如说
50%
,如果那些
3
概率中没有人超过此阈值,则打印
Unknown

换句话说,如果您使用softmax分布进行分类,那么您可以确定正确分类样本的基线最大概率,然后推断新样本是否不属于任何已知类别,如果其最大概率低于某种阈值


这个想法来源于一篇解释这种情况的研究论文:

你的问题是你的人际网络只有三种选择(猫、狗或花)

最好的方法是添加第四个选项(“未知”)

因此,您需要在训练数据中添加一些标签为“未知”的随机图片。当然,这些图片不能包含猫、狗或花

这样,你的网络不仅学会预测给定对象,还学会判断图片中是否没有已知对象

更笼统地说:你应该尽可能地训练你的网络,使其接近实际应用


在你的情况下:为什么你有一栋房子.jpg,但不把它用于培训?

你做得很好。如果你不让你的网络为你的笔记本电脑选择另一个类。jpg,你的模型将尝试做的工作是了解笔记本电脑的图片是否与猫、狗或花有更多的共同点。假设它有一朵花,你的网络可能会预测你给它的任何笔记本电脑图片的班级花


拜拜:)

你能分享你用来做预测的代码吗?如果你在预测概率,那么你可以设置一个阈值,超过该阈值,结果应该是有效的,否则它们可能会被标记为其他。请注意,softmax的概率总和始终为1。另外,softmax是一个函数,旨在为最有可能的类别提供非常高的概率,这使得很难找到一个好的阈值。谢谢您的指导和时间。但预测也给了我超过80%的准确率,除了类图像。有没有其他办法来解决这个问题。
model.add(Dense(3, activation="softmax"))