Python 如何添加';实例键';到gcloud ai平台中批量预测的keras模型输入?

Python 如何添加';实例键';到gcloud ai平台中批量预测的keras模型输入?,python,tensorflow,gcloud,Python,Tensorflow,Gcloud,我试图添加“键”以匹配Google AI平台的批量预测输出,但是我的模型输入只允许一个输入 看起来是这样的: input = tf.keras.layers.Input(shape=(max_len,)) x = tf.keras.layers.Embedding(max_words, embed_size, weights=[embedding_matrix], trainable=False)(input) x = tf.keras.layers.Bidirectional(tf.kera

我试图添加“键”以匹配Google AI平台的批量预测输出,但是我的模型输入只允许一个输入

看起来是这样的:

input = tf.keras.layers.Input(shape=(max_len,))

x = tf.keras.layers.Embedding(max_words, embed_size, weights=[embedding_matrix], trainable=False)(input)
x = tf.keras.layers.Bidirectional(tf.keras.layers.GRU(128, return_sequences=True, dropout=0.3, recurrent_dropout=0.1))(x)
x = tf.keras.layers.Conv1D(128, kernel_size=3, padding="valid", kernel_initializer="glorot_uniform")(x)

avg_pool = tf.keras.layers.GlobalAveragePooling1D()(x)
max_pool = tf.keras.layers.GlobalMaxPooling1D()(x)

x = tf.keras.layers.concatenate([avg_pool, max_pool])

preds = tf.keras.layers.Dense(2, activation="sigmoid")(x)
model = tf.keras.Model(input, preds)
model.summary()
model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(lr=1e-3), metrics=['accuracy','binary_crossentropy'])
我遇到过,但不知道如何将其应用到我的代码中


有什么想法吗?谢谢

按照您的代码,您可以执行以下操作:

首先,从输入中获取键值:

input=tf.keras.layers.input(shape=(max_len,)
key_raw=tf.keras.layers.Input(shape=(),name='key')
它将在以后用于连接

key = tf.keras.layers.Reshape((1,), input_shape=())(key_raw)
关键在于最终结果

preds = tf.keras.layers.Dense(2, activation="sigmoid")(x)
preds = tf.keras.layers.concatenate([preds, key])
将其添加到模型的输入中

model = tf.keras.Model([input, key_raw], preds)
输入json文件示例:

{"input_1": [1.2,1.1,3.3,4.3], "key":1}
{"input_1": [0.3, 0.4, 1.5, 1], "key":2}
现在,您可以将键作为预测结果的最后一个元素。 输出示例:

[0.48686566948890686, 0.5113844275474548, 1.0]
[0.505149781703949, 0.5156428813934326, 2.0]

或者,您可以将序列化的服务函数更改为SavedModel(或第二个服务函数)。这很方便,因为您可以有一个服务基础设施(即TFServing、Google Cloud AI平台在线/批量)同时为关键预测和非关键预测提供服务。此外,当您无法访问生成SavedModel的底层keras代码时,可以向SavedModel添加键

tf.saved\u model.save(model,model\u导出路径)
loaded_model=tf.keras.models.load_model(model_导出路径)
@函数(输入_签名=[tf.TensorSpec([None],dtype=tf.string),tf.TensorSpec([None,28,28],dtype=tf.float32]))
def键控_预测(键,图像):
pred=加载的_模型(图像,训练=假)
返回{
“preds”:pred,
“键”:键
}
已加载的\u model.save(键控的\u导出\u路径,签名={'SERVICED\u default':键控的\u预测})

更多示例和笔记本。

US ASCII是UTF-8的子集。将文本文件从US ASCII转换为UTF-8不会改变任何东西,因为每个ASCII文件也是一个UTF-8文件(但反之亦然)。我认为问题出在别处。你说得对。我想问题出在“钥匙”部分。我对模型的输入只接受'input_1',因此我需要调整输入以能够接受'keys'。我遇到了和,但不知道如何适应我的模型。谢谢@Tiaquetzal!我想我取得了一些成就,但仍在努力塑造preds的产量。我得到了以下错误:
在将shape(None,3)的输出作为损失'binary_crossentropy'时,传递了一个具有shape(40069,2)的目标数组。此损失期望目标与输出具有相同的形状我基本上输入两个相同长度的numpy数组,然后进行拟合:
基线模型=模型。拟合([x\u-train,x\u-train\u-array],y\u-train,validation\u-split=0.2,batch\u-size=batch\u-size,epoch=5,callbacks=callbacks,verbose=1)
y\u-train
。由于增加了键,模型的预测现在是张量
(无,3)
。因此,您必须在
y_train
中添加一个额外的列,以使
preds
与它工作的targetsGlad匹配!考虑选择答案作为选择