【发布时间】:2021-04-12 12:45:04
【问题描述】:
我是 TensorFlow 新手。我使用convNetKerasLarge.py 生成模型并保存为 tflite 模型。
我正在尝试如下测试这个保存的模型
import tensorflow as tf
import numpy as np
import glob
from skimage.transform import resize
from skimage import io
# out of previously used training and test set
start = 4001
# no of images
row_count = 1
end = start + row_count
n_image_rows = 106
n_image_cols = 106
np_val_images = np.zeros(shape=(1, 1))
np_val_labels = np.zeros(shape=(1, 1))
def prepare_validation_set():
global np_val_images
global np_val_labels
positive_samples = glob.glob('datasets/drunk_resize_frontal_faces/pos/*')[start:end]
# negative_samples = glob.glob('datasets/drunk_resize_frontal_faces/neg/*')[start:end]
# negative_samples = random.sample(negative_samples, len(positive_samples))
val_images = []
val_labels = []
for i in range(len(positive_samples)):
val_images.append(resize(io.imread(positive_samples[i]), (n_image_rows, n_image_cols)))
val_labels.append(1)
# for i in range(len(negative_samples)):
# val_images.append(resize(io.imread(negative_samples[i]), (n_image_rows, n_image_cols)))
# val_labels.append(0)
np_val_images = np.array(val_images)
np_val_labels = np.array(val_labels)
def run_tflite_model(tflite_file, index):
prepare_validation_set()
# Initialize the interpreter
interpreter = tf.lite.Interpreter(model_path=str(tflite_file))
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()[0]
output_details = interpreter.get_output_details()[0]
test_image = np_val_images[index]
test_image = np.expand_dims(test_image, axis=0).astype(input_details["dtype"])
interpreter.set_tensor(input_details["index"], test_image)
interpreter.invoke()
output = interpreter.get_tensor(output_details["index"])[0]
print(output_details)
prediction = output.argmax()
print(prediction)
if __name__ == '__main__':
test_image_index = 1
tflite_model_file = "models/converted/model.tflite"
run_tflite_model(tflite_model_file, 0)
如果我运行这个,我得到的预测为0,即使标签应该是1,因为我输入的是正面图像。 (仅供参考:Test loss: 0.08881912380456924 Test accuracy: 0.9729166626930237 有 10 个时期)。我确信我的代码中存在导致此问题的错误,请帮助我找到它。
【问题讨论】:
-
您需要标准化您的图像(减去均值并除以标准差)。实际上,您为模型图像提供的功能与您在训练期间使用的功能完全不同。
-
@Lescurel 目录中的所有图像均已标准化。如果您查看
convNetKerasLarge.py和prepare_validation_set代码似乎相似,所以功能集不能不同,如果不是请解释。 -
来自您链接的脚本:
X_train[:,:,:,i] = (X_train[:,:,:,i]- mean[i]) / std[i]。您没有在数据准备功能中这样做。 -
@Lescurel 你能否发布一个相应的修复
prepare_validation_set的答案
标签: python tensorflow tensorflow2.0 tensorflow-lite