You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow构建多2D卷积子网模型时遇Graph Disconnected错误求助

解决TensorFlow模型构建中的“Graph Disconnected”错误

问题根源

你遇到的“Graph Disconnected”错误,核心原因是子网络函数S2D_CNN_SLICE_SUB_NETWORK内部自行创建了Input层,导致每个子网络都是独立的计算图,和主模型的输入张量没有关联,最终拼接时整个模型的数据流完全断开。

修复方案

修改子网络函数,让它接收外部传入的输入张量,而非在内部创建新的Input。这样所有子网络都会复用主模型的输入,保证数据流全程连通。

修复后的完整代码

import tensorflow as tf
from keras.models import Model
from keras.layers import Activation, Input, concatenate, BatchNormalization 
from keras.layers import Conv3D, UpSampling3D, Conv3DTranspose, MaxPooling3D,AveragePooling3D,GlobalAveragePooling3D, MaxPooling2D, GlobalAveragePooling2D, Conv2D
from keras.layers import add
from keras.layers import LeakyReLU, Reshape, Lambda
from keras.initializers import RandomNormal
from keras.layers import Flatten
from keras.layers import Dense
from tensorflow import keras
import numpy as np
import os 

def myConv2DBlock(x_in, nf, strides=1, kernel_size = 3):
    """
    specific convolution module including convolution followed by leakyrelu
    """
    x_out = Conv2D(nf, kernel_size=3, padding='same',kernel_initializer='he_normal', strides=strides)(x_in)
    x_out = BatchNormalization()(x_out)
    x_out = LeakyReLU(0.2)(x_out)
    x_out = MaxPooling2D(pool_size= (2,2),strides=2)(x_out)
    return x_out

# 修改子网络:不再内部创建Input,改为接收外部输入张量
def S2D_CNN_SLICE_SUB_NETWORK(input_tensor):
    layer = myConv2DBlock(input_tensor, nf = 8)  
    layer = myConv2DBlock(layer, nf = 32)
    layer = myConv2DBlock(layer, nf = 64)
    layer = myConv2DBlock(layer, nf = 128)
    layer = GlobalAveragePooling2D()(layer)
        
    return layer

# 主模型:创建统一输入,传递给所有子网络
def S2D_CNN_NETWORK(vol_size, num_slices):
    inputs = Input(shape=vol_size)
    slice_networks = []
    for i in range(num_slices):
        # 将主模型的输入传入子网络,复用同一数据流起点
        slice_networks.append(S2D_CNN_SLICE_SUB_NETWORK(inputs))
    layer = concatenate(slice_networks)
    layer = Dense(128, activation='relu')(layer)
    layer = Dense(8, activation='relu')(layer)
    model = Model(inputs=[inputs], outputs=[layer])
    
    return model

# 测试模型
testModel = S2D_CNN_NETWORK((128,128,1), 1)
testModel.summary()
keras.utils.plot_model(testModel, show_shapes=True)

关键修改说明

  • 子网络函数调整:删除S2D_CNN_SLICE_SUB_NETWORK内的独立Input创建逻辑,改为接收外部传入的input_tensor参数,直接对共享输入进行处理。
  • 主模型传参优化:在循环创建子网络时,将主模型的inputs传递给每个子网络,确保所有分支的数据流都从同一个输入源出发,最终形成完整连通的计算图。

内容的提问来源于stack exchange,提问作者Steven Dew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 08:42:21