I am trying to start small and have trained my model with 2 items. It recognises both just fine but when I show it something other than the 2 items it knows, it keeps telling me that is is always the same item. For example, I have an apple and banana. If I show it the apple, it correctly gives me apple, if I show it a banana it correctly returns banana. But if I show it a dog, it tells me it is an apple. If I show it a helicopter it tells me it is an apple. I even tried an if statement to say that if it isn't an apple or a banana then just return that it can't be recognised, but that never comes because everything besides the banana is always an apple?!
EDIT My question was down voted perhaps because of a misunderstanding. I am not asking why it doesn't recognise a dog when I have only trained an apple and banana, I am asking why it doesn't tell me that the image is unrecognised when I show it a dog instead of telling me it's an apple. Obviously if I have only trained it with 2 items it is only going to recognise 2 items.
Here is the code that returns the classifications
func processClassifications(for request: VNRequest, error: Error?) {
DispatchQueue.main.async {
guard let results = request.results else {
self.classificationLabel.text = "Unable to classify image"
return
}
let classifications = results as! [VNClassificationObservation]
if classifications.isEmpty {
self.classificationLabel.text = "Nothing recognized"
} else {
//Display top classifications ranked by confidence in the UI
let topClassifications = classifications.prefix(1)
let descriptions = topClassifications.map { classification in
return String(format: " (%.2f) %@", classification.confidence, classification.identifier)
}
self.classificationLabel.text = descriptions.joined(separator: "\n")
}
}
}
If you have model trained with 2 items only (in your case Apple and Banana) you can't expect that your ML model recognize something else than these 2 items. Code that you wrote always returns item which will have the biggest confidence.
Anyway, if you have more items, you can do something like: if no item matches with testing image for at least x%, do this
guard let topResult = classifications.first else { return }
if topResult.confidence > 0.75 {
print(topResult.identifier)
} else {
print("Match is less than 75%")
}