第6章構築者のための手引き
6.6.1. Loading and Saving Tensors6.6.1 テンソルの読み込みと保存
For individual tensors, we can directly invoke the
load and save functions to read and write them respectively. Both functions require that we supply a name, and save requires as input the variable to be saved.英語のヒント
個々のテンソルについては、
load関数とsave関数を直接呼び出して、それぞれ読み込みと書き込みを行える。どちらの関数も名前を与えることが必要で、saveには保存すべき変数も入力として必要である。x = torch.arange(4)
torch.save(x, 'x-file')We can now read the data from the stored file back into memory.
英語のヒント
これで、保存したファイルからデータをメモリに読み戻せる。
x2 = torch.load('x-file')
x2tensor([0, 1, 2, 3])We can store a list of tensors and read them back into memory.
英語のヒント
テンソルのリストを保存して、メモリに読み戻すこともできる。
y = torch.zeros(4)
torch.save([x, y],'x-files')
x2, y2 = torch.load('x-files')
(x2, y2)(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))We can even write and read a dictionary that maps from strings to tensors. This is convenient when we want to read or write all the weights in a model.
英語のヒント
文字列からテンソルへ対応づける辞書を書き込んで読み込むことさえできる。これは、モデルのすべての重みを読み書きしたいときに便利である。
mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
mydict2{'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}