Я пытаюсь написать пользовательскую процедуру прогнозирования ML на платформе AI, чтобы получить текстовые данные от клиента, выполнить некоторую пользовательскую предварительную обработку, передать ее в модель и запустить модель. Мне удалось успешно упаковать и развернуть этот код в облаке Google. Однако каждый раз, когда я пытаюсь отправить ему запрос из node.js, я получаю обратно data: { error: 'Prediction failed: unknown error.' },
.
Вот мой соответствующий код пользовательской процедуры прогнозирования. Обратите внимание, что я установил instances
для своего текста в клиенте, а затем токенизировал и предварительно обработал его в процедуре пользовательского прогнозирования.
def __init__(self, model, session, saver, dictionary):
self.model = model
self.sess = session
@classmethod
def from_path(cls, model_dir):
m = Model(learning_rate=0.1)
session = tf.Session()
session.run(tf.global_variables_initializer())
session.run(tf.local_variables_initializer())
saver = tf.train.Saver(max_to_keep=0)
saver.restore(session, (os.path.join(model_dir, 'model.ckpt')))
return cls(m, session)
def predict(self, instances, **kwargs):
utterance = nltk.word_tokenize(instances)
utterance = self.preprocess_utterance(utterance)
preds = self.sess.run([self.model['preds'], feed_dict={'input_data': utterance)
return preds
Вот мой код Node.js:
text_string = "Hello how are you?"
google.auth.getApplicationDefault(function (err, authClient, projectId) {
if (err) {
console.log('Authentication failed because of ', err);
return;
}
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
var scopes = ['https://www.googleapis.com/auth/cloud-platform'];
authClient = authClient.createScoped(scopes);
}
var request = {
name: "projects/" + projectId + "/models/classifier",
resource: {"instances": [message_string]},
// This is a "request-level" option
auth: authClient
};
machinelearning.projects.predict(request, function (err, result) {
console.log(result)
if (err) {
console.log(err);
} else {
console.log(result);
res.status(200).send('Hello, world! This is the prediction: ' + JSON.stringify(result)).end();
}
});
});
В этом коде я просто отправляю текст в модель Google Cloud. Тело запроса:
body: '{"instances":["Hello how are you?"]}',
Кто-нибудь имеет представление о том, почему он терпит неудачу?
Если нет, то кто-нибудь знает, как я могу это отладить? Неизвестное сообщение об ошибке бесполезно.
Edit:
Вот вывод saved_model_cli
с опцией --all
.
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['length_input'] tensor_info:
dtype: DT_INT32
shape: ()
name: Placeholder_3:0
inputs['seqlen'] tensor_info:
dtype: DT_INT32
shape: (-1)
name: Placeholder_2:0
inputs['indicator'] tensor_info:
dtype: DT_INT32
shape: (-1, 2)
name: Placeholder_1:0
inputs['input_data'] tensor_info:
dtype: DT_INT32
shape: (-1, -1)
name: Placeholder:0
inputs['y'] tensor_info:
dtype: DT_INT32
shape: (-1, -1)
name: Placeholder_4:0
The given SavedModel SignatureDef contains the following output(s):
outputs['preds'] tensor_info:
dtype: DT_INT32
shape: (-1, -1)
name: Cast:0
Method name is: tensorflow/serving/predict
Исходя из этого, я должен предоставить этот словарь в качестве входных данных, но он не работает.
{"instances": [ {
"input_data": [138, 30, 66],
"length_input": 1,
"indicator": [[0, 0]],
"seqlen": [3],
"y": [138, 30, 66]
}
]}