简体   繁体   English

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

[英]How to just save tensor not models in Tensorflow2

I have learned Tensorflow2 for several months but I meet some difficulty.For example,I create one tensor like:我已经学习了 Tensorflow2 几个月,但我遇到了一些困难。例如,我创建了一个像这样的张量:

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

Now I just want to save tensor v into suitable file.Actually speaking,v is created from.nc data.I use packages "netCDF4" to read it and select some variables,whose dimensions are (time,lon,lat),to concat them into v with dimensions of (time,lon,lat,var_num).现在我只想将张量v保存到合适的文件中。实际上,v是从.nc数据创建的。我使用包“netCDF4”来读取它和select一些变量,其维度是(时间,经度,纬度),来连接将它们放入尺寸为 (time,lon,lat,var_num) 的 v 中。

But v's size is large (for example,(1000,224,224,5)).So I need to save v in case of reading netcdf for many times.但是v的大小很大(例如,(1000,224,224,5))。所以我需要保存v以防多次读取netcdf。 I search some questions but little can help me because they are either about saving variables in tf1.X or saving models(or variables in models) in tf 2.我搜索了一些问题,但对我没有什么帮助,因为它们要么是关于在 tf1.X 中保存变量,要么是在 tf 2 中保存模型(或模型中的变量)。

So I come here and seek handsome persons's help.Thanks a lot in advance.所以我来这里寻求帅哥的帮助。提前非常感谢。

You can still use the saved model format to store a single tf.Variable您仍然可以使用保存的 model 格式来存储单个tf.Variable

You would just capture v in a tf.Variable then pass that to tf.saved_model.save .您只需在tf.Variable中捕获v ,然后将其传递给tf.saved_model.save

Maybe something like this:也许是这样的:

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

then to load again from the saved version:然后从保存的版本再次加载:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM