在Cloud ML部署InceptionV3模型时遇base64无效字符错误求助
Let's break down what's causing this error and walk through how to fix it:
Root Causes
Your issue stems from two key mismatches:
- Request format doesn't match your model's signature: When you saved the model, you defined the input key as
inputs, but your request is usingimage_bytes— Cloud ML can't map this to the model's input tensor. Additionally, you're passing a URL-safe Base64 string which isn't compatible with TensorFlow's decoding logic. - URL-safe Base64 isn't supported: TensorFlow's
DecodeBase64op only recognizes standard Base64 characters (+/instead of-_). Your use ofbase64.urlsafe_b64encodeintroduces invalid characters for the decoder.
Step-by-Step Fixes
1. Switch to Standard Base64 Encoding
Replace the URL-safe encoding with standard Base64 in both your local test code and request code:
# Replace this line: # encoded_string = str(base64.urlsafe_b64encode(image_file.read()),'ascii') # With this: encoded_string = str(base64.b64encode(image_file.read()), 'ascii')
2. Align Request Body with Model Signature
Your model's serving signature expects an input key named inputs (matching the tensor input_b64:0). Adjust your request body to match this structure:
Option 1: Basic Request (Single Input)
Since your input tensor has shape (1,), pass the encoded string as a single-element array:
request_body = json.dumps({ "inputs": [encoded_string] })
Option 2: Instance Format (Good for Batch Requests)
If you need to include identifiers or send multiple images, use the instances format:
request_body = json.dumps({ "instances": [ {"inputs": encoded_string} ] })
3. Verify Input Tensor Shape (Optional)
If you're still having issues, double-check your input tensor's shape to ensure your request matches:
# Add this to your local test code after loading the model input_tensor = tf.get_default_graph().get_tensor_by_name('input_b64:0') print(f"Input tensor shape: {input_tensor.shape}")
- If the shape is
(1,), keep passing an array[encoded_string] - If it's a scalar
(), pass the string directly without the array wrapper
4. Redeploy the Updated Model
Make sure you regenerate your SavedModel with the corrected encoding logic, then redeploy it to Cloud ML Engine — old model caches can sometimes cause unexpected behavior.
Full Working Request Example
Here's a complete snippet of the corrected request code:
import base64 import json import requests # Encode image with standard Base64 with open('MEL_BE_0.jpg', 'rb') as image_file: encoded_string = str(base64.b64encode(image_file.read()), 'ascii') # Build properly formatted request body request_body = json.dumps({ "inputs": [encoded_string] }) # Send request to your Cloud ML endpoint response = requests.post( "YOUR_CLOUD_ML_ENDPOINT_URL", data=request_body, headers={"Content-Type": "application/json"} ) # Check the response print(response.json())
内容的提问来源于stack exchange,提问作者sarim zafar

