Python 尝试从.export_savedmmodel()获取预测时遇到错误 样本数据 DNNCLassifier的列功能 还原使用.export\u savedmodel()保存的DNNCLASSIFIER模型 将tensorflow导入为tf 导出的路径='D:

Python 尝试从.export_savedmmodel()获取预测时遇到错误 样本数据 DNNCLassifier的列功能 还原使用.export\u savedmodel()保存的DNNCLASSIFIER模型 将tensorflow导入为tf 导出的路径='D:,python,tensorflow,machine-learning,Python,Tensorflow,Machine Learning,尝试从.export_savedmmodel()获取预测时遇到错误 样本数据 DNNCLassifier的列功能 还原使用.export\u savedmodel()保存的DNNCLASSIFIER模型 将tensorflow导入为tf 导出的路径='D:\\dnnclassifier\\1518769534' res_pred=[] 导入时间 从日期时间导入日期时间 开始=时间。时间() start\u time=time.strftime(“%Y-%m-%d%H:%m:%S”,time.lo

尝试从.export_savedmmodel()获取预测时遇到错误 样本数据 DNNCLassifier的列功能 还原使用.export\u savedmodel()保存的DNNCLASSIFIER模型
将tensorflow导入为tf
导出的路径='D:\\dnnclassifier\\1518769534'
res_pred=[]
导入时间
从日期时间导入日期时间
开始=时间。时间()
start\u time=time.strftime(“%Y-%m-%d%H:%m:%S”,time.localtime(start))
打印('开始时间:',开始时间)
使用tf.Session()作为sess:
#加载保存的模型
tf.saved_model.loader.load(sess,[tf.saved_model.tag_constants.service],导出的_路径)
#准备模型输入,模型期望将浮点数组传递给x
#检查第28行服务\u输入\u接收器\u fn
模型输入=tf.train.Example(特征=特征规格2)
#获取预测值,请参阅tf.contrib.predicdtor
predictor=tf.contrib.predictor.from_保存的_模型(导出的_路径)
#从模型图中获取输入张量
#名称是输入接收器函数中定义的输入张量,请参阅tf.dnn.classifier
input_tensor=tf.get_default_graph().get_tensor_by_name(“input_tensor:0”)
#获取输出dict
#不要忘记在模型_输入附近使用[],否则它会抱怨张量形状(?,)的形状()
#因为我们训练它时它的形状是(?)
model\u input=model\u input.SerializeToString()
打印(模型)
输出=预测器({“输入”:[模型输入]})
#打印(“预测为”,输出内容[‘分数])
end=time.time()
end\u time=time.strftime(“%Y-%m-%d%H:%m:%S”,time.localtime(end))
打印('结束时间:',结束时间)
遇到错误:-
开始时间:2018-02-16 14:08:05
信息:tensorflow:从b'D还原参数:\\dnnclassifier\\1518769534\\variables\\variables'
---------------------------------------------------------------------------
KeyError回溯(最近一次呼叫最后一次)
C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site packages\google\protobuf\internal\python\u message.py in\u GetFieldByName(消息描述符,字段名称)
544尝试:
-->545返回消息描述符。按字段名称[字段名称]
546除键错误外:
KeyError:“SameDevice”
在处理上述异常期间,发生了另一个异常:
ValueError回溯(最近一次调用上次)
在()
15
16
--->17型号输入=tf.train.示例(特征=特征规格2)
18
19#获取预测值,参考tf.contrib.predicdtor
C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site packages\google\protobuf\internal\python\u message.py在init中(self,**kwargs)
514新值=字段值
515如果存在(字段值,dict):
-->516新值=字段。消息类型。具体类(**字段值)
517试试:
518副本。合并自(新)
C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site packages\google\protobuf\internal\python\u message.py在init中(self,**kwargs)
482 self.\u listener\u for\u children=\u listener(self)
483对于字段\名称,kwargs.items()中的字段\值:
-->484字段=_GetFieldByName(消息描述符,字段名称)
485如果字段为无:
486 raise TypeError(“%s()获取了意外的关键字参数“%s”
C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site packages\google\protobuf\internal\python\u message.py in\u GetFieldByName(消息描述符,字段名称)
546除键错误外:
547 raise VALUERROR('协议消息%s没有“%s”字段。'%
-->548(消息描述符名称、字段名称))
549
550
ValueError:协议消息功能没有“SameDevice”字段。
尝试从存储的DNNCLASSIFIER模型获取预测时遇到以下错误
普拉班·15分钟前
特征规格2={
“Alarm_First_Notify_Delay”:tf.FixedLenFeature([X_test.Alarm_First_Notify_Delay.count()],tf.float32),
'Customer_Same':tf.FixedLenFeature([X_test.Customer_Same.count()],tf.float32),
“持续时间差异”:tf.FixedLenFeature([X_test.Duration_Difference.count()],tf.float32),
“SameDevice”:tf.FixedLenFeature([X_test.SameDevice.count()],tf.float32),
“Site_Same”:tf.FixedLenFeature([X_test.Site_Same.count()],tf.float32)
}
特征_spec2的值如下:-
{'Alarm\u First\u Notify\u Delay':FixedLenFeature(形状=[66849],数据类型=tf.float32,默认值=无),
“客户相同”:FixedLenFeature(形状=[66849],数据类型=tf.float32,默认值=无),
“持续时间差异”:FixedLenFeature(形状=[66849],数据类型=tf.float32,默认值=无),
“SameDevice”:FixedLenFeature(形状=[66849],数据类型=tf.float32,默认值=无),
'Site_Same':FixedLenFeature(shape=[66849],dtype=tf.float32,默认值=None)}
获取预测的代码
导入tensorflow作为tf
导出的路径='D:\\dnnclassifier\\1518769534'
res_pred=[]
导入时间
从日期时间导入日期时间
开始=时间。时间()
start\u time=time.strftime(“%Y-%m-%d%H:%m:%S”,time.localtime(start))
打印('开始时间:',开始时间)
使用tf.Session()作为sess:
#加载保存的模型
tf.saved_model.loader.load(sess,[tf.saved_model.tag_constants.service],导出的_路径)
#准备模型输入,模型期望将浮点数组传递给x
#检查第28行服务\u输入\u接收器\u fn
模型输入=tf.train.Example(特征=特征规格2)
#获取预测值,请参阅tf.contrib.predicdtor
predictor=tf.contrib.predictor.from_保存的_模型(导出的_路径)
#从模型图中获取输入张量
#名称是输入接收器函数中定义的输入张量,请参阅tf.dnn.classifier
input_tensor=tf.get_default_graph().get_tensor_by_name(“input_tensor:0”)
#获取输出dict
#不要忘记在模型_输入附近使用[],否则它会抱怨张量形状(?,)的形状()
#因为我们训练它时它的形状是(?)
摩登派青年
X_test.head()


Alarm_First_Notify_Delay

Duration_Difference

Customer_Same

Site_Same

SameDevice



100746
701 631 1 0 0 

87012
0 35 1 1 1 

167585
0 0 1 1 1 

178924
0 35 1 1 1 

76793
0 0 1 1 1 
  feature_spec2 = {
                   'Alarm_First_Notify_Delay': tf.FixedLenFeature([X_test.Alarm_First_Notify_Delay.count()],tf.float32),
                   'Customer_Same':tf.FixedLenFeature([X_test.Customer_Same.count()],tf.float32),
                   'Duration_Difference':tf.FixedLenFeature([X_test.Duration_Difference.count()],tf.float32),
                   'SameDevice':tf.FixedLenFeature([X_test.SameDevice.count()],tf.float32),
                   'Site_Same':tf.FixedLenFeature([X_test.Site_Same.count()],tf.float32)

               }



value of feature_spec2 is as follows :-

{'Alarm_First_Notify_Delay': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None),
 'Customer_Same': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None),
 'Duration_Difference': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None),
 'SameDevice': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None),
 'Site_Same': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None)}
import tensorflow as tf
exported_path = 'D:\\dnnclassifier\\1518769534'

res_pred =[]
import time
from datetime import datetime
start = time.time()
start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start))
print('start time : ',start_time)

with tf.Session() as sess:
     #load the saved model
     tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], exported_path)
     #Prepare model input, the model expects a float array to be passed to x
     # check line 28 serving_input_receiver_fn


     model_input= tf.train.Example(features= feature_spec2) 

       #get the predictor , refer tf.contrib.predicdtor
     predictor= tf.contrib.predictor.from_saved_model(exported_path)

       #get the input_tensor tensor from the model graph
       # name is input_tensor defined in input_receiver function refer to tf.dnn.classifier
     input_tensor=tf.get_default_graph().get_tensor_by_name("input_tensors:0")
       #get the output dict
       # do not forget [] around model_input or else it will complain shape() for Tensor shape(?,)
       # since its of shape(?,) when we trained it
     model_input=model_input.SerializeToString()
     print(model)
     output_dict= predictor({"inputs":[model_input]})
        #print(" prediction is " , output_dict['scores'])



     end = time.time()
     end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end))
     print('end time : ',end_time)

error encountered:-

start time :  2018-02-16 14:08:05
INFO:tensorflow:Restoring parameters from b'D:\\dnnclassifier\\1518769534\\variables\\variables'
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site-packages\google\protobuf\internal\python_message.py in _GetFieldByName(message_descriptor, field_name)
    544   try:
--> 545     return message_descriptor.fields_by_name[field_name]
    546   except KeyError:

KeyError: 'SameDevice'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-136-02d93ae3ed5d> in <module>()
     15 
     16 
---> 17      model_input= tf.train.Example(features= feature_spec2)
     18 
     19        #get the predictor , refer tf.contrib.predicdtor

C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site-packages\google\protobuf\internal\python_message.py in init(self, **kwargs)
    514         new_val = field_value
    515         if isinstance(field_value, dict):
--> 516           new_val = field.message_type._concrete_class(**field_value)
    517         try:
    518           copy.MergeFrom(new_val)

C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site-packages\google\protobuf\internal\python_message.py in init(self, **kwargs)
    482     self._listener_for_children = _Listener(self)
    483     for field_name, field_value in kwargs.items():
--> 484       field = _GetFieldByName(message_descriptor, field_name)
    485       if field is None:
    486         raise TypeError("%s() got an unexpected keyword argument '%s'" %

C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site-packages\google\protobuf\internal\python_message.py in _GetFieldByName(message_descriptor, field_name)
    546   except KeyError:
    547     raise ValueError('Protocol message %s has no "%s" field.' %
--> 548                      (message_descriptor.name, field_name))
    549 
    550 

ValueError: Protocol message Features has no "SameDevice" field.




encounter the below error while trying to get predictions from a stored DNNCLASSIFIER model
Plaban · 15 minutes ago
feature_spec2 = {
               'Alarm_First_Notify_Delay': tf.FixedLenFeature([X_test.Alarm_First_Notify_Delay.count()],tf.float32),
               'Customer_Same':tf.FixedLenFeature([X_test.Customer_Same.count()],tf.float32),
               'Duration_Difference':tf.FixedLenFeature([X_test.Duration_Difference.count()],tf.float32),
               'SameDevice':tf.FixedLenFeature([X_test.SameDevice.count()],tf.float32),
               'Site_Same':tf.FixedLenFeature([X_test.Site_Same.count()],tf.float32)

               }



value of feature_spec2 is as follows :-

{'Alarm_First_Notify_Delay': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None),
 'Customer_Same': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None),
 'Duration_Difference': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None),
 'SameDevice': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None),
 'Site_Same': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None)}
Code to get predictions 

import tensorflow as tf
exported_path = 'D:\\dnnclassifier\\1518769534'
res_pred =[]
import time
from datetime import datetime
start = time.time()
start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start))
print('start time : ',start_time)

with tf.Session() as sess:
     #load the saved model
     tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], exported_path)
     #Prepare model input, the model expects a float array to be passed to x
     # check line 28 serving_input_receiver_fn


     model_input= tf.train.Example(features= feature_spec2) 

       #get the predictor , refer tf.contrib.predicdtor
     predictor= tf.contrib.predictor.from_saved_model(exported_path)

       #get the input_tensor tensor from the model graph
       # name is input_tensor defined in input_receiver function refer to tf.dnn.classifier
     input_tensor=tf.get_default_graph().get_tensor_by_name("input_tensors:0")
       #get the output dict
       # do not forget [] around model_input or else it will complain shape() for Tensor shape(?,)
       # since its of shape(?,) when we trained it
     model_input=model_input.SerializeToString()
     print(model)
     output_dict= predictor({"inputs":[model_input]})
        #print(" prediction is " , output_dict['scores'])
     res_pred.append([items[0],items[1],items[2],items[3],items[4],output_dict['classes'],output_dict['scores']])


     end = time.time()
     end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end))
     print('end time : ',end_time)

error encountered:-

start time :  2018-02-16 14:08:05
INFO:tensorflow:Restoring parameters from b'D:\\dnnclassifier\\1518769534\\variables\\variables'
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site-packages\google\protobuf\internal\python_message.py in _GetFieldByName(message_descriptor, field_name)
    544   try:
--> 545     return message_descriptor.fields_by_name[field_name]
    546   except KeyError:

KeyError: 'SameDevice'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-136-02d93ae3ed5d> in <module>()
     15 
     16 
---> 17      model_input= tf.train.Example(features= feature_spec2)
     18 
     19        #get the predictor , refer tf.contrib.predicdtor

C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site-packages\google\protobuf\internal\python_message.py in init(self, **kwargs)
    514         new_val = field_value
    515         if isinstance(field_value, dict):
--> 516           new_val = field.message_type._concrete_class(**field_value)
    517         try:
    518           copy.MergeFrom(new_val)

C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site-packages\google\protobuf\internal\python_message.py in init(self, **kwargs)
    482     self._listener_for_children = _Listener(self)
    483     for field_name, field_value in kwargs.items():
--> 484       field = _GetFieldByName(message_descriptor, field_name)
    485       if field is None:
    486         raise TypeError("%s() got an unexpected keyword argument '%s'" %

C:\ProgramData\Anaconda3\envs\tfdeeplearning\lib\site-packages\google\protobuf\internal\python_message.py in _GetFieldByName(message_descriptor, field_name)
    546   except KeyError:
    547     raise ValueError('Protocol message %s has no "%s" field.' %
--> 548                      (message_descriptor.name, field_name))
    549 
    550 

ValueError: Protocol message Features has no "SameDevice" field.

Could you please advise what is wrong over here, the model was exported with same input features.