Я новичок в машинном обучении и следовал шаблону на одном из курсов ML, чтобы обучить изображениям кошек и собак их классифицировать.
Если я загружу изображение, которое будет предсказано в моей модели, неважночто, предсказание становится первым классом, который я определил в конце списка.
Я делаю это для классификации других типов изображений, однако я получаю ту же ошибку в этом наборе данных, поэтому я подумалиспользования классического набора данных о кошках и собаках.
Я хочу предсказать, что если изображение текста, которое я даю обученной модели, имеет причудливый текст или стандартный текстовый шрифт.
Вот мойкод.
#create classifier
classifier = Sequential()
#adding convolution layer
classifier.add(Convolution2D(32, 3, 3, input_shape = (64, 64, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2,2), strides = (2,2)))
classifier.add(Convolution2D(32, 3, 3, activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2,2), strides = (2,2)))
classifier.add(Flatten())
classifier.add(Dense(output_dim = 128, activation = 'relu'))
classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))
# In[54]:
#compiling
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# In[55]:
#making Image size same
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(
'D:/Third Year/kaggle/cats/New Data/Convolutional_Neural_Networks/dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory(
'D:/Third Year/kaggle/cats/New Data/Convolutional_Neural_Networks/dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
print('TRAINING:',training_set)
print('TEST: ',test_set)
# In[56]:
#checking if already a weight file exists. if it does loads it into the model
if os.path.isfile("modelCNN_CD.h5") :
classifier.load_weights("modelCNN_CD.h5")
#checkpoint saves the model.
filepath="modelCNN_CD.h5"
checkpoint1 = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
classifier.summary()
classifier.fit_generator(
training_set,
steps_per_epoch=8000,
epochs=25,
validation_data=test_set,
validation_steps=2000,callbacks=[checkpoint1,])
# In[67]:
# load the model
#model = VGG16()
# load an image from file
image = load_img('D:/Third Year/kaggle/cats/New Data/Convolutional_Neural_Networks/dog.4029.jpg', target_size=(64, 64))
# convert the image pixels to a numpy array
image = img_to_array(image)
# reshape data for the model
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
yhat = classifier.predict(image)
print(yhat)
import numpy as np
print(platetype[np.argmax(yhat)])
# In[57]:
platetype = ['Cat','Dog']
# In[9]:
from keras.models import load_model
classifier = load_model('modelCNN_LP.h5')