【发布时间】:2021-06-20 12:26:41
【问题描述】:
我已经设法用标签训练图像,但我无法用相应的图像预测单个图像并输出它。
代码如下:
labels = ['Black_Shank', 'Brown_Spot']
img_size = 224
def get_data(data_dir):
data = []
for label in labels:
path = os.path.join(data_dir, label)
class_num = labels.index(label)
for img in os.listdir(path):
try:
img_arr = cv2.imread(os.path.join(path, img))[...,::-1] #convert BGR to RGB format
resized_arr = cv2.resize(img_arr, (img_size, img_size)) # Reshaping images to preferred size
data.append([resized_arr, class_num])
except Exception as e:
print(e)
return np.array(data)
train = get_data('/Users/cynthianchabaya/Downloads/Tobacco/Basedata/Training')
val = get_data('/Users/cynthianchabaya/Downloads/Tobacco/Basedata/Testing')
model = Sequential()
model.add(Conv2D(32,3,padding="same", activation="relu", input_shape=(224,224,3)))
model.add(MaxPool2D())
model.add(Conv2D(32, 3, padding="same", activation="relu"))
model.add(MaxPool2D())
model.add(Conv2D(64, 3, padding="same", activation="relu"))
model.add(MaxPool2D())
model.add(Dropout(0.4))
model.add(Flatten())
model.add(Dense(128,activation="relu"))
model.add(Dense(2, activation="softmax"))
model.summary()
#opt = Adam(lr=0.000001)
model.compile(optimizer = "adam" , loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) , metrics = ['accuracy'])
history = model.fit(x_train,y_train,epochs = 500 , validation_data = (x_val, y_val))
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(500)
predictions = model.predict_classes(x_val)
predictions = predictions.reshape(1,-1)[0]
print(classification_report(y_val, predictions, target_names = ['Black_Shank (Class 0)','Brown_Spot (Class 1)']))
我遵循了一些教程,我不太了解它,但它的工作原理。哈哈。
【问题讨论】:
-
您应该使用
cv2.imread加载一张图片,然后将其提供给model.predict_classes() -
你不需要
from_logits = True,设置为False。
标签: python tensorflow machine-learning keras deep-learning