Tensorflow 本地加载GCMLE并获得激活

Tensorflow 本地加载GCMLE并获得激活,tensorflow,google-cloud-ml,Tensorflow,Google Cloud Ml,我想从部署到GCMLE预测服务的保存的_模型本地查看激活(比如jupyter笔记本),以便我可以进行可视化实验。我已成功将保存的\u模型加载到图形中: with tf.Session(graph=tf.Graph()) as sess: tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], _VERSION) 我还有一个输入字典request,我通常可以将其提供给部署的预测服务(predict\u

我想从部署到GCMLE预测服务的
保存的_模型
本地查看激活(比如jupyter笔记本),以便我可以进行可视化实验。我已成功将
保存的\u模型
加载到图形中:

with tf.Session(graph=tf.Graph()) as sess:
  tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], _VERSION)
我还有一个输入字典
request
,我通常可以将其提供给部署的预测服务(
predict\u json()
),为简单起见,最后包括:

responses = predict_json(project, model, instances = [request], version)
有没有什么方法可以让我在本地使用我的
保存的\u模型
,输入
请求
,然后查看特定层的激活情况(例如登录或卷积的输出)?我相信我正在尝试做的是这样的:

with tf.Session(graph=tf.Graph()) as sess:
    tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], _VERSION)
    graph = tf.get_default_graph()
    inputs = graph.get_tensor_by_name("input_layer:0")
    activations = graph.get_tensor_by_name("conv1d/bias:0")

    print(sess.run(inputs, activations))
然而,我不知道类似于
body={'instances':instances}这样的服务输入函数的等价物的张量名称
predict_json
中。此外,我只是假设如果我按名称获得卷积偏差,这将表示卷积的激活,但我对此也不肯定(因为我无法看到它们是什么)

GCMLE
predict_json()
供参考

def predict_json(project, model, instances, version=None):
"""Send json data to a deployed model for prediction.

Args:
    project (str): project where the Cloud ML Engine Model is deployed.
    model (str): model name.
    instances ([Mapping[str: Any]]): Keys should be the names of Tensors
        your deployed model expects as inputs. Values should be datatypes
        convertible to Tensors, or (potentially nested) lists of datatypes
        convertible to tensors.
    version: str, version of the model to target.
Returns:
    Mapping[str: any]: dictionary of prediction results defined by the
        model.
"""
# Create the ML Engine service object.
# To authenticate set the environment variable
# GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
service = googleapiclient.discovery.build('ml', 'v1')
name = 'projects/{}/models/{}'.format(project, model)

if version is not None:
    name += '/versions/{}'.format(version)

response = service.projects().predict(
    name=name,
    body={'instances': instances}
).execute(num_retries=2)

if 'error' in response:
    raise RuntimeError(response['error'])

return response['predictions']
def predict_json(项目、模型、实例、版本=None):
“”“将json数据发送到已部署的模型进行预测。
Args:
项目(str):部署云ML引擎模型的项目。
模型(str):模型名称。
实例([Mapping[str:Any]]):键应该是张量的名称
您部署的模型需要作为输入。值应为数据类型
可转换为张量或(可能嵌套的)数据类型列表
可转换为张量。
版本:str,目标模型的版本。
返回:
映射[str:any]:由
模型
"""
#创建ML引擎服务对象。
#要进行身份验证,请设置环境变量
#GOOGLE\u应用程序\u凭据=
service=googleapiclient.discovery.build('ml','v1')
名称='projects/{}/models/{}'。格式(项目,模型)
如果版本不是无:
名称+='/versions/{}'。格式(版本)
response=service.projects().predict(
name=name,
正文={'instances':实例}
).execute(重试次数=2)
如果响应中出现“错误”:
引发运行时错误(响应['error'])
返回响应[“预测”]

您的总体方法是正确的

您可以使用检查输入和输出的张量名称,例如(来自上述文档):

可能会输出如下内容:

The given SavedModel SignatureDef contains the following input(s):
inputs['x'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, 1)
    name: x:0
The given SavedModel SignatureDef contains the following output(s):
outputs['y'] tensor_info:
    dtype: DT_FLOAT
    shape: (-1, 1)
    name: y:0
Method name is: tensorflow/serving/predict
您可以看到输入
x
映射到张量名称
x:0

当然,查找非输入张量的名称有点困难。如果您从头开始构建图形,您可以通过向ops添加
name=“XXX”
来为张量命名。否则,您必须执行类似转储保存的模型的操作,例如

from tensorflow.core.protobuf import saved_model_pb2
s = saved_model_pb2.SavedModel()
with open("saved_model.pb") as f:
  s.ParseFromString(f.read())
print(s)
from tensorflow.core.protobuf import saved_model_pb2
s = saved_model_pb2.SavedModel()
with open("saved_model.pb") as f:
  s.ParseFromString(f.read())
print(s)