从Tensorflow模型中分别返回层激活和权重的线程中

2024-05-12 23:20:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个线程(使用keras.models.model_源于_json加载权重)并在另一个web服务器上运行(使用predict)。如何还可以提供来自隐藏层和网络权重的输出?在

在一些尝试通过创建如下模型来预测中间层模型时,我得到了一个错误,包括“张量不是这个图的一个元素”。在

for modelLayer in mModel.layers:
    if not modelLayer.output == mModel.input:
        intermediateModel = keras.models.Model(inputs=mModel.input, outputs=modelLayer.output)
        layerActivations = intermediateModel.predict(np.array([inputs]))[0]

当尝试使用源线程中生成的会话获取权重时(mSess

^{pr2}$

我得到了一个错误:

FailedPreconditionError (see above for traceback): Error while reading resource variable dense/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense/kernel)

[[Node: dense/kernel/Read/ReadVariableOp = ReadVariableOpdtype=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]]

尝试使用新会话和适当的图形返回层权重

sess = tf.Session(graph=mModel.output.graph)
sess.run(tf.global_variables_initializer())
mModel.layers[1].weights[0].eval(session=sess)

我得到了一个错误:

ValueError: Fetch argument cannot be interpreted as a Tensor. (Operation name: "init" op: "NoOp" is not an element of this graph.)


Tags: localhostoutputmodels错误not线程kernelpredict
1条回答
网友
1楼 · 发布于 2024-05-12 23:20:47

“张量不是该图的一个元素”的错误可以通过使用模型中与张量相关联的图来解决。在

with mModel.output.graph.as_default():
    for modelLayer in mModel.layers:
        if not modelLayer.output == mModel.input:
            intermediateModel = keras.models.Model(inputs=mModel.input, outputs=modelLayer.output)
            layerActivations = intermediateModel.predict(np.array([inputs]))[0]

编辑:更新的解决方案

虽然下面的原始解决方案解决了报告的问题,但使用…eval(sess)为权重提供的值是初始化值,而不是学习值或预测使用的值。也许有一种方法可以使用eval来获得正确的结果,但我并不知道。我发现的另一种解决方案是在模型或层上使用get_weights(),如:

^{pr2}$

原始解决方案

解决权重的问题是使用适当的图和使用权重的初始值设定项而不是全局初始值设定项初始化会话的组合。在

^{3}$

这些解决方案跨线程工作。在

相关问题 更多 >