我已经在Jupyter Notebook中训练了一个图像分类模型,并且已经到了测试一个图像是“Pasta = 0”还是“Pizza = 1”的地步。
但是,值预测并没有打印出来。处理测试图像时所发生的一切只是处理过程显示为“已完成”,每一步所用的时间也显示为“已完成”。没有打印“Pasta”或“比萨饼”。
下面是我目前所拥有的代码:
#Import all libraries needed.
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
from tensorflow.keras import layers
from keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import RMSprop
import cv2
import os
plt.style.use('fivethirtyeight')
img = image.load_img("D:/ML Datasets/FoodImageClassification/Training Data/Pizza/Pizza - Wikipedia.jpg")
plt.imshow(img)
cv2.imread("D:/ML Datasets/FoodImageClassification/Training Data/Pizza/Pizza - Wikipedia.jpg")
cv2.imread("D:/ML Datasets/FoodImageClassification/Training Data/Pizza/Pizza - Wikipedia.jpg").shape
#Training and Validation
train = ImageDataGenerator(rescale = 1/255)
validation = ImageDataGenerator(rescale = 1/255)
train_dataset = train.flow_from_directory('D:/ML Datasets/FoodImageClassification/Training Data/',target_size = (200,200),
batch_size = 4,
class_mode = 'binary')
validation_dataset = train.flow_from_directory('D:/ML Datasets/FoodImageClassification/Testing Data/',target_size = (200,200),
batch_size = 4,
class_mode = 'binary')
train_dataset.class_indices #This returns {'Pasta': 0, 'Pizza': 1}
train_dataset.classes
model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(16,(3,3),activation = 'relu',input_shape = (200,200,3)),
tf.keras.layers.MaxPool2D(2,2),
#
tf.keras.layers.Conv2D(32,(3,3),activation = 'relu'),
tf.keras.layers.MaxPool2D(2,2),
#
tf.keras.layers.Conv2D(32,(3,3),activation = 'relu'),
tf.keras.layers.MaxPool2D(2,2),
##
tf.keras.layers.Flatten(),
##
tf.keras.layers.Flatten(),
##
tf.keras.layers.Dense(512,activation='relu'),
##
tf.keras.layers.Dense(1,activation='sigmoid'),
##
tf.keras.layers.Dense(1,activation='softmax'),
##
tf.keras.layers.Dense(1,activation='sigmoid')
])
model.compile(loss = 'binary_crossentropy',
optimizer = RMSprop(learning_rate=0.30),
metrics = ['accuracy'])
model_fit = model.fit(train_dataset,
steps_per_epoch = 5,
epochs = 50,
validation_data = validation_dataset)
from skimage.transform import resize
img = image.load_img('D://ML Datasets/FoodImageClassification/Testing Data/Pasta/Garlic Butter Parmesan Pasta Recipe.jpg')
newsize = (200, 200)
img = img.resize(newsize)
# Shows the image in image viewer
img.show()
X = image.img_to_array(img)
X = np.expand_dims(X,axis = 0)
images = np.vstack([X])
val = model.predict(images)
if val == 0:
print("Pasta")
elif val == 1:
print("Pizza")
1条答案
按热度按时间iih3973s1#
当模型的输出使用S形激活函数时,
model.predict()
返回一个介于[0,1]之间的浮点数。它几乎不会返回0或1。您需要使用类似np.rint()
的值对预测进行舍入,并检查 * 该 * 值,假设在训练期间训练集的类是平衡的,则可能需要对实际预测进行一些调整。