Keras 中的 y 参数拟合和计算函数



Keras文档说,拟合和求值函数中的y参数可以设置为None,这实际上是默认值。(我缩短了下面的函数定义以节省一些空间。

fit(self, x=None, **y=None**,  ...)
evaluate(self, x=None, **y=None**, ...)

文档激励值None如下: "y 可以是 None(默认值(,如果从框架原生张量(例如 TensorFlow 数据张量(馈送。">

这并没有真正告诉我那么多。谁能解释一下这到底意味着什么?如果可以举一个简短的例子,将不胜感激。

提前谢谢你!

ADDENDUM1:

例如,假设以下代码段

model = ResNet50(weights='imagenet')
x = model.get_layer('flatten_1').output # layer 'flatten_1' is the last layer of the "model"
model_out = Dense(128, activation='relu',  name='model_out')(x)
model_out = Lambda(lambda  x: K.l2_normalize(x,axis=-1))(model_out)
new_model = Model(inputs=model.input, outputs=model_out)
anchor_input = Input(shape=(224, 224, 3), name='anchor_input')
pos_input = Input(shape=(224, 224, 3), name='pos_input')
neg_input = Input(shape=(224, 224, 3), name='neg_input')
encoding_anchor   = new_model(anchor_input)
encoding_pos      = new_model(pos_input)
encoding_neg      = new_model(neg_input)
loss = Lambda(triplet_loss)([encoding_anchor, encoding_pos, encoding_neg])
siamese_network = Model(inputs  = [anchor_input, pos_input, neg_input], 
outputs = loss)
siamese_network.compile(optimizer=Adam(lr=.00003), loss=identity_loss)

在此示例中,当我稍后从 Keras 运行拟合和/或评估函数时,我应该如何设置y参数?

增编2:

这是上面代码中提到的triplet_loss函数:

def triplet_loss(inputs):
anchor, positive, negative = inputs
positive_distance = K.square(anchor - positive)
negative_distance = K.square(anchor - negative)
positive_distance = K.sqrt(K.sum(positive_distance, axis=-1, keepdims=True))
negative_distance = K.sqrt(K.sum(negative_distance, axis=-1, keepdims=True))
loss = K.maximum(0.0, 2 + loss)
return K.mean(loss)

这是个好问题。尽管这不经常使用,但 Keras 允许馈送框架原生张量,而不是通过占位符馈送。请考虑以下示例:

from keras.models import Model
from keras.layers import Dense, Input
import tensorflow as tf
# TensorFlow native tensors
a = tf.random_uniform(shape=(32, 1,), maxval=1)
b = 2*a
# Keras model
x = Input(shape=(1,), tensor=a)
h = Dense(1)(x)
model = Model(x, h)
model.compile('sgd', 'mse', target_tensors=[b])
# Train + evaluate
model.fit(steps_per_epoch=1000)
print('MSE: {}'.format(model.evaluate(steps=10)))

在这里,我们通过 keras.layers.Input 中的参数tensor指定模型的输入。在这种情况下,Keras 没有定义占位符(您通常会通过 model.fit 中的参数x输入占位符(。相反,TensorFlow张量a直接连接到x。类似地,可以通过 model.compiletarget_tensors来定义目标。

当您从框架原生张量馈送时,来自 model.fit 的参数steps_per_epoch应设置为构成纪元的批次数,而来自 model.evaluate 的参数steps是用于评估模型的批次数。

最新更新