如何从自定义神经网络模型中获得logits和概率



以下源代码可以从Tensorflow 中的图像网预训练模型中获得概率和logits

import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
import PIL
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#Sets the threshold for what messages will be logged
tf.logging.set_verbosity(tf.logging.ERROR)
#Starts the Interactive Session
sess=tf.InteractiveSession()
#Get logits and probs from the model
def inception(image, reuse):
preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)
arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)
with slim.arg_scope(arg_scope):
logits, _ = nets.inception.inception_v3(preprocessed, 1001, is_training=False, reuse=reuse)
logits = logits[:,1:]
probs = tf.nn.softmax(logits)
return logits, probs
#Returns logits and probabilities from the network 
logits, probs = inception(image, reuse=False)

现在,假设我有以下模型:在另一个数据集中微调的RESNET-50,我将简单地加载它的模型定义和权重:

json_file = open('/path/resnet-model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
#load weights into new model
model.load_weights("/path/weights/resnet-weights.h5")

如何制作一个类似的函数,从这样一个现有的预训练模型中提取问题和逻辑?

p.s1:模型、权重和示例图像输入可以在这里找到

p.s2:像HERE这样的问题的一些现有解决方案只解释了如何获得一个或另一个。我需要一个像上面第一个一样的函数,它将为我提供从文件加载的现有训练模型的logits和probs。

IIUC,您应该能够以相同的方式直接执行此操作:

import tensorflow as tf
json_file = open('/content/resnet-model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model_json = loaded_model_json.replace('"activation":"softmax"', '"activation":"linear"')
model = tf.keras.models.model_from_json(loaded_model_json)
image = tf.keras.preprocessing.image.load_img('/content/sample-image.jpeg')
image = tf.constant([tf.keras.preprocessing.image.img_to_array(image)])
logits = model(image)
probs = tf.nn.softmax(logits)

您还可以定义一个与softmax函数相反的新模型:

def inv_softmax(x, C):
return tf.math.log(x) + C
outputs = tf.keras.layers.Lambda(lambda x : inv_softmax(x, tf.math.log(10.)),name='inv_softmax')(model.output)
new_model = tf.keras.Model(model.input, outputs) 
logits = new_model(image)
probs = tf.nn.softmax(logits)

或者去掉最后一层,用linear激活函数定义一个新层。

最新更新