tensorflow获取模型中间层结果及错误tf.keras.backend.function Layer ‘ + self.name + ‘ has no inbound nodes.

本文探讨了在TensorFlow中尝试获取已训练模型中间层输出时遇到的错误,包括AttributeError和'Layer has no inbound nodes'问题。错误产生的原因是模型的某些层没有输入节点。正确的做法是在构建模型时确保每个层都有输入,使得图层之间连通。通过示例代码展示了如何正确调用中间层结果,避免上述错误。
摘要由CSDN通过智能技术生成

错误使用

1、构建模型:

import tensorflow as tf
import collections
from efficientnet import tfkeras


class MyModel(tf.keras.Model):

    def __init__(self, height=None,width=None,channel=None):
        super(MyModel,self).__init__()

        self.inputshape = tf.keras.layers.InputLayer(input_shape=(height,width,channel))

        self.effnet = tfkeras.EfficientNetB0(
                include_top=False,
                weights='imagenet',
                input_shape=(height,width,channel)
        )
        self.pool = tf.keras.layers.GlobalAveragePooling2D(name="GlobalAP")
        self.dense3 = tf.keras.layers.Dense(512,activation="relu",kernel_initializer="he_normal")
        self.dense4 = tf.keras.layers.Dense(6,activation="softmax")


    def call(self, input):

        # x = self.resnet50(input)
        # print(x.shape)

        x = self.inputshape(input)
        x = self.effnet(x)
        print(x)


        x = self.pool(x)
        x = self.dense3(x)
        self.out = self.dense4(x)

        return self.out

2、调用已训练模型中间层输出

for index, (train_index, valid_index) in enumerate(kfold.split(train_data,label)):

    print("========= %d =========="%index)
    x_train, x_valid, y_train, y_valid = X_train[train_index], X_train[valid_index], Y_train[train_index], Y_train[valid_index]

    md = model.MyModel(width, height, channel)
    
    # =======================================================================
    ## 获取中间结果
    get_GlobalAveragePooling = tf.keras.backend.function([md.layers[0].input,                                                 
              tf.keras.backend.learning_phase()], [md.GlobalAP.output])
    # =====================
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值