«Объяснение бета-версии gcloud ai», сообщающее об ошибках с трехмерным входным массивом для модели LSTM - PullRequest
2 голосов
/ 05 апреля 2020

У меня есть 3d модель входного кераса, которая успешно обучается, вот сводка модели:

Model: "model"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         [(None, 5, 1815)]         0         
_________________________________________________________________
bidirectional (Bidirectional (None, 5, 64)             473088    
_________________________________________________________________
bidirectional_1 (Bidirection (None, 5, 64)             24832     
_________________________________________________________________
output (TimeDistributed)     (None, 5, 25)             1625      
=================================================================
Total params: 499,545
Trainable params: 499,545
Non-trainable params: 0
_________________________________________________________________

Пост, что оценщик определен, и порция создана как:

# Convert our Keras model to an estimator
keras_estimator = tf.keras.estimator.model_to_estimator(keras_model=model, model_dir='export')

# We need this serving input function to export our model in the next cell
serving_fn = tf.estimator.export.build_raw_serving_input_receiver_fn(
    {'input_1': model.input}
)

#export the model to bucket
export_path = keras_estimator.export_saved_model(
  'gs://' + BUCKET_NAME + '/explanations',
  serving_input_receiver_fn=serving_fn
).decode('utf-8')
print(export_path)

Определение метаданных объяснения определено и скопировано в требуемое место назначения, как показано ниже:

explanation_metadata = {
    "inputs": {
      "data": {
        "input_tensor_name": "input_1:0",
        "input_baselines": [np.mean(data_X, axis=0).tolist()],
        "encoding": "bag_of_features", 
        "index_feature_mapping": feature_X.tolist()
      }
    },
    "outputs": {
      "duration": {
        "output_tensor_name": "output/Reshape_1:0"
      }
    },
  "framework": "tensorflow"
  }

# Write the json to a local file
with open('explanation_metadata.json', 'w') as output_file:
  json.dump(explanation_metadata, output_file)
!gsutil cp explanation_metadata.json $export_path

Публикуйте, что модель создана и версия определена как:

# Create the model if it doesn't exist yet (you only need to run this once)
!gcloud ai-platform models create $MODEL --enable-logging --regions=us-central1

# Create the version with gcloud
explain_method = 'integrated-gradients'
!gcloud beta ai-platform versions create $VERSION \
--model $MODEL \
--origin $export_path \
--runtime-version 1.15 \
--framework TENSORFLOW \
--python-version 3.7 \
--machine-type n1-standard-4 \
--explanation-method $explain_method \
--num-integral-steps 25

До этого шага все работает нормально , но теперь, когда я создаю и отправляю запрос объяснения как:

prediction_json = {'input_1': data_X[:5].tolist()}
with open('diag-data.json', 'w') as outfile:
  json.dump(prediction_json, outfile)

#Send the request to google cloud
!gcloud beta ai-platform explain --model $MODEL --json-instances='diag-data.json'

, я получаю следующую ошибку:

{
  "error": "Explainability failed with exception: <_InactiveRpcError of RPC that terminated with:\n\tstatus = StatusCode.INVALID_ARGUMENT\n\tdetails = \"transpose expects a vector of size 4. But input(1) is a vector of size 3\n\t [[{{node bidirectional/forward_lstm_1/transpose}}]]\"\n\tdebug_error_string = \"{\"created\":\"@1586068796.692241013\",\"description\":\"Error received from peer ipv4:10.7.252.78:8500\",\"file\":\"src/core/lib/surface/call.cc\",\"file_line\":1056,\"grpc_message\":\"transpose expects a vector of size 4. But input(1) is a vector of size 3\\n\\t [[{{node bidirectional/forward_lstm_1/transpose}}]]\",\"grpc_status\":3}\"\n>"
}

Я пытался изменить форму ввода, но ничего не получалось. Затем, чтобы проверить формат, который я попытался с помощью команды Google Cloud прогнозирования, которая изначально не работала, но работала после изменения формы ввода:

prediction_json = {'input_1': data_X[:5].reshape(-1,1815).tolist()}
with open('diag-data.json', 'w') as outfile:
  json.dump(prediction_json, outfile)

#send the predict request
!gcloud beta ai-platform predict --model $MODEL --json-instances='diag-data.json'

Сейчас я зашел в тупик с !gcloud beta ai-platform explain --model $MODEL --json-instances='diag-data.json' и ищу очень нужная помощь от сообщества SO.

Кроме того, для удобства эксперимента доступ к блокноту можно получить из google_explain_test_notebook

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...