LoginSignup
3

More than 5 years have passed since last update.

Python / numpy > list(numpy array)のファイル保存・読込

Last updated at Posted at 2017-03-27
動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 14.04 LTS desktop amd64
TensorFlow v0.11
cuDNN v5.1 for Linux
CUDA v8.0
Python 2.7.6
IPython 5.1.0 -- An enhanced Interactive Python.
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
GNU bash, version 4.3.8(1)-release (x86_64-pc-linux-gnu)

TensorFlowの学習後のinput batch, output batch, predictionの値をファイルに保存し、それを別のPython scriptから利用しようとしている。

numpyでバイナリ書き出しすることでできそうだ。

関連 numpy > ファイル読み書き > np.save() / np.load() / np.savetxt() / np.loadtxt() > バイナリ読み書き / csv読み書き

以下のコードを実装してみた。

test_python_170324a.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np

# on Python 2.7.6

# 1. save
inpbt1 = np.array([[3, 1], [4, 1], [5, 9]], dtype='f')
inpbt2 = np.array([[2, 7], [1, 8], [2, 7]], dtype='f')
inpbt3 = np.array([[6, 0], [2, 2], [10, 23]], dtype='f')
alist = list([inpbt1, inpbt2, inpbt3])
print(alist)

FILENMAE = 'test_res_170328a.npy'
np.save(FILENMAE, alist)

# 2. load
rddat = np.load(FILENMAE)
for idx, elem in enumerate(rddat):
    print('%d:%s' % (idx, elem))
結果
$ python test_python_170324a.py 
[array([[ 3.,  1.],
       [ 4.,  1.],
       [ 5.,  9.]], dtype=float32), array([[ 2.,  7.],
       [ 1.,  8.],
       [ 2.,  7.]], dtype=float32), array([[  6.,   0.],
       [  2.,   2.],
       [ 10.,  23.]], dtype=float32)]
0:[[ 3.  1.]
 [ 4.  1.]
 [ 5.  9.]]
1:[[ 2.  7.]
 [ 1.  8.]
 [ 2.  7.]]
2:[[  6.   0.]
 [  2.   2.]
 [ 10.  23.]]

上の結果はTensorFlowで学習後にprint()した時と同じデータ形式。batch_size=3, 3回iterationした例。
下の結果は保存したファイルから読み込んで出力。

np.save と np.load はファイルにndarrayを出力したり、ファイルから入力したりできる。ファイルのフォーマットはバイナリで、ファイル名の拡張子にはよく.npyを使う。 1ファイルにndarrayを1つ保存できる。

input batch, output batch, predictionをそれぞれ別のファイルに保存しようかと検討中。

しかしながら、predictionを取得していくと、その間も学習が進んでしまいそうで、weightとbiasを保存してネットワークを再構成する方がいいかもしれない。
http://qiita.com/7of9/items/ce58e66b040a0795b2ae

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3