qiitaの記事を参考に、画像認識のプログラムを作成したいと思っています。
記事の内容をコピーして動かしてみたところ、MemoryErrorが表示されてしまいました。
原因ですが、記事中では画像数は500枚程度と記載があったのですが、
今回検証で利用した画像数が8000枚程度あるためではないかと考えています。
メモリ負荷を軽減するために、どのような工夫をすれば良いか、
ご教示いただけますと幸いです。
#ラベリングによる学習/検証データの準備 from PIL import Image import os, glob import numpy as np import random, math #画像が保存されているルートディレクトリのパス root_dir = r"C:\Users\python\cnn" # 商品名 categories = ["UP","DOWN","YOKO"] # 画像データ用配列 X = [] # ラベルデータ用配列 Y = [] #画像データごとにadd_sample()を呼び出し、X,Yの配列を返す関数 def make_sample(files): global X, Y X = [] Y = [] for cat, fname in files: add_sample(cat, fname) return np.array(X), np.array(Y) #渡された画像データを読み込んでXに格納し、また、 #画像データに対応するcategoriesのidxをY格納する関数 def add_sample(cat, fname): img = Image.open(fname) img = img.convert("RGB") img = img.resize((150, 150)) data = np.asarray(img) X.append(data) Y.append(cat) #全データ格納用配列 allfiles = [] #カテゴリ配列の各値と、それに対応するidxを認識し、全データをallfilesにまとめる for idx, cat in enumerate(categories): image_dir = root_dir + "/" + cat files = glob.glob(image_dir + "/*.png") for f in files: allfiles.append((idx, f)) #シャッフル後、学習データと検証データに分ける random.shuffle(allfiles) th = math.floor(len(allfiles) * 0.8) train = allfiles[0:th] test = allfiles[th:] X_train, y_train = make_sample(train) X_test, y_test = make_sample(test) xy = (X_train, X_test, y_train, y_test) #データを保存する(データの名前を「tea_data.npy」としている) np.save(r"C:\Users\python\cnn\save_data\tea_data.npy", xy)
以下、エラー文です
--------------------------------------------------------------------------- MemoryError Traceback (most recent call last) <ipython-input-3-ad173c75b3a6> in <module>() 54 xy = (X_train, X_test, y_train, y_test) 55 #データを保存する(データの名前を「tea_data.npy」としている) ---> 56 np.save(r"C:\Users\python\cnn\save_data\tea_data.npy", xy) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\npyio.py in save(file, arr, allow_pickle, fix_imports) 527 arr = np.asanyarray(arr) 528 format.write_array(fid, arr, allow_pickle=allow_pickle, --> 529 pickle_kwargs=pickle_kwargs) 530 finally: 531 if own_fid: ~\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\format.py in write_array(fp, array, version, allow_pickle, pickle_kwargs) 627 if pickle_kwargs is None: 628 pickle_kwargs = {} --> 629 pickle.dump(array, fp, protocol=2, **pickle_kwargs) 630 elif array.flags.f_contiguous and not array.flags.c_contiguous: 631 if isfileobj(fp): MemoryError:
回答1件
あなたの回答
tips
プレビュー