tf2.X中将模型保存为savedmodel

背景

将一个计算欧式距离的小模型转换为savedmodel。

代码

import tensorflow as tf


class EuclideanDisTanceNet(tf.keras.Model):
  def __init__(self):
    super(EuclideanDisTanceNet, self).__init__()
    

  def call(self, input):
    sub = tf.subtract(input[0], input[1])
    print('sub>', sub)
    pow = tf.pow(sub, 2)
    print('pow>', pow)
    rd = tf.reduce_sum(pow, axis=3)
    print('rd>', rd)
    sq = tf.math.sqrt(rd)
    return sq


input1 = tf.constant(3, dtype=tf.float32, shape=[1, 1, 500, 512])   
input2 = tf.constant(1, dtype=tf.float32, shape=[1, 1, 1, 512])

model = EuclideanDisTanceNet()

# out = model([input1, input2])
# print("out>", out)


out = model.predict([input1, input2])
print("out>", out)
model.save("./savedmodle", include_optimizer=False)

特别注意

如果没有调用predict(),则上面的代码会报错:

cannot be saved because the input shapes have not been set. Usually, input shapes are automatically determined from calling `.fit()` or `.predict()`. To manually set the shapes, call `model.build(input_shape)`.

参考资料

在 TensorFlow 2 中使用 TF Hub 中的 SavedModel

tensorflow2.x:构建tf.keras.Model实例的几种方式

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值