我构建了一个通用的 python 类,用于与使用“tf.saved_model.builder.SavedModelBuilder”保存的经过训练的神经网络进行交互。
当我使用给定的神经网络从类继承一次时,一切正常。然而,当我再次继承第二个具有不同架构的神经网络时, tensorflow 会抛出一个形状不适合的错误: “分配要求两个张量的形状匹配。lhs shape= [100,2] rhs shape= [400,4]”
这些形状属于两个不同的神经网络,但我不明白为什么 tensorflow 会记住第一个网络。
有没有简单的方法来解决这个问题?如果不是,在一个项目中使用多个神经网络的正确方法是什么?
这是类代码:
import tensorflow as tf
# prevents tensorflow from using GPU
config = tf.ConfigProto(
device_count={'GPU': 0}
)
class TFService():
def __init__(self, netName, inputName, outputName):
# opens a tensorflow session to use continously
self.session = tf.Session(config=config)
# loads the trained neural net
importDir = 'ocr/neural_nets/{}'.format(netName)
tf.saved_model.loader.load(
self.session,
[tf.saved_model.tag_constants.SERVING],
importDir
)
# saves the input and output tensors for the net
self.x = tf.get_default_graph().get_tensor_by_name(inputName)
self.y_pred = tf.get_default_graph().get_tensor_by_name(outputName)
def getPredictions(self, inputData):
# the object to feed the neural net
feed_dict = {self.x: inputData}
# runs the neural net and returns an array with the predictions
results = self.session.run(self.y_pred, feed_dict=feed_dict)
return results
请您参考如下方法:
对不同的网络使用不同的图表。
你可以这样做:
def __init__(self, netName, inputName, outputName):
self.graph = tf.Graph()
# opens a tensorflow session to use continously
# use self.graph as graph the the session
self.session = tf.Session(config=config, graph=self.graph)
tf.saved_model.loader.load(
self.session,
[tf.saved_model.tag_constants.SERVING],
importDir
)
# saves the input and output tensors for the net
self.x = self.graph.get_tensor_by_name(inputName)
self.y_pred = self.graph.get_tensor_by_name(outputName)
