加载tensorflow2.0模型时出现错误

时间:2020-01-15 12:52:31

标签: tensorflow2.0

我正在学习一个简单的模型以执行线性回归,然后保存模型

class NN(tf.keras.Model):
  def __init__(self):
    super(NN, self).__init__()
    L = 20
    self.W1 = tf.Variable(tf.random.truncated_normal([1, L], stddev=math.sqrt(3)))
    self.B1 = tf.Variable(tf.random.truncated_normal([1, L], stddev=1.0))
    self.W2 = tf.Variable(tf.random.truncated_normal([L, 1], stddev=math.sqrt(3/L)))
    self.B2 = tf.Variable(tf.zeros([1]))
  def call(self, inputs):
    Z1 = tf.matmul(inputs, self.W1) + self.B1
    Y1 = tf.nn.tanh(Z1)
    Y = tf.matmul(Y1, self.W2) + self.B2
    return Y

# The loss function to be optimized
def loss(model, X, Y_):
  error = model(X) - Y_
  return tf.reduce_mean(tf.square(error))

model = NN()
optimizer = tf.optimizers.Adam(learning_rate=0.001)
bsize = 20

# You can call this function in a loop to train the model, bsize samples at a time
def training_step(i):
  # read data
  x_batch, y_batch = func.next_batch(bsize)
  x_batch = np.reshape(x_batch, (bsize,1))
  y_batch = np.reshape(y_batch, (bsize,1))
  # compute training values
  loss_fn = lambda: loss(model, x_batch, y_batch)
  optimizer.minimize(loss_fn, [model.W1, model.B1, model.W2, model.B2])
  if i%5000 == 0:
    l = loss(model, x_batch, y_batch)
    print(str(i) + ": epoch: " + str(func._epochs_completed) + ": loss: " + str(l.numpy()))

for i in range(50001): 
  training_step(i)

# save the model
tf.saved_model.save(model, "my_file")

然后我试图在tensorflow文档之后用以下几行加载模型:

model = tf.saved_model.load("my_file")
f = model.signatures["serving_default"]
y = f(x)

但是我收到以下错误消息:

 f = model.signatures["serving_default"]
File "my_file/signature_serialization.py", line 195, in __getitem__
    return self._signatures[key]
KeyError: 'serving_default'

怎么了?为什么未定义serving_default?

0 个答案:

没有答案