【发布时间】:2021-09-05 21:47:03
【问题描述】:
我正在尝试在 google colab 中为面罩检测项目执行此代码,但我对保存的模型有疑问。使用的代码和错误如下。 培训已完成,但我不明白为什么找不到保存的模型(我的朋友使用相同的代码,她没有发现模型有任何问题),有人可以帮我吗?我错过了什么吗??
import tensorflow
checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
batch_size=32
# Create a callback that saves the model's weights
cp_callback = tensorflow.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
save_weights_only=True,
verbose=1,
save_freq=10*batch_size)
import keras
epochs = 50
save_freq=10*batch_size
model.compile(loss = 'categorical_crossentropy',
optimizer = 'Adam',
metrics = ['accuracy'])
fitted_model = model.fit(
train_X,
train_y,
epochs = epochs,
validation_split=0.30,
callbacks=[cp_callback],
verbose=1)
import tensorflow as tf
import numpy as np
import cv2
import face_recognition
from google.colab.patches import cv2_imshow
model=tf.keras.models.load_model('mask_detection.model')
text_dict={0:'Mask ON',1:'No Mask'}
rect_color_dict={0:(0,255,0),1:(0,0,255)}
image=cv2.imread("/content/drive/MyDrive/148.jpg")
img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces =face_recognition.face_locations(image,model='hog')
type = isinstance(faces, tuple)
if type == False:
for face in faces:
face_location = np.array(face)
x = face_location[3]
y = face_location[0]
w = face_location[1] - face_location[3]
h = face_location[2] - face_location[0]
im = image[y:y + w, x:x + w]
grayscale_image = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
resized_image = cv2.resize(grayscale_image, (200, 200))
imags = []
imags.append(resized_image)
imags = np.array(imags) / 255.0
imags = np.reshape(imags, (imags.shape[0], 200, 200, 1))
predictions = model.predict(imags)
predictions = np.argmax(predictions)
label = predictions
cv2.rectangle(image, (x, y), (x + w, y + h), rect_color_dict[label], 2)
cv2.rectangle(image, (x, y - 40), (x + w, y), rect_color_dict[label], -1)
cv2.putText(image, text_dict[label], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2)
else:
print('no faces detected')
cv2_imshow(image)
错误:
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-21-17164d330c43> in <module>()
6 from google.colab.patches import cv2_imshow
7
----> 8 model=tf.keras.models.load_model('mask_detection.model')
9
10
2 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/saved_model/loader_impl.py in parse_saved_model(export_dir)
119 "SavedModel file does not exist at: %s%s{%s|%s}" %
120 (export_dir, os.path.sep, constants.SAVED_MODEL_FILENAME_PBTXT,
--> 121 constants.SAVED_MODEL_FILENAME_PB))
122
123
OSError: SavedModel file does not exist at: mask_detection.model/{saved_model.pbtxt|saved_model.pb}
【问题讨论】:
-
看起来您正在保存一个名为
"training_1/cp.ckpt"的模型,并试图加载一个名为'mask_detection.model'的模型;最好仔细检查一下。 -
另外,在
Colab会话之间保存和加载模型时要小心,因为模型数据可能不会被保留。 -
没错,模型的名称是问题所在。感谢您的帮助
标签: python tensorflow keras google-colaboratory