Keras的文档中提到,fit和evaluate函数中的y参数可以设置为None,这实际上是默认值。(为了节省空间,我简化了下面的函数定义。)
fit(self, x=None, **y=None**, ...)evaluate(self, x=None, **y=None**, ...)
文档中对None值的解释如下:“y可以是None(默认值),如果是从框架原生张量(例如TensorFlow数据张量)中馈送数据。”
这并没有真正告诉我太多信息。能有人解释一下这到底是什么意思吗?如果可能的话,给出一个简短的例子将非常受欢迎。
提前感谢!
补充1:
例如,假设以下代码片段
model = ResNet50(weights='imagenet')x = model.get_layer('flatten_1').output # 层'flatten_1'是“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的fit和/或evaluate函数时,我应该如何设置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 Modelfrom keras.layers import Dense, Inputimport tensorflow as tf# TensorFlow原生张量a = tf.random_uniform(shape=(32, 1,), maxval=1)b = 2*a# Keras模型x = Input(shape=(1,), tensor=a)h = Dense(1)(x)model = Model(x, h)model.compile('sgd', 'mse', target_tensors=[b])# 训练 + 评估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.compile的target_tensors
参数定义目标。
当你从框架原生张量中馈送数据时,model.fit的steps_per_epoch
参数应设置为构成一个epoch的批次数量,而model.evaluate的steps
参数则是用于评估模型的批次数量。