0
点赞
收藏
分享

微信扫一扫

读写文件(tensorflow)

英乐 2022-02-03 阅读 57

文章目录

读写文件(tensorflow)

代码整理

加载和保存张量

import numpy as np
import tensorflow as tf

x = tf.range(4)
np.save('x-file.npy', x)

我们现在可以将存储在文件中的数据读回内存

x2 = np.load('x-file.npy', allow_pickle=True)

我们可以存储一个张量列表,然后把它们读回内存

y = tf.zeros(4)
np.save('xy-files.npy', [x, y])
x2, y2 = np.load('xy-files.npy', allow_pickle=True)
(x2, y2)

我们甚至可以写入或读取从字符串映射到张量的字典。 当我们要读取或写入模型中的所有权重时,这很方便

mydict = {'x': x, 'y': y}
np.save('mydict.npy', mydict)
mydict2 = np.load('mydict.npy', allow_pickle=True)
mydict2

加载和保存模型参数

class MLP(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.flatten = tf.keras.layers.Flatten()
        self.hidden = tf.keras.layers.Dense(units=256, activation=tf.nn.relu)
        self.out = tf.keras.layers.Dense(units=10)

    def call(self, inputs):
        x = self.flatten(inputs)
        x = self.hidden(x)
        return self.out(x)

net = MLP()
X = tf.random.uniform((2, 20))
Y = net(X)
net.save_weights('mlp.params')
clone = MLP()
clone.load_weights('mlp.params')
Y_clone = clone(X)
Y_clone == Y

小结

  • save和load函数可用于张量对象的文件读写。

  • 我们可以通过参数字典保存和加载网络的全部参数。

  • 保存架构必须在代码中完成,而不是在参数中完成。

举报

相关推荐

0 条评论