我已经使用功能性API实现了Keras模型:
x_inp, x_out = graphsage_model.in_out_tensors()
prediction = layers.Dense(units=train_targets.shape[1], activation="softmax")(x_out)
model = Model(inputs=x_inp, outputs=prediction)
model.compile(
optimizer=optimizers.Adam(lr=0.005),
loss=losses.categorical_crossentropy,
metrics=["acc"],
)
具有张量的是:
x_inp: [<tf.Tensor 'input_1:0' shape=(None, 1, 1433) dtype=float32>, <tf.Tensor 'input_2:0' shape=(None, 10, 1433) dtype=float32>, <tf.Tensor 'input_3:0' shape=(None, 50, 1433) dtype=float32>]
x_out: Tensor("lambda/Identity:0", shape=(None, 32), dtype=float32)
prediction: Tensor("dense/Identity:0", shape=(None, 7), dtype=float32)
train_targets.shape[1] = 7
据我所知,在功能API方法中,我的模型在输入层有50个单位,在隐藏层有32个单位,在输出层有7个单位。为了了解Keras的顺序模型与功能性API的工作方式不同,我尝试用顺序方法来实现:
model = models.Sequential()
model.add(layers.Dense(32, activation='softmax', input_shape=(50,)))
model.add(layers.Dense(7, activation='softmax'))
但这给了我以下错误:
ValueError:检查模型输入时出错:Numpy数组的列表 您传递给模型的信息不是模型期望的大小。 预期会看到1个数组,但得到以下3个列表 数组:
有关x_inp和x_out的计算方式的其他信息:
def in_out_tensors(self, multiplicity=None):
"""
Builds a GraphSAGE model for node or link/node pair prediction, depending on the generator used to construct
the model (whether it is a node or link/node pair generator).
Returns:
tuple: (x_inp, x_out), where ``x_inp`` is a list of Keras input tensors
for the specified GraphSAGE model (either node or link/node pair model) and ``x_out`` contains
model output tensor(s) of shape (batch_size, layer_sizes[-1])
"""
if multiplicity is None:
multiplicity = self.multiplicity
if multiplicity == 1:
return self._node_model()
elif multiplicity == 2:
return self._link_model()
else:
raise RuntimeError(
"Currently only multiplicities of 1 and 2 are supported. Consider using node_model or "
"link_model method explicitly to build node or link prediction model, respectively."
)
def _node_model(self):
"""
Builds a GraphSAGE model for node prediction
Returns:
tuple: (x_inp, x_out) where ``x_inp`` is a list of Keras input tensors
for the specified GraphSAGE model and ``x_out`` is the Keras tensor
for the GraphSAGE model output.
"""
# Create tensor inputs for neighbourhood sampling
x_inp = [
Input(shape=(s, self.input_feature_size)) for s in self.neighbourhood_sizes
]
# Output from GraphSAGE model
x_out = self(x_inp)
# Returns inputs and outputs
return x_inp, x_out