python - 从外部附加函数调用 `model.predict()`
问题描述
以此为参考,我想出了以下代码:
import tensorflow as tf
from tensorflow.keras.applications.densenet import DenseNet121
from tensorflow.keras.applications.densenet import preprocess_input as densenet_preprocess_input
import inspect, cv2
import numpy as np
@tf.function(input_signature=[tf.TensorSpec([None, None, 3],dtype=tf.uint8)])
def _preprocess(image_array):
im_arr = tf.image.resize(image_array, (resize_height, resize_width))
im_arr = densenet_preprocess_input(im_arr)
input_batch = tf.expand_dims(im_arr, axis=0)
return input_batch
training_model = DenseNet121(include_top=True, weights='imagenet')
#Assign resize dimensions
resize_height = tf.constant(480, dtype=tf.int64)
resize_width = tf.constant(640, dtype=tf.int64)
#Attach function to Model
training_model.preprocess = _preprocess
#Attach resize dimensions to Model
training_model.resize_height = resize_height
training_model.resize_width = resize_width
training_model.save("saved_model", overwrite=True)
它基本上附加了一个名为preprocess的方法,为DenseNet121tf.keras.Model
定义。
以便以后我可以使用它来进行预测:
pred_model = tf.keras.models.load_model('saved_model')
#download image
image_path = tf.keras.utils.get_file("cat.jpg", "https://storage.googleapis.com/download.tensorflow.org/example_images/320px-Felis_catus-cat_on_snow.jpg")
#load and convert the image to tf.uint8 numpy array
image_array = np.array(tf.keras.preprocessing.image.load_img(path=image_path))
#call the custom function bound to the model
preprocessed_image = pred_model.preprocess(image_array)
result = pred_model.predict(preprocessed_image)
print(np.argmax(result, axis=-1), np.amax(result, axis=-1))
我的问题:
如何从预处理函数调用模型的预测方法。以便
preprocessed_image = pred_model.preprocess(image_array)
result = pred_model.predict(preprocessed_image)
可以变成
result = pred_model.preprocess_predict(image_array)
解决方案
推荐阅读
- ssis - SSIS 类型 2 SCD
- python - 拆分和操作 Pandas DataFrame 以进行多次绘图
- python - “查找访问代码”Google Foobar 挑战
- ruby-on-rails - 在 Windows 服务器上使用带有 Rails 5.2 的 Nokogiri 时出现无效参数 @ rb_sysopen 错误
- arrays - 同时使用两个进程(父进程和子进程)的分段错误
- php - 尝试在 Laravel 单元测试中第一次运行测试用例时出现 CommandNotFoundException
- java - 如何编写一个存在于 Java 的 2 个列表中的唯一值
- python - 将 Excel Solver 转换为 Python Pulp
- c# - 将 MS-SQL 表简单地导入 System.Data.DataTable,这可能吗?
- javascript - JavaScript Object 方法不改变属性