car*_*rop 5 python tensorflow tensorflow-datasets tensorflow2.0
我试图保存一个张量数组,该数组必须使用装饰器计算到函数中@tf.function,这使得函数内的所有张量都变成张量图,因此成为不可迭代的对象。例如,在下面的最小代码中,我想知道是否可以使用函数内的代码将张量保存到文件中foo()。
@tf.function
def foo(x):
# code for saving x
a=tf.constant([1,2,3])
foo(a)
Run Code Online (Sandbox Code Playgroud)
小智 5
好吧,我假设您正在图形模式下运行该函数,否则(急切模式执行)您可以在通过.numpy()张量函数访问值后使用 NumPy 或正常的 pythonic 文件处理方式来保存值。
在图形模式下,您可以使用tf.io.write_file()操作。进一步阐述前面提到的解决方案,write_filefn 采用单个字符串。下面的例子可能会有更多帮助:
a = tf.constant([1,2,3,4,5] , dtype = tf.int32)
b = tf.constant([53.44569] , dtype= tf.float32)
c = tf.constant(0)
# if u wish to write all these tensors on each line ,
# then create a single string out of these.
one_string = tf.strings.format("{}\n{}\n{}\n", (a,b,c))
# {} is a placeholder for each element ina string and thus you would need n PH for n tensors.
# send this string to write_file fn
tf.io.write_file(filename, one_string)
Run Code Online (Sandbox Code Playgroud)
write_filefn 只接受字符串,因此您需要先将所有内容转换为字符串。此外,如果您在同一次运行中调用 write_file fn n 次,则每次调用都会覆盖先前的输出,因此 file 将包含上次调用的内容。