尝试使用Keras'创建Keras模型时收到错误AttributeError: 'NoneType' object has no attribute '_inbound_nodes'
,
model = Model(inputs=input, outputs=out)
根据我对Stackoverflow上有关同一错误的其他问题的理解(例如:Q1,Q2,Q3,Q4),诀窍应该是连接input
至out
仅使用Keras图层对象,即使这意味着使用Lambda
。我很确定自己做到了。
我的代码如下:
from keras import backend as K
import keras
from keras.layers import Layer, Activation, Conv1D, Lambda, Concatenate, Add
from keras.layers.normalization import BatchNormalization
def create_resnet_model(input_shape, block_channels, repetitions, layer_class, batchnorm=False):
input = keras.Input(shape=input_shape)
x = K.identity(input)
resdim = sum(block_channels[-1]) if hasattr(block_channels[-1], "__iter__") else block_channels[-1]
def zero_pad_input(z):
pad_shape = K.concatenate([K.shape(z)[:2], [1 + resdim - input_shape[-1]]])
return K.concatenate([z, K.zeros(pad_shape)], axis=-1)
def add_mask_dim(z):
return K.concatenate([K.zeros_like(z[:, :, :1]), z], axis=-1)
padded_input = Lambda(zero_pad_input)(input)
def extract_features(z):
return z[:, :, 1:]
for block in range(repetitions):
for args in block_channels:
if not hasattr(args, "__iter__"):
args = (args, )
layer = layer_class(*args)
y = layer(x)
y_f = Lambda(extract_features)(y)
if batchnorm:
bn = BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None)
y_f = bn(y_f)
y_f = Activation("relu")(y_f)
y = Lambda(add_mask_dim)(y_f)
if block == 0:
x = Add()([y, padded_input])
else:
x = Add()([x, y])
out = Conv1D(filters=1, kernel_size=1, activation="linear", padding="same")(x)
model = keras.Model(inputs=input, outputs=out)
return model
layer_class
是Keras图层模块。因此在我看来,从ìnput
到out
的所有事物都使用Keras图层进行了转换。即使是添加内容,我也使用Add
。
答案 0 :(得分:0)
我发现了问题。
x = K.identity(input)
不是Keras图层!
将该行更改为
def identity(z):
return z
x = Lambda(identity)(input)
解决了问题。