如何从自定义神经网络模型中获取逻辑和概率

发布于 2025-01-15 19:55:30 字数 1697 浏览 0 评论 0原文

以下源代码可以从 Tensorflow 中的 imagenet 预训练模型中获取概率和 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:模型、其权重和示例图像输入可以在此处< /a>

P.s2:诸如 此处 仅解释如何获得其中之一。我需要一个类似于上面第一个函数的函数,它可以为我提供从文件加载的现有训练模型的 logits 和 probs。

The following source code could get both probabilities and logits from an imagenet pretrained model in Tensorflow

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)

Now, suppose I have the following model: a RESNET-50 fine tuned in another dataset that I will simply load its model definition and weights:

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")

How to make a similar function to take the probs and logits from such an existing pre-trained model?

P.s1: the model, its weights, and an example image input can be found HERE

P.s2: some existing solutions to questions like HERE only explain how to get one or another. I need a function like the first one above that will give me both the logits and probs from an existing trained model loaded from a file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莫言歌 2025-01-22 19:55:30

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)

或者直接删除最后一层并使用线性定义一个新层> 激活函数。

IIUC, you should be able to do this directly the same way:

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)

You could also define a new model with the reverse of a softmax function:

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)

Or just drop the last layer and define a new one with a linear activation function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文