CNN模型即使训练精度很高也无法对水果图像进行分类

时间:2020-07-12 12:01:15

标签: tensorflow keras cnn

我正在使用kaggle水果360数据集,并希望预测10到15个水果,并且该模型对我来说看起来不错,训练测试的准确性也很好。但是最后我下载了一些图像并将其输入以测试模型时,它完全将其识别为除苹果果实以外的其他果实。也许那是在模型的末尾,在那里我检查特定的类是否匹配它。即我要输入图像的最后一块。我尝试过VGG16模型,即使精度较高,也存在相同的问题。请帮忙,因为我坚持了过去两天。

这是我的代码:

"""Fruits.ipynb
Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1AiGMVBshT9w-5T3fzzi3jyrJr0CVGv6A
"""

from google.colab import files

!pip install -q kaggle

uploaded = files.upload()

!mkdir -p ~/.kaggle
!cp kaggle.json ~/.kaggle/
!ls ~/.kaggle
!chmod 600 /root/.kaggle/kaggle.json

!kaggle kernels list — user hinaaslam1 — sort-by dateRun

!kaggle datasets download -d moltean/fruits 

#https://www.kaggle.com/moltean/fruits see the dataset at this link.

!unzip -q fruits.zip -d content

!ls

!pip install --upgrade keras
!pip install tensorflow

from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
from keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image



no_of_classes = 131

# Initialising the CNN
classifier = Sequential()

# Step 1 - Convolution
classifier.add(Conv2D(32, (5, 5), input_shape = (100, 100, 3), activation = 'relu'))

# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2), strides= 2))

# Adding a convolutional layer
classifier.add(Conv2D(64, (5, 5), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2), strides= 2))

# Adding a second convolutional layer
classifier.add(Conv2D(128, (5, 5), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2), strides= 2))

# Adding a third convolutional layer
classifier.add(Conv2D(256, (5, 5), activation = 'relu'))
classifier.add(Dropout(0.25))
classifier.add(MaxPooling2D(pool_size = (2, 2), strides= 2))

# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dropout(0.25))
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dropout(0.25))
classifier.add(Dense(units = no_of_classes, activation = 'softmax'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])

# Part 2 - Fitting the CNN to the images

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

Training = train_datagen.flow_from_directory('/content/fruits-360/Training',
                                                 target_size = (100, 100),
                                                 batch_size = 32,
                                                 class_mode = 'categorical')

Validation = test_datagen.flow_from_directory('/content/fruits-360/Test',
                                            target_size = (100, 100),
                                            batch_size = 32,
                                            class_mode = 'categorical')

import os
os.walk('/content/fruits-360')
[x[0] for x in os.walk('/content/fruits-360/Training')]

"""# New Section"""

history = classifier.fit_generator(Training,
                         
                         epochs = 25,
                         verbose = 1,
                         validation_data = Validation,
                         
                         )
classifier.summary()

history.history['accuracy']

#Plotting graphs
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
 
epochs = range(len(acc))
 
plt.plot(epochs, acc, 'b', label='Training accuracy')
plt.plot(epochs, val_acc, 'r', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
 
plt.figure()
 
plt.plot(epochs, loss, 'b', label='Training loss')
plt.plot(epochs, val_loss, 'r', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
 
plt.show()

name_of_classes = [ ' Pitahaya Red', ' Apple Golden 1',' Beetroot', ' Pear Abate', ' Mulberry', ' Apple Golden 2', ' Pineapple', ' Pear Monster', ' Pear Red', ' Orange', ' Cherry Wax Red', ' Pear', ' Pear Stone', ' Banana', ' Limes', ' Apple Red Yellow 2', ' Apple Crimson Snow', ' Plum', ' Cactus fruit', ' Grape White 2', ' Pear 2', ' Pineapple Mini', ' Cantaloupe 2', ' Carambula', ' Cherry 1', ' Tamarillo', ' Papaya', ' Lemon',' Cherry 2', ' Tomato 2', ' Mandarine', ' Pomelo Sweetie', ' Pepper Red', ' Hazelnut', ' Nut Pecan', ' Physalis', ' Grape White 3', ' Grape White',' Cherry Wax Yellow', ' Apple Granny Smith', ' Tangelo', ' Kohlrabi', ' Melon Piel de Sapo', ' Cauliflower', ' Strawberry Wedge', ' Potato Sweet',' Apple Red 2', ' Apple Red 3', ' Grapefruit White', ' Avocado ripe', ' Cantaloupe 1', ' Tomato Maroon', ' Tomato Heart', ' Grape Blue', ' Walnut',' Grape Pink', ' Maracuja', ' Tomato Yellow', ' Lychee', ' Apple Red 1', ' Nectarine Flat', ' Pear Forelle', ' Tomato 4', ' Cherry Rainier',' Grapefruit Pink',' Peach',' Dates',' Mango Red',' Raspberry', ' Fig', ' Strawberry', ' Apple Pink Lady', ' Kumquats', ' Plum 3', ' Plum 2', ' Lemon Meyer', ' Pepper Yellow', ' Kaki', ' Tomato 1', ' Pepper Orange', ' Apple Golden 3', ' Potato White', ' Physalis with Husk', ' Mango',' Huckleberry',' Cocos',' Redcurrant',' Tomato not Ripened',' Passion Fruit', ' Apple Braeburn', ' Potato Red Washed',' Salak',' Granadilla',' Tomato 3',' Peach Flat', ' Apple Red Delicious', ' Banana Lady Finger', ' Watermelon', ' Clementine', ' Corn', ' Onion Red Peeled',' Onion White', ' Rambutan', ' Guava', ' Potato Red', ' Cucumber Ripe 2', ' Pepper Green', ' Grape White 4', ' Blueberry', ' Tomato Cherry Red',' Pomegranate',' Cucumber Ripe',' Mangostan', ' Pear Kaiser', ' Onion Red', ' Ginger Root', ' Pear Williams', ' Avocado',' Pepino', ' Corn Husk',' Banana Red', ' Apple Red Yellow 1', ' Chestnut', ' Eggplant', ' Quince', ' Cherry Wax Black', ' Nectarine', ' Kiwi', ' Nut Forest', ' Apricot', ' Peach 2']

Training.class_indices

test_image = image.load_img('/content/apple.jpg',target_size = (100, 100))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0 )
result = classifier.predict(test_image)
Training.class_indices
img = '/content/apple.jpg'
Image.open('/content/apple.jpg')

for i in range(no_of_classes):
    if (result[0][i] == 1.0):
        img_path = '/content/apple.jpg'
        print ('Predicted:',name_of_classes[i])
Image.open(img_path)

test_image = image.load_img('/content/apple red yellow.jpg', target_size = (100, 100))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
Training.class_indices
img = '/content/apple red yellow.jpg'
Image.open(img)

for i in range(no_of_classes):
    if (result[0][i] == 1.0):
        img_path = '/content/apple red yellow.jpg'
        print ('Predicted:',name_of_classes[i])
Image.open(img_path)

test_image = image.load_img('/content/chestnut.jpg', target_size = (100, 100))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
Training.class_indices
img = '/content/chestnut.jpg'
Image.open(img)


for i in range(no_of_classes):
    if (result[0][i] == 1.0):
        img_path = '/content/chestnut.jpg'
        print ('Predicted:',name_of_classes[i])
Image.open(img_path)

test_image = image.load_img('/content/banana.jpg', target_size = (100, 100))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
Training.class_indices
img = '/content/banana.jpg'
Image.open(img)


for i in range(no_of_classes):
    if (result[0][0] == 1.0):
        img_path = '/content/banana.jpg'
        print ('Predicted:',name_of_classes[i])
Image.open(img_path)

test_image = image.load_img('/content/grapes.jpg', target_size = (100, 100))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
Training.class_indices
img = '/content/grapes.jpg'
Image.open(img)


for i in range(no_of_classes):
    if (result[0][i] == 1.0):
        img_path = '/content/grapes.jpg'
        print ('Predicted:',name_of_classes[i])
Image.open(img_path)

test_image = image.load_img('/content/mango.jpg', target_size = (100, 100))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
Training.class_indices
img = '/content/mango.jpg'
Image.open(img)


for i in range(no_of_classes):
    if (result[0][i] == 1.0):
        img_path = '/content/mango.jpg'
        print ('Predicted:',name_of_classes[i])
Image.open(img_path)

0 个答案:

没有答案
相关问题