如何只保存张量而不是 Tensorflow2 中的模型

How to just save tensor not models in Tensorflow2

我已经学习了几个月的 Tensorflow2 但我遇到了一些 difficulty.For 示例,我创建了一个张量,例如:

import tensorflow as tf
v=tf.random.normal((20,30,40))

现在我只想将张量 v 保存到合适的 file.Actually 中,v 是从 .nc 创建的 data.I 使用包“netCDF4”读取它和 select 一些变量,其维度为 (time,lon,lat),将它们连接成维度为 (time,lon,lat,var_num) 的 v。

但是v的大小很大(比如,(1000,224,224,5))。所以我需要保存v,以防多次读取netcdf。我搜索了一些问题,但对我帮助不大,因为它们要么是关于在 tf1.X 中保存变量,要么是关于在 tf 2.

中保存模型(或模型中的变量)

所以特意来找帅哥help.Thanks提前很多

您仍然可以使用 saved model format 存储单个 tf.Variable

您只需在 tf.Variable 中捕获 v,然后将其传递给 tf.saved_model.save

也许是这样的:

v=tf.Variable(tf.random.normal((20,30,40)))
tf.saved_model.save(v, '/path/to/my_var')

然后从保存的版本再次加载:

v_from_file = tf.saved_model.load('/path/to/my_var')