我正在使用tensorflow学习图像分类。下面是我的程序。对于同一张测试图像,如果我一次又一次地通过,它有时会给出不同的标签。它无法正确预测
import tensorflow as tf
import numpy as np
import os
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten,Activation
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.constraints import maxnorm
from keras.utils import np_utils
classifier = Sequential()
classifier.add(Conv2D(32, (3, 3), input_shape = (64,64,3 ),activation="relu"))
classifier.add(MaxPooling2D(pool_size = (2,2)))
classifier.add(Flatten())
classifier.add(Dense(128 , kernel_initializer ='uniform' , activation = 'relu'))
classifier.add(Dense(10 , kernel_initializer ='uniform' , activation = 'softmax'))
classifier.compile(optimizer = 'rmsprop', loss = 'categorical_crossentropy' , metrics = ['accuracy'])
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_set = train_datagen.flow_from_directory(
'/code/train',
shuffle=True,
target_size=(64,64),
batch_size=5,
class_mode='categorical',
classes=["shiv", "kart", "nall","surendra","harshi","nag","saura","rajan","manoj","abhimanyu"])
test_set = test_datagen.flow_from_directory(
'/code/validation',
shuffle=True,
target_size=(64,64),
batch_size=5,
class_mode='categorical',
classes=["shiv", "kart", "nall","surendra","harshi","nag","saura","rajan","manoj","abhimanyu"])
from IPython.display import display
from PIL import Image
classifier.fit(
training_set,
steps_per_epoch=80,
epochs=12,
validation_data=test_set,
validation_steps=100)
from keras_preprocessing import image
files_dir = '/code/test_image_clasification1'
files = os.listdir(files_dir)
np.set_printoptions(precision=3)
for f in files:
image_path = files_dir + '/' + f
test_image = image.load_img(image_path,target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
#classes = classifier.predict_classes(test_image)
#print (classes)
labels = ["shivaji","kartik","nallayan","surendar","harshita","nagendar","saurabh","rajan","manoj","abhimanyu"]
indx = np.argmax(result)
#score = np.argmax(np.round(result*100,2))
#print(np.round(result,2))
match_percentage=np.max(result)
match_class=labels[indx]
print("the image " + f + " is matching with "+ match_class + " having matching percentage " +"{:.2%}".format(match_percentage) )
#print(list(zip(labels,result)))
#print(f,labelsindx])
如果模型训练有任何问题,谁能帮助我。作为参考,我在训练集中有122张图像,在验证集中有48张图像。
答案 0 :(得分:1)
您需要对图像应用相同的缩放比例因子,当前缺少此因子,因此会导致错误的概率预测。因此,您还需要通过将1./255应用于test_image来重新缩放为[0,1]。
答案 1 :(得分:0)
您可以尝试更改损耗和优化器。
classifier.compile(optimizer = 'sgd', loss = 'sparse_categorical_crossentropy' , metrics = ['accuracy'])